diff --git "a/data/chunks.jsonl" "b/data/chunks.jsonl" --- "a/data/chunks.jsonl" +++ "b/data/chunks.jsonl" @@ -852,6 +852,30 @@ {"id": "fastapi/_compat/v2.py::get_flat_models_from_fields::L478", "text": "# File: fastapi/_compat/v2.py | Symbol: get_flat_models_from_fields\ndef get_flat_models_from_fields(\n fields: Sequence[ModelField], known_models: TypeModelSet\n) -> TypeModelSet:\n for field in fields:\n get_flat_models_from_field(field, known_models=known_models)\n return known_models", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_flat_models_from_fields", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L478-L483", "start_line": 478, "end_line": 483} {"id": "fastapi/_compat/v2.py::_regenerate_error_with_loc::L486", "text": "# File: fastapi/_compat/v2.py | Symbol: _regenerate_error_with_loc\ndef _regenerate_error_with_loc(\n *, errors: Sequence[Any], loc_prefix: tuple[str | int, ...]\n) -> list[dict[str, Any]]:\n updated_loc_errors: list[Any] = [\n {**err, \"loc\": loc_prefix + err.get(\"loc\", ())} for err in errors\n ]\n\n return updated_loc_errors", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "_regenerate_error_with_loc", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L486-L493", "start_line": 486, "end_line": 493} {"id": "fastapi/_compat/v2.py::", "text": "# File: fastapi/_compat/v2.py | Symbol: \nimport re\nimport warnings\nfrom collections.abc import Sequence\nfrom copy import copy\nfrom dataclasses import dataclass, is_dataclass\nfrom enum import Enum\nfrom functools import lru_cache\nfrom typing import (\n Annotated,\n Any,\n Literal,\n Union,\n cast,\n get_args,\n get_origin,\n)\nfrom fastapi._compat import lenient_issubclass, shared\nfrom fastapi.openapi.constants import REF_TEMPLATE\nfrom fastapi.types import IncEx, ModelNameMap, UnionType\nfrom pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model\nfrom pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError\nfrom pydantic import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation\nfrom pydantic import ValidationError as ValidationError\nfrom pydantic._internal import _typing_extra as _pydantic_typing_extra\nfrom pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined]\n GetJsonSchemaHandler as GetJsonSchemaHandler,\n)\nfrom pydantic.fields import FieldInfo as FieldInfo\nfrom pydantic.json_schema import GenerateJsonSchema as _GenerateJsonSchema\nfrom pydantic.json_schema import JsonSchemaValue as JsonSchemaValue\nfrom pydantic_core import CoreSchema as CoreSchema\nfrom pydantic_core import PydanticUndefined\nfrom pydantic_core import Url as Url\nfrom pydantic_core.core_schema import (\n with_info_plain_validator_function as with_info_plain_validator_function,\n)\nRequiredParam = PydanticUndefined\nUndefined = PydanticUndefined\n# TODO: remove when dropping support for Pydantic < v2.12.3\n_Attrs = {\n \"default\": ...,\n \"default_factory\": None,\n \"alias\": None,\n \"alias_priority\": None,\n \"validation_alias\": None,\n \"serialization_alias\": None,\n \"title\": None,\n \"field_title_generator\": None,\n \"description\": None,\n \"examples\": None,\n \"exclude\": None,\n \"exclude_if\": None,\n \"discriminator\": None,\n \"deprecated\": None,\n \"json_schema_extra\": None,\n \"frozen\": None,\n \"validate_default\": None,\n \"repr\": True,\n \"init\": None,\n \"init_var\": None,\n \"kw_only\": None,\n}\n# TODO: remove when dropping support for Pydantic < v2.12.3\n# Duplicate of several schema functions from Pydantic v1 to make them compatible with\n# Pydantic v2 and allow mixing the models\nTypeModelOrEnum = type[\"BaseModel\"] | type[Enum]\nTypeModelSet = set[TypeModelOrEnum]", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L1-L422", "start_line": 1, "end_line": 422} +{"id": "fastapi/applications.py::FastAPI.__init__::L58", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.__init__\ndef __init__(\n self: AppType,\n *,\n debug: Annotated[\n bool,\n Doc(\n \"\"\"\n Boolean indicating if debug tracebacks should be returned on server\n errors.\n\n Read more in the\n [Starlette docs for Applications](https://www.starlette.dev/applications/#instantiating-the-application).\n \"\"\"\n ),\n ] = False,\n routes: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n You normally wouldn't use this parameter with FastAPI, it is inherited\n from Starlette and supported for compatibility.\n\n In FastAPI, you normally would use the *path operation methods*,\n like `app.get()`, `app.post()`, etc.\n \"\"\"\n ),\n ] = None,\n title: Annotated[\n str,\n Doc(\n \"\"\"\n The title of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(title=\"ChimichangApp\")\n ```\n \"\"\"\n ),\n ] = \"FastAPI\",\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A short summary of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(summary=\"Deadpond's favorite app. Nuff said.\")\n ```\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str,\n Doc(\n '''\n A description of the API. Supports Markdown (using\n [CommonMark syntax](https://commonmark.org/)).\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n description=\"\"\"\n ChimichangApp API helps you do awesome stuff. 🚀\n\n ## Items\n\n You can **read items**.\n\n ## Users\n\n You will be able to:\n\n * **Create users** (_not implemented_).\n * **Read users** (_not implemented_).\n\n \"\"\"\n )\n ```\n '''\n ),\n ] = \"\",\n version: Annotated[\n str,\n Doc(\n \"\"\"\n The version of the API.\n\n **Note** This is the version of your application, not the version of\n the OpenAPI specification nor the version of FastAPI being used.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(version=\"0.0.1\")\n ```\n \"\"\"\n ),\n ] = \"0.1.0\",\n openapi_url: Annotated[\n str | None,\n Doc(\n \"\"\"\n The URL where the OpenAPI schema will be served from.\n\n If you set it to `None`, no OpenAPI schema will be served publicly, and\n the default automatic endpoints `/docs` and `/redoc` will also be\n disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(openapi_url=\"/api/v1/openapi.json\")\n ```\n \"\"\"\n ),\n ] = \"/openapi.json\",\n openapi_tags: Annotated[\n list[dict[str, Any]] | None,\n Doc(\n \"\"\"\n A list of tags used by OpenAPI, these are the same `tags` you can set\n in the *path operations*, like:\n\n * `@app.get(\"/users/\", tags=[\"users\"])`\n * `@app.get(\"/items/\", tags=[\"items\"])`\n\n The order of the tags can be used to specify the order shown in\n tools like Swagger UI, used in the automatic path `/docs`.\n\n It's not required to specify all the tags used.\n\n The tags that are not declared MAY be organized randomly or based\n on the tools' logic. Each tag name in the list MUST be unique.\n\n The value of each item is a `dict` containing:\n\n * `name`: The name of the tag.\n * `description`: A short description of the tag.\n [CommonMark syntax](https://commonmark.org/) MAY be used for rich\n text representation.\n * `externalDocs`: Additional external documentation for this tag. If\n provided, it would contain a `dict` with:\n * `description`: A short description of the target documentation.\n [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `url`: The URL for the target documentation. Value MUST be in\n the form of a URL.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n tags_metadata = [\n {\n \"name\": \"users\",\n \"description\": \"Operations with users. The **login** logic is also here.\",\n },\n {\n \"name\": \"items\",\n \"description\": \"Manage items. So _fancy_ they have their own docs.\",\n \"externalDocs\": {\n \"description\": \"Items external docs\",\n \"url\": \"https://fastapi.tiangolo.com/\",\n },\n },\n ]\n\n app = FastAPI(openapi_tags=tags_metadata)\n ```\n \"\"\"\n ),\n ] = None,\n servers: Annotated[\n list[dict[str, str | Any]] | None,\n Doc(\n \"\"\"\n A `list` of `dict`s with connectivity information to a target server.\n\n You would use it, for example, if your application is served from\n different domains and you want to use the same Swagger UI in the\n browser to interact with each of them (instead of having multiple\n browser tabs open). Or if you want to leave fixed the possible URLs.\n\n If the servers `list` is not provided, or is an empty `list`, the\n `servers` property in the generated OpenAPI will be:\n\n * a `dict` with a `url` value of the application's mounting point\n (`root_path`) if it's different from `/`.\n * otherwise, the `servers` property will be omitted from the OpenAPI\n schema.\n\n Each item in the `list` is a `dict` containing:\n\n * `url`: A URL to the target host. This URL supports Server Variables\n and MAY be relative, to indicate that the host location is relative\n to the location where the OpenAPI document is being served. Variable\n substitutions will be made when a variable is named in `{`brackets`}`.\n * `description`: An optional string describing the host designated by\n the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `variables`: A `dict` between a variable name and its value. The value\n is used for substitution in the server's URL template.\n\n Read more in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n servers=[\n {\"url\": \"https://stag.example.com\", \"description\": \"Staging environment\"},\n {\"url\": \"https://prod.example.com\", \"description\": \"Production environment\"},\n ]\n )\n ```\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of global dependencies, they will be applied to each\n *path operation*, including in sub-routers.\n\n Read more about it in the\n [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import func_dep_1, func_dep_2\n\n app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])\n ```\n \"\"\"\n ),\n ] = None,\n default_response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n app = FastAPI(default_response_class=ORJSONResponse)\n ```\n \"\"\"\n ),\n ] = Default(JSONResponse),\n redirect_slashes: Annotated[\n bool,\n Doc(\n \"\"\"\n Whether to detect and redirect slashes in URLs when the client doesn't\n use the same format.\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(redirect_slashes=True) # the default\n\n @app.get(\"/items/\")\n async def read_items():\n return [{\"item_id\": \"Foo\"}]\n ```\n\n With this app, if a client goes to `/items` (without a trailing slash),\n they will be automatically redirected with an HTTP status code of 307\n to `/items/`.\n \"\"\"\n ),\n ] = True,\n docs_url: Annotated[\n str | None,\n Doc(\n \"\"\"\n The path to the automatic interactive API documentation.\n It is handled in the browser by Swagger UI.\n\n The default URL is `/docs`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url=\"/documentation\", redoc_url=None)\n ```\n \"\"\"\n ),\n ] = \"/docs\",\n redoc_url: Annotated[\n str | None,\n Doc(\n \"\"\"\n The path to the alternative automatic interactive API documentation\n provided by ReDoc.\n\n The default URL is `/redoc`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url=\"/documentation\", redoc_url=\"redocumentation\")\n ```\n \"\"\"\n ),\n ] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Annotated[\n str | None,\n Doc(\n \"\"\"\n The OAuth2 redirect endpoint for the Swagger UI.\n\n By default it is `/docs/oauth2-redirect`.\n\n This is only used if you use OAuth2 (with the \"Authorize\" button)\n with Swagger UI.\n \"\"\"\n ),\n ] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n OAuth2 configuration for the Swagger UI, by default shown at `/docs`.\n\n Read more about the available configuration options in the\n [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).\n \"\"\"\n ),\n ] = None,\n middleware: Annotated[\n Sequence[Middleware] | None,\n Doc(\n \"\"\"\n List of middleware to be added when creating the application.\n\n In FastAPI you would normally do this with `app.add_middleware()`\n instead.\n\n Read more in the\n [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).\n \"\"\"\n ),\n ] = None,\n exception_handlers: Annotated[\n dict[\n int | type[Exception],\n Callable[[Request, Any], Coroutine[Any, Any, Response]],\n ]\n | None,\n Doc(\n \"\"\"\n A dictionary with handlers for exceptions.\n\n In FastAPI, you would normally use the decorator\n `@app.exception_handler()`.\n\n Read more in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n \"\"\"\n ),\n ] = None,\n on_startup: Annotated[\n Sequence[Callable[[], Any]] | None,\n Doc(\n \"\"\"\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n ),\n ] = None,\n on_shutdown: Annotated[\n Sequence[Callable[[], Any]] | None,\n Doc(\n \"\"\"\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n ),\n ] = None,\n lifespan: Annotated[\n Lifespan[AppType] | None,\n Doc(\n \"\"\"\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n ),\n ] = None,\n terms_of_service: Annotated[\n str | None,\n Doc(\n \"\"\"\n A URL to the Terms of Service for your API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(terms_of_service=\"http://example.com/terms/\")\n ```\n \"\"\"\n ),\n ] = None,\n contact: Annotated[\n dict[str, str | Any] | None,\n Doc(\n \"\"\"\n A dictionary with the contact information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) The name of the contact person/organization.\n * `url`: (`str`) A URL pointing to the contact information. MUST be in\n the format of a URL.\n * `email`: (`str`) The email address of the contact person/organization.\n MUST be in the format of an email address.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n contact={\n \"name\": \"Deadpoolio the Amazing\",\n \"url\": \"http://x-force.example.com/contact/\",\n \"email\": \"dp@x-force.example.com\",\n }\n )\n ```\n \"\"\"\n ),\n ] = None,\n license_info: Annotated[\n dict[str, str | Any] | None,\n Doc(\n \"\"\"\n A dictionary with the license information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The\n license name used for the API.\n * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression\n for the API. The `identifier` field is mutually exclusive of the `url`\n field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.\n * `url`: (`str`) A URL to the license used for the API. This MUST be\n the format of a URL.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n license_info={\n \"name\": \"Apache 2.0\",\n \"url\": \"https://www.apache.org/licenses/LICENSE-2.0.html\",\n }\n )\n ```\n \"\"\"\n ),\n ] = None,\n openapi_prefix: Annotated[\n str,\n Doc(\n \"\"\"\n A URL prefix for the OpenAPI URL.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n \"openapi_prefix\" has been deprecated in favor of \"root_path\", which\n follows more closely the ASGI standard, is simpler, and more\n automatic.\n \"\"\"\n ),\n ] = \"\",\n root_path: Annotated[\n str,\n Doc(\n \"\"\"\n A path prefix handled by a proxy that is not seen by the application\n but is seen by external clients, which affects things like Swagger UI.\n\n Read more about it at the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path=\"/api/v1\")\n ```\n \"\"\"\n ),\n ] = \"\",\n root_path_in_servers: Annotated[\n bool,\n Doc(\n \"\"\"\n To disable automatically generating the URLs in the `servers` field\n in the autogenerated OpenAPI using the `root_path`.\n\n Read more about it in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path_in_servers=False)\n ```\n \"\"\"\n ),\n ] = True,\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n OpenAPI callbacks that should apply to all *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n webhooks: Annotated[\n routing.APIRouter | None,\n Doc(\n \"\"\"\n Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't\n depend on specific *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.\n\n Read more about it in the\n [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark all *path operations* as deprecated. You probably don't need it,\n but it's available.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) all the *path operations* in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n swagger_ui_parameters: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Parameters to configure Swagger UI, the autogenerated interactive API\n documentation (by default at `/docs`).\n\n Read more about it in the\n [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n separate_input_output_schemas: Annotated[\n bool,\n Doc(\n \"\"\"\n Whether to generate separate OpenAPI schemas for request body and\n response body when the results would be more precise.\n\n This is particularly useful when automatically generating clients.\n\n For example, if you have a model like:\n\n ```python\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n tags: list[str] = []\n ```\n\n When `Item` is used for input, a request body, `tags` is not required,\n the client doesn't have to provide it.\n\n But when using `Item` for output, for a response body, `tags` is always\n available because it has a default value, even if it's just an empty\n list. So, the client should be able to always expect it.\n\n In this case, there would be two different schemas, one for input and\n another one for output.\n\n Read more about it in the\n [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)\n \"\"\"\n ),\n ] = True,\n openapi_external_docs: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n This field allows you to provide additional external documentation links.\n If provided, it must be a dictionary containing:\n\n * `description`: A brief description of the external documentation.\n * `url`: The URL pointing to the external documentation. The value **MUST**\n be a valid URL format.\n\n **Example**:\n\n ```python\n from fastapi import FastAPI\n\n external_docs = {\n \"description\": \"Detailed API Reference\",\n \"url\": \"https://example.com/api-docs\",\n }\n\n app = FastAPI(openapi_external_docs=external_docs)\n ```\n \"\"\"\n ),\n ] = None,\n strict_content_type: Annotated[\n bool,\n Doc(\n \"\"\"\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n \"\"\"\n ),\n ] = True,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Extra keyword arguments to be stored in the app, not used by FastAPI\n anywhere.\n \"\"\"\n ),\n ],\n ) -> None:\n self.debug = debug\n self.title = title\n self.summary = summary\n self.description = description\n self.version = version\n self.terms_of_service = terms_of_service\n self.contact = contact\n self.license_info = license_info\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n self.root_path_in_servers = root_path_in_servers\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.separate_input_output_schemas = separate_input_output_schemas\n self.openapi_external_docs = openapi_external_docs\n self.extra = extra\n self.openapi_version: Annotated[\n str,\n Doc(\n \"\"\"\n The version string of OpenAPI.\n\n FastAPI will generate OpenAPI version 3.1.0, and will output that as\n the OpenAPI version. But some tools, even though they might be\n compatible with OpenAPI 3.1.0, might not recognize it as a valid.\n\n So you could override this value to trick those tools into using\n the generated OpenAPI. Have in mind that this is a hack. But if you\n avoid using features added in OpenAPI 3.1.0, it might work for your\n use case.\n\n This is not passed as a parameter to the `FastAPI` class to avoid\n giving the false idea that FastAPI would generate a different OpenAPI\n schema. It is only available as an attribute.\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI()\n\n app.openapi_version = \"3.0.2\"\n ```\n \"\"\"\n ),\n ] = \"3.1.0\"\n self.openapi_schema: dict[str, Any] | None = None\n self._openapi_routes_version: int | None = None\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications/\"\n )\n self.webhooks: Annotated[\n routing.APIRouter,\n Doc(\n \"\"\"\n The `app.webhooks` attribute is an `APIRouter` with the *path\n operations* that will be used just for documentation of webhooks.\n\n Read more about it in the\n [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).\n \"\"\"\n ),\n ] = webhooks or routing.APIRouter()\n self.root_path = root_path or openapi_prefix\n self.state: Annotated[\n State,\n Doc(\n \"\"\"\n A state object for the application. This is the same object for the\n entire application, it doesn't change from request to request.\n\n You normally wouldn't use this in FastAPI, for most of the cases you\n would instead use FastAPI dependencies.\n\n This is simply inherited from Starlette.\n\n Read more about it in the\n [Starlette docs for Applications](https://www.starlette.dev/applications/#storing-state-on-the-app-instance).\n \"\"\"\n ),\n ] = State()\n self.dependency_overrides: Annotated[\n dict[Callable[..., Any], Callable[..., Any]],\n Doc(\n \"\"\"\n A dictionary with overrides for the dependencies.\n\n Each key is the original dependency callable, and the value is the\n actual dependency that should be called.\n\n This is for testing, to replace expensive dependencies with testing\n versions.\n\n Read more about it in the\n [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).\n \"\"\"\n ),\n ] = {}\n self.router: routing.APIRouter = routing.APIRouter(\n routes=routes,\n redirect_slashes=redirect_slashes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n lifespan=lifespan,\n default_response_class=default_response_class,\n dependencies=dependencies,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n responses=responses,\n generate_unique_id_function=generate_unique_id_function,\n strict_content_type=strict_content_type,\n )\n self.exception_handlers: dict[\n Any, Callable[[Request, Any], Response | Awaitable[Response]]\n ] = {} if exception_handlers is None else dict(exception_handlers)\n self.exception_handlers.setdefault(HTTPException, http_exception_handler)\n self.exception_handlers.setdefault(\n RequestValidationError, request_validation_exception_handler\n )\n\n # Starlette still has incorrect type specification for the handlers\n self.exception_handlers.setdefault(\n WebSocketRequestValidationError,\n websocket_request_validation_exception_handler, # type: ignore[arg-type]\n ) # ty: ignore[no-matching-overload]\n\n self.user_middleware: list[Middleware] = (\n [] if middleware is None else list(middleware)\n )\n self.middleware_stack: ASGIApp | None = None\n self.setup()", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.__init__", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L58-L1018", "start_line": 58, "end_line": 1018} +{"id": "fastapi/applications.py::FastAPI.build_middleware_stack::L1020", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.build_middleware_stack\ndef build_middleware_stack(self) -> ASGIApp:\n # Duplicate/override from Starlette to add AsyncExitStackMiddleware\n # inside of ExceptionMiddleware, inside of custom user middlewares\n debug = self.debug\n error_handler = None\n exception_handlers: dict[Any, ExceptionHandler] = {}\n\n for key, value in self.exception_handlers.items():\n if key in (500, Exception):\n error_handler = value\n else:\n exception_handlers[key] = value\n\n middleware = (\n [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]\n + self.user_middleware\n + [\n Middleware(\n ExceptionMiddleware,\n handlers=exception_handlers,\n debug=debug,\n ),\n # Add FastAPI-specific AsyncExitStackMiddleware for closing files.\n # Before this was also used for closing dependencies with yield but\n # those now have their own AsyncExitStack, to properly support\n # streaming responses while keeping compatibility with the previous\n # versions (as of writing 0.117.1) that allowed doing\n # except HTTPException inside a dependency with yield.\n # This needs to happen after user middlewares because those create a\n # new contextvars context copy by using a new AnyIO task group.\n # This AsyncExitStack preserves the context for contextvars, not\n # strictly necessary for closing files but it was one of the original\n # intentions.\n # If the AsyncExitStack lived outside of the custom middlewares and\n # contextvars were set, for example in a dependency with 'yield'\n # in that internal contextvars context, the values would not be\n # available in the outer context of the AsyncExitStack.\n # By placing the middleware and the AsyncExitStack here, inside all\n # user middlewares, the same context is used.\n # This is currently not needed, only for closing files, but used to be\n # important when dependencies with yield were closed here.\n Middleware(AsyncExitStackMiddleware),\n ]\n )\n\n app = self.router\n for cls, args, kwargs in reversed(middleware):\n app = cls(app, *args, **kwargs)\n return app", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.build_middleware_stack", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1020-L1068", "start_line": 1020, "end_line": 1068} +{"id": "fastapi/applications.py::FastAPI.openapi::L1070", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.openapi\ndef openapi(self) -> dict[str, Any]:\n \"\"\"\n Generate the OpenAPI schema of the application. This is called by FastAPI\n internally.\n\n The first time it is called it stores the result in the attribute\n `app.openapi_schema`, and next times it is called, it just returns that same\n result. To avoid the cost of generating the schema every time.\n\n If you need to modify the generated OpenAPI schema, you could modify it.\n\n Read more in the\n [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).\n \"\"\"\n routes_version = self.router._get_routes_version()\n if not self.openapi_schema or self._openapi_routes_version != routes_version:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n openapi_version=self.openapi_version,\n summary=self.summary,\n description=self.description,\n terms_of_service=self.terms_of_service,\n contact=self.contact,\n license_info=self.license_info,\n routes=self.routes,\n webhooks=self.webhooks.routes,\n tags=self.openapi_tags,\n servers=self.servers,\n separate_input_output_schemas=self.separate_input_output_schemas,\n external_docs=self.openapi_external_docs,\n )\n self._openapi_routes_version = routes_version\n return self.openapi_schema", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.openapi", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1070-L1103", "start_line": 1070, "end_line": 1103} +{"id": "fastapi/applications.py::FastAPI.setup::L1105", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.setup\ndef setup(self) -> None:\n if self.openapi_url:\n\n async def openapi(req: Request) -> JSONResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n schema = self.openapi()\n if root_path and self.root_path_in_servers:\n server_urls = {s.get(\"url\") for s in schema.get(\"servers\", [])}\n if root_path not in server_urls:\n schema = dict(schema)\n schema[\"servers\"] = [{\"url\": root_path}] + schema.get(\n \"servers\", []\n )\n return JSONResponse(schema)\n\n self.add_route(self.openapi_url, openapi, include_in_schema=False)\n if self.openapi_url and self.docs_url:\n\n async def swagger_ui_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url\n if oauth2_redirect_url:\n oauth2_redirect_url = root_path + oauth2_redirect_url\n return get_swagger_ui_html(\n openapi_url=openapi_url,\n title=f\"{self.title} - Swagger UI\",\n oauth2_redirect_url=oauth2_redirect_url,\n init_oauth=self.swagger_ui_init_oauth,\n swagger_ui_parameters=self.swagger_ui_parameters,\n )\n\n self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)\n\n if self.swagger_ui_oauth2_redirect_url:\n\n async def swagger_ui_redirect(req: Request) -> HTMLResponse:\n return get_swagger_ui_oauth2_redirect_html()\n\n self.add_route(\n self.swagger_ui_oauth2_redirect_url,\n swagger_ui_redirect,\n include_in_schema=False,\n )\n if self.openapi_url and self.redoc_url:\n\n async def redoc_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n return get_redoc_html(\n openapi_url=openapi_url, title=f\"{self.title} - ReDoc\"\n )\n\n self.add_route(self.redoc_url, redoc_html, include_in_schema=False)", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.setup", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1105-L1158", "start_line": 1105, "end_line": 1158} +{"id": "fastapi/applications.py::FastAPI.__call__::L1160", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.__call__\nasync def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n if self.root_path:\n scope[\"root_path\"] = self.root_path\n await super().__call__(scope, receive, send)", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.__call__", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1160-L1163", "start_line": 1160, "end_line": 1163} +{"id": "fastapi/applications.py::FastAPI.add_api_route::L1165", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.add_api_route\ndef add_api_route(\n self,\n path: str,\n endpoint: Callable[..., Any],\n *,\n response_model: Any = Default(None),\n status_code: int | None = None,\n tags: list[str | Enum] | None = None,\n dependencies: Sequence[Depends] | None = None,\n summary: str | None = None,\n description: str | None = None,\n response_description: str = \"Successful Response\",\n responses: dict[int | str, dict[str, Any]] | None = None,\n deprecated: bool | None = None,\n methods: list[str] | None = None,\n operation_id: str | None = None,\n response_model_include: IncEx | None = None,\n response_model_exclude: IncEx | None = None,\n response_model_by_alias: bool = True,\n response_model_exclude_unset: bool = False,\n response_model_exclude_defaults: bool = False,\n response_model_exclude_none: bool = False,\n include_in_schema: bool = True,\n response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),\n name: str | None = None,\n openapi_extra: dict[str, Any] | None = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n ) -> None:\n self.router.add_api_route(\n path,\n endpoint=endpoint,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=methods,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.add_api_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1165-L1220", "start_line": 1165, "end_line": 1220} +{"id": "fastapi/applications.py::FastAPI.frontend::L1222", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.frontend\ndef frontend(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path prefix where the frontend build should be served.\n \"\"\"\n ),\n ],\n *,\n directory: Annotated[\n str | os.PathLike[str],\n Doc(\n \"\"\"\n The directory containing the static frontend build output.\n \"\"\"\n ),\n ],\n fallback: Annotated[\n Literal[\"auto\", \"index.html\", \"404.html\"] | None,\n Doc(\n \"\"\"\n The fallback file behavior for missing frontend paths.\n \"\"\"\n ),\n ] = \"auto\",\n check_dir: Annotated[\n bool,\n Doc(\n \"\"\"\n Check that the frontend directory exists when the app is created.\n \"\"\"\n ),\n ] = True,\n ) -> None:\n \"\"\"\n Serve a static frontend build as low-priority routes.\n\n Use this for frontend tools that build static files into a directory,\n such as `dist`. **FastAPI** path operations are checked first, and\n the frontend files are checked only if no normal route matched.\n\n A typical project could look like this:\n\n ```text\n .\n ├── pyproject.toml\n ├── app\n │ ├── __init__.py\n │ └── main.py\n └── dist\n ├── index.html\n └── assets\n └── app.js\n ```\n\n Then in `app/main.py`:\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI()\n app.frontend(\"/\", directory=\"dist\")\n ```\n \"\"\"\n self.router.frontend(\n path,\n directory=directory,\n fallback=fallback,\n check_dir=check_dir,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.frontend", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1222-L1293", "start_line": 1222, "end_line": 1293} +{"id": "fastapi/applications.py::FastAPI.api_route::L1295", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.api_route\ndef api_route(\n self,\n path: str,\n *,\n response_model: Any = Default(None),\n status_code: int | None = None,\n tags: list[str | Enum] | None = None,\n dependencies: Sequence[Depends] | None = None,\n summary: str | None = None,\n description: str | None = None,\n response_description: str = \"Successful Response\",\n responses: dict[int | str, dict[str, Any]] | None = None,\n deprecated: bool | None = None,\n methods: list[str] | None = None,\n operation_id: str | None = None,\n response_model_include: IncEx | None = None,\n response_model_exclude: IncEx | None = None,\n response_model_by_alias: bool = True,\n response_model_exclude_unset: bool = False,\n response_model_exclude_defaults: bool = False,\n response_model_exclude_none: bool = False,\n include_in_schema: bool = True,\n response_class: type[Response] = Default(JSONResponse),\n name: str | None = None,\n openapi_extra: dict[str, Any] | None = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.router.add_api_route(\n path,\n func,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=methods,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.api_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1295-L1353", "start_line": 1295, "end_line": 1353} +{"id": "fastapi/applications.py::FastAPI.add_api_websocket_route::L1355", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.add_api_websocket_route\ndef add_api_websocket_route(\n self,\n path: str,\n endpoint: Callable[..., Any],\n name: str | None = None,\n *,\n dependencies: Sequence[Depends] | None = None,\n ) -> None:\n self.router.add_api_websocket_route(\n path,\n endpoint,\n name=name,\n dependencies=dependencies,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.add_api_websocket_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1355-L1368", "start_line": 1355, "end_line": 1368} +{"id": "fastapi/applications.py::FastAPI.websocket::L1370", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.websocket\ndef websocket(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n WebSocket path.\n \"\"\"\n ),\n ],\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n A name for the WebSocket. Only used internally.\n \"\"\"\n ),\n ] = None,\n *,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be used for this\n WebSocket.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n \"\"\"\n ),\n ] = None,\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Decorate a WebSocket function.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n **Example**\n\n ```python\n from fastapi import FastAPI, WebSocket\n\n app = FastAPI()\n\n @app.websocket(\"/ws\")\n async def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n while True:\n data = await websocket.receive_text()\n await websocket.send_text(f\"Message text was: {data}\")\n ```\n \"\"\"\n\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_api_websocket_route(\n path,\n func,\n name=name,\n dependencies=dependencies,\n )\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.websocket", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1370-L1433", "start_line": 1370, "end_line": 1433} +{"id": "fastapi/applications.py::FastAPI.include_router::L1435", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.include_router\ndef include_router(\n self,\n router: Annotated[routing.APIRouter, Doc(\"The `APIRouter` to include.\")],\n *,\n prefix: Annotated[str, Doc(\"An optional path prefix for the router.\")] = \"\",\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import get_token_header\n from .internal import admin\n\n app = FastAPI()\n\n app.include_router(\n admin.router,\n dependencies=[Depends(get_token_header)],\n )\n ```\n \"\"\"\n ),\n ] = None,\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark all the *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n deprecated=True,\n )\n ```\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include (or not) all the *path operations* in this router in the\n generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n include_in_schema=False,\n )\n ```\n \"\"\"\n ),\n ] = True,\n default_response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Default response class to be used for the *path operations* in this\n router.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n default_response_class=ORJSONResponse,\n )\n ```\n \"\"\"\n ),\n ] = Default(JSONResponse),\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> None:\n \"\"\"\n Include an `APIRouter` in the same app.\n\n Read more about it in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n\n from .users import users_router\n\n app = FastAPI()\n\n app.include_router(users_router)\n ```\n \"\"\"\n self.router.include_router(\n router,\n prefix=prefix,\n tags=tags,\n dependencies=dependencies,\n responses=responses,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n default_response_class=default_response_class,\n callbacks=callbacks,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.include_router", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1435-L1638", "start_line": 1435, "end_line": 1638} +{"id": "fastapi/applications.py::FastAPI.get::L1640", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.get\ndef get(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP GET operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI()\n\n @app.get(\"/items/\")\n def read_items():\n return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n ```\n \"\"\"\n return self.router.get(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.get", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1640-L2011", "start_line": 1640, "end_line": 2011} +{"id": "fastapi/applications.py::FastAPI.put::L2013", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.put\ndef put(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP PUT operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n\n @app.put(\"/items/{item_id}\")\n def replace_item(item_id: str, item: Item):\n return {\"message\": \"Item replaced\", \"id\": item_id}\n ```\n \"\"\"\n return self.router.put(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.put", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L2013-L2389", "start_line": 2013, "end_line": 2389} +{"id": "fastapi/applications.py::FastAPI.post::L2391", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.post\ndef post(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP POST operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n\n @app.post(\"/items/\")\n def create_item(item: Item):\n return {\"message\": \"Item created\"}\n ```\n \"\"\"\n return self.router.post(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.post", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L2391-L2767", "start_line": 2391, "end_line": 2767} +{"id": "fastapi/applications.py::FastAPI.delete::L2769", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.delete\ndef delete(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP DELETE operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI()\n\n @app.delete(\"/items/{item_id}\")\n def delete_item(item_id: str):\n return {\"message\": \"Item deleted\"}\n ```\n \"\"\"\n return self.router.delete(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.delete", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L2769-L3140", "start_line": 2769, "end_line": 3140} +{"id": "fastapi/applications.py::FastAPI.options::L3142", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.options\ndef options(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP OPTIONS operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI()\n\n @app.options(\"/items/\")\n def get_item_options():\n return {\"additions\": [\"Aji\", \"Guacamole\"]}\n ```\n \"\"\"\n return self.router.options(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.options", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L3142-L3513", "start_line": 3142, "end_line": 3513} +{"id": "fastapi/applications.py::FastAPI.head::L3515", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.head\ndef head(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP HEAD operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI, Response\n\n app = FastAPI()\n\n @app.head(\"/items/\", status_code=204)\n def get_items_headers(response: Response):\n response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n ```\n \"\"\"\n return self.router.head(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.head", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L3515-L3886", "start_line": 3515, "end_line": 3886} +{"id": "fastapi/applications.py::FastAPI.patch::L3888", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.patch\ndef patch(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP PATCH operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n\n @app.patch(\"/items/\")\n def update_item(item: Item):\n return {\"message\": \"Item updated in place\"}\n ```\n \"\"\"\n return self.router.patch(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.patch", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L3888-L4264", "start_line": 3888, "end_line": 4264} +{"id": "fastapi/applications.py::FastAPI.trace::L4266", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.trace\ndef trace(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[routing.APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP TRACE operation.\n\n ## Example\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI()\n\n @app.trace(\"/items/{item_id}\")\n def trace_item(item_id: str):\n return None\n ```\n \"\"\"\n return self.router.trace(\n path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.trace", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L4266-L4637", "start_line": 4266, "end_line": 4637} +{"id": "fastapi/applications.py::FastAPI.websocket_route::L4639", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.websocket_route\ndef websocket_route(\n self, path: str, name: str | None = None\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.router.add_websocket_route(path, func, name=name)\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.websocket_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L4639-L4646", "start_line": 4639, "end_line": 4646} +{"id": "fastapi/applications.py::FastAPI.on_event::L4648", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.on_event\n@deprecated(\n \"\"\"\n on_event is deprecated, use lifespan event handlers instead.\n\n Read more about it in the\n [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n )\n def on_event(\n self,\n event_type: Annotated[\n str,\n Doc(\n \"\"\"\n The type of event. `startup` or `shutdown`.\n \"\"\"\n ),\n ],\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add an event handler for the application.\n\n `on_event` is deprecated, use `lifespan` event handlers instead.\n\n Read more about it in the\n [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n \"\"\"\n return self.router.on_event(event_type) # ty: ignore[deprecated]", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.on_event", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L4648-L4675", "start_line": 4648, "end_line": 4675} +{"id": "fastapi/applications.py::FastAPI.middleware::L4677", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.middleware\ndef middleware(\n self,\n middleware_type: Annotated[\n str,\n Doc(\n \"\"\"\n The type of middleware. Currently only supports `http`.\n \"\"\"\n ),\n ],\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a middleware to the application.\n\n Read more about it in the\n [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).\n\n ## Example\n\n ```python\n import time\n from typing import Awaitable, Callable\n\n from fastapi import FastAPI, Request, Response\n\n app = FastAPI()\n\n\n @app.middleware(\"http\")\n async def add_process_time_header(\n request: Request, call_next: Callable[[Request], Awaitable[Response]]\n ) -> Response:\n start_time = time.time()\n response = await call_next(request)\n process_time = time.time() - start_time\n response.headers[\"X-Process-Time\"] = str(process_time)\n return response\n ```\n \"\"\"\n\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_middleware(BaseHTTPMiddleware, dispatch=func)\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.middleware", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L4677-L4721", "start_line": 4677, "end_line": 4721} +{"id": "fastapi/applications.py::FastAPI.exception_handler::L4723", "text": "# File: fastapi/applications.py | Class: FastAPI | Symbol: FastAPI.exception_handler\ndef exception_handler(\n self,\n exc_class_or_status_code: Annotated[\n int | type[Exception],\n Doc(\n \"\"\"\n The Exception class this would handle, or a status code.\n \"\"\"\n ),\n ],\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add an exception handler to the app.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n\n ## Example\n\n ```python\n from fastapi import FastAPI, Request\n from fastapi.responses import JSONResponse\n\n\n class UnicornException(Exception):\n def __init__(self, name: str):\n self.name = name\n\n\n app = FastAPI()\n\n\n @app.exception_handler(UnicornException)\n async def unicorn_exception_handler(request: Request, exc: UnicornException):\n return JSONResponse(\n status_code=418,\n content={\"message\": f\"Oops! {exc.name} did something. There goes a rainbow...\"},\n )\n ```\n \"\"\"\n\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_exception_handler(exc_class_or_status_code, func)\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/applications.py", "symbol": "FastAPI.exception_handler", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L4723-L4768", "start_line": 4723, "end_line": 4768} +{"id": "fastapi/applications.py::", "text": "# File: fastapi/applications.py | Symbol: \nimport os\nfrom collections.abc import Awaitable, Callable, Coroutine, Sequence\nfrom enum import Enum\nfrom typing import Annotated, Any, Literal, TypeVar\nfrom annotated_doc import Doc\nfrom fastapi import routing\nfrom fastapi.datastructures import Default, DefaultPlaceholder\nfrom fastapi.exception_handlers import (\n http_exception_handler,\n request_validation_exception_handler,\n websocket_request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError\nfrom fastapi.logger import logger\nfrom fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.params import Depends\nfrom fastapi.types import DecoratedCallable, IncEx\nfrom fastapi.utils import generate_unique_id\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.middleware.base import BaseHTTPMiddleware\nfrom starlette.middleware.errors import ServerErrorMiddleware\nfrom starlette.middleware.exceptions import ExceptionMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send\nfrom typing_extensions import deprecated\nAppType = TypeVar(\"AppType\", bound=\"FastAPI\")\nclass FastAPI(Starlette):\n \"\"\"\n `FastAPI` app class, the main entrypoint to use FastAPI.\n Read more in the\n [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).\n ## Example\n ```python\n from fastapi import FastAPI\n app = FastAPI()\n ```\n \"\"\"", "source_type": "code", "path": "fastapi/applications.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/applications.py#L1-L56", "start_line": 1, "end_line": 56} {"id": "fastapi/background.py::BackgroundTasks::L11", "text": "# File: fastapi/background.py | Symbol: BackgroundTasks\nclass BackgroundTasks(StarletteBackgroundTasks):\n \"\"\"\n A collection of background tasks that will be called after a response has been\n sent to the client.\n\n Read more about it in the\n [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).\n\n ## Example\n\n ```python\n from fastapi import BackgroundTasks, FastAPI\n\n app = FastAPI()\n\n\n def write_notification(email: str, message=\"\"):\n with open(\"log.txt\", mode=\"w\") as email_file:\n content = f\"notification for {email}: {message}\"\n email_file.write(content)\n\n\n @app.post(\"/send-notification/{email}\")\n async def send_notification(email: str, background_tasks: BackgroundTasks):\n background_tasks.add_task(write_notification, email, message=\"some notification\")\n return {\"message\": \"Notification sent in the background\"}\n ```\n \"\"\"\n\n def add_task(\n self,\n func: Annotated[\n Callable[P, Any],\n Doc(\n \"\"\"\n The function to call after the response is sent.\n\n It can be a regular `def` function or an `async def` function.\n \"\"\"\n ),\n ],\n *args: P.args,\n **kwargs: P.kwargs,\n ) -> None:\n \"\"\"\n Add a function to be called in the background after the response is sent.\n\n Read more about it in the\n [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).\n \"\"\"\n return super().add_task(func, *args, **kwargs)", "source_type": "code", "path": "fastapi/background.py", "symbol": "BackgroundTasks", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/background.py#L11-L61", "start_line": 11, "end_line": 61} {"id": "fastapi/background.py::", "text": "# File: fastapi/background.py | Symbol: \nfrom collections.abc import Callable\nfrom typing import Annotated, Any\nfrom annotated_doc import Doc\nfrom starlette.background import BackgroundTasks as StarletteBackgroundTasks\nfrom typing_extensions import ParamSpec\nP = ParamSpec(\"P\")", "source_type": "code", "path": "fastapi/background.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/background.py#L1-L8", "start_line": 1, "end_line": 8} {"id": "fastapi/cli.py::main::L8", "text": "# File: fastapi/cli.py | Symbol: main\ndef main() -> None:\n if not cli_main: # type: ignore[truthy-function]\n message = 'To use the fastapi command, please install \"fastapi[standard]\":\\n\\n\\tpip install \"fastapi[standard]\"\\n'\n print(message)\n raise RuntimeError(message) # noqa: B904\n cli_main()", "source_type": "code", "path": "fastapi/cli.py", "symbol": "main", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/cli.py#L8-L13", "start_line": 8, "end_line": 13} @@ -1019,6 +1043,93 @@ {"id": "fastapi/responses.py::UJSONResponse::L39", "text": "# File: fastapi/responses.py | Symbol: UJSONResponse\n@deprecated(\n \"UJSONResponse is deprecated, FastAPI now serializes data directly to JSON \"\n \"bytes via Pydantic when a return type or response model is set, which is \"\n \"faster and doesn't need a custom response class. Read more in the FastAPI \"\n \"docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model \"\n \"and https://fastapi.tiangolo.com/tutorial/response-model/\",\n category=FastAPIDeprecationWarning,\n stacklevel=2,\n)\nclass UJSONResponse(JSONResponse):\n \"\"\"JSON response using the ujson library to serialize data to JSON.\n\n **Deprecated**: `UJSONResponse` is deprecated. FastAPI now serializes data\n directly to JSON bytes via Pydantic when a return type or response model is\n set, which is faster and doesn't need a custom response class.\n\n Read more in the\n [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model)\n and the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n\n **Note**: `ujson` is not included with FastAPI and must be installed\n separately, e.g. `pip install ujson`.\n \"\"\"\n\n def render(self, content: Any) -> bytes:\n assert ujson is not None, \"ujson must be installed to use UJSONResponse\"\n return ujson.dumps(content, ensure_ascii=False).encode(\"utf-8\")", "source_type": "code", "path": "fastapi/responses.py", "symbol": "UJSONResponse", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/responses.py#L39-L66", "start_line": 39, "end_line": 66} {"id": "fastapi/responses.py::ORJSONResponse::L69", "text": "# File: fastapi/responses.py | Symbol: ORJSONResponse\n@deprecated(\n \"ORJSONResponse is deprecated, FastAPI now serializes data directly to JSON \"\n \"bytes via Pydantic when a return type or response model is set, which is \"\n \"faster and doesn't need a custom response class. Read more in the FastAPI \"\n \"docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model \"\n \"and https://fastapi.tiangolo.com/tutorial/response-model/\",\n category=FastAPIDeprecationWarning,\n stacklevel=2,\n)\nclass ORJSONResponse(JSONResponse):\n \"\"\"JSON response using the orjson library to serialize data to JSON.\n\n **Deprecated**: `ORJSONResponse` is deprecated. FastAPI now serializes data\n directly to JSON bytes via Pydantic when a return type or response model is\n set, which is faster and doesn't need a custom response class.\n\n Read more in the\n [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model)\n and the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n\n **Note**: `orjson` is not included with FastAPI and must be installed\n separately, e.g. `pip install orjson`.\n \"\"\"\n\n def render(self, content: Any) -> bytes:\n assert orjson is not None, \"orjson must be installed to use ORJSONResponse\"\n return orjson.dumps(\n content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY\n )", "source_type": "code", "path": "fastapi/responses.py", "symbol": "ORJSONResponse", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/responses.py#L69-L98", "start_line": 69, "end_line": 98} {"id": "fastapi/responses.py::", "text": "# File: fastapi/responses.py | Symbol: \nimport importlib\nfrom typing import Any, Protocol, cast\nfrom fastapi.exceptions import FastAPIDeprecationWarning\nfrom fastapi.sse import EventSourceResponse as EventSourceResponse # noqa\nfrom starlette.responses import FileResponse as FileResponse # noqa\nfrom starlette.responses import HTMLResponse as HTMLResponse # noqa\nfrom starlette.responses import JSONResponse as JSONResponse # noqa\nfrom starlette.responses import PlainTextResponse as PlainTextResponse # noqa\nfrom starlette.responses import RedirectResponse as RedirectResponse # noqa\nfrom starlette.responses import Response as Response # noqa\nfrom starlette.responses import StreamingResponse as StreamingResponse # noqa\nfrom typing_extensions import deprecated\ntry:\n ujson = cast(_UjsonModule, importlib.import_module(\"ujson\"))\nexcept ModuleNotFoundError: # pragma: nocover\n ujson = None # type: ignore[assignment]\ntry:\n orjson = cast(_OrjsonModule, importlib.import_module(\"orjson\"))\nexcept ModuleNotFoundError: # pragma: nocover\n orjson = None # type: ignore[assignment]", "source_type": "code", "path": "fastapi/responses.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/responses.py#L1-L36", "start_line": 1, "end_line": 36} +{"id": "fastapi/routing.py::request_response::L113", "text": "# File: fastapi/routing.py | Symbol: request_response\ndef request_response(\n func: Callable[[Request], Awaitable[Response] | Response],\n) -> ASGIApp:\n \"\"\"\n Takes a function or coroutine `func(request) -> response`,\n and returns an ASGI application.\n \"\"\"\n f: Callable[[Request], Awaitable[Response]] = (\n func # type: ignore[assignment]\n if is_async_callable(func)\n else functools.partial(run_in_threadpool, func) # type: ignore[call-arg]\n ) # ty: ignore[invalid-assignment]\n\n async def app(scope: Scope, receive: Receive, send: Send) -> None:\n request = Request(scope, receive, send)\n\n async def app(scope: Scope, receive: Receive, send: Send) -> None:\n # Starts customization\n response_awaited = False\n async with AsyncExitStack() as request_stack:\n scope[\"fastapi_inner_astack\"] = request_stack\n async with AsyncExitStack() as function_stack:\n scope[\"fastapi_function_astack\"] = function_stack\n response = await f(request)\n await response(scope, receive, send)\n # Continues customization\n response_awaited = True\n if not response_awaited:\n raise FastAPIError(\n \"Response not awaited. There's a high chance that the \"\n \"application code is raising an exception and a dependency with yield \"\n \"has a block with a bare except, or a block with except Exception, \"\n \"and is not raising the exception again. Read more about it in the \"\n \"docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except\"\n )\n\n # Same as in Starlette\n await wrap_app_handling_exceptions(app, request)(scope, receive, send)\n\n return app", "source_type": "code", "path": "fastapi/routing.py", "symbol": "request_response", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L113-L152", "start_line": 113, "end_line": 152} +{"id": "fastapi/routing.py::websocket_session::L157", "text": "# File: fastapi/routing.py | Symbol: websocket_session\ndef websocket_session(\n func: Callable[[WebSocket], Awaitable[None]],\n) -> ASGIApp:\n \"\"\"\n Takes a coroutine `func(session)`, and returns an ASGI application.\n \"\"\"\n # assert asyncio.iscoroutinefunction(func), \"WebSocket endpoints must be async\"\n\n async def app(scope: Scope, receive: Receive, send: Send) -> None:\n session = WebSocket(scope, receive=receive, send=send)\n\n async def app(scope: Scope, receive: Receive, send: Send) -> None:\n async with AsyncExitStack() as request_stack:\n scope[\"fastapi_inner_astack\"] = request_stack\n async with AsyncExitStack() as function_stack:\n scope[\"fastapi_function_astack\"] = function_stack\n await func(session)\n\n # Same as in Starlette\n await wrap_app_handling_exceptions(app, session)(scope, receive, send)\n\n return app", "source_type": "code", "path": "fastapi/routing.py", "symbol": "websocket_session", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L157-L178", "start_line": 157, "end_line": 178} +{"id": "fastapi/routing.py::_AsyncLiftContextManager::L185", "text": "# File: fastapi/routing.py | Symbol: _AsyncLiftContextManager\nclass _AsyncLiftContextManager(AbstractAsyncContextManager[_T]):\n \"\"\"\n Wraps a synchronous context manager to make it async.\n\n This is vendored from Starlette to avoid importing private symbols.\n \"\"\"\n\n def __init__(self, cm: AbstractContextManager[_T]) -> None:\n self._cm = cm\n\n async def __aenter__(self) -> _T:\n return self._cm.__enter__()\n\n async def __aexit__(\n self,\n exc_type: type[BaseException] | None,\n exc_value: BaseException | None,\n traceback: types.TracebackType | None,\n ) -> bool | None:\n return self._cm.__exit__(exc_type, exc_value, traceback)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_AsyncLiftContextManager", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L185-L204", "start_line": 185, "end_line": 204} +{"id": "fastapi/routing.py::_wrap_gen_lifespan_context::L208", "text": "# File: fastapi/routing.py | Symbol: _wrap_gen_lifespan_context\ndef _wrap_gen_lifespan_context(\n lifespan_context: Callable[[Any], Generator[Any, Any, Any]],\n) -> Callable[[Any], AbstractAsyncContextManager[Any]]:\n \"\"\"\n Wrap a generator-based lifespan context into an async context manager.\n\n This is vendored from Starlette to avoid importing private symbols.\n \"\"\"\n cmgr = contextlib.contextmanager(lifespan_context)\n\n @functools.wraps(cmgr)\n def wrapper(app: Any) -> _AsyncLiftContextManager[Any]:\n return _AsyncLiftContextManager(cmgr(app))\n\n return wrapper", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_wrap_gen_lifespan_context", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L208-L222", "start_line": 208, "end_line": 222} +{"id": "fastapi/routing.py::_merge_lifespan_context::L225", "text": "# File: fastapi/routing.py | Symbol: _merge_lifespan_context\ndef _merge_lifespan_context(\n original_context: Lifespan[Any], nested_context: Lifespan[Any]\n) -> Lifespan[Any]:\n @asynccontextmanager\n async def merged_lifespan(\n app: AppType,\n ) -> AsyncIterator[Mapping[str, Any] | None]:\n async with original_context(app) as maybe_original_state:\n async with nested_context(app) as maybe_nested_state:\n if maybe_nested_state is None and maybe_original_state is None:\n yield None # old ASGI compatibility\n else:\n yield {**(maybe_nested_state or {}), **(maybe_original_state or {})}\n\n return merged_lifespan # type: ignore[return-value] # ty: ignore[invalid-return-type]", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_merge_lifespan_context", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L225-L239", "start_line": 225, "end_line": 239} +{"id": "fastapi/routing.py::_DefaultLifespan::L242", "text": "# File: fastapi/routing.py | Symbol: _DefaultLifespan\nclass _DefaultLifespan:\n \"\"\"\n Default lifespan context manager that runs on_startup and on_shutdown handlers.\n\n This is a copy of the Starlette _DefaultLifespan class that was removed\n in Starlette. FastAPI keeps it to maintain backward compatibility with\n on_startup and on_shutdown event handlers.\n\n Ref: https://github.com/Kludex/starlette/pull/3117\n \"\"\"\n\n def __init__(self, router: \"APIRouter\") -> None:\n self._router = router\n\n async def __aenter__(self) -> None:\n await self._router._startup()\n\n async def __aexit__(self, *exc_info: object) -> None:\n await self._router._shutdown()\n\n def __call__(self: _T, app: object) -> _T:\n return self", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_DefaultLifespan", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L242-L263", "start_line": 242, "end_line": 263} +{"id": "fastapi/routing.py::_extract_endpoint_context::L270", "text": "# File: fastapi/routing.py | Symbol: _extract_endpoint_context\ndef _extract_endpoint_context(func: Any) -> EndpointContext:\n \"\"\"Extract endpoint context with caching to avoid repeated file I/O.\"\"\"\n func_id = id(func)\n\n if func_id in _endpoint_context_cache:\n return _endpoint_context_cache[func_id]\n\n try:\n ctx: EndpointContext = {}\n\n if (source_file := inspect.getsourcefile(func)) is not None:\n ctx[\"file\"] = source_file\n if (line_number := inspect.getsourcelines(func)[1]) is not None:\n ctx[\"line\"] = line_number\n if (func_name := getattr(func, \"__name__\", None)) is not None:\n ctx[\"function\"] = func_name\n except Exception:\n ctx = EndpointContext()\n\n _endpoint_context_cache[func_id] = ctx\n return ctx", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_extract_endpoint_context", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L270-L290", "start_line": 270, "end_line": 290} +{"id": "fastapi/routing.py::serialize_response::L293", "text": "# File: fastapi/routing.py | Symbol: serialize_response\nasync def serialize_response(\n *,\n field: ModelField | None = None,\n response_content: Any,\n include: IncEx | None = None,\n exclude: IncEx | None = None,\n by_alias: bool = True,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n is_coroutine: bool = True,\n endpoint_ctx: EndpointContext | None = None,\n dump_json: bool = False,\n) -> Any:\n if field:\n if is_coroutine:\n value, errors = field.validate(response_content, {}, loc=(\"response\",))\n else:\n value, errors = await run_in_threadpool(\n field.validate, response_content, {}, loc=(\"response\",)\n )\n if errors:\n ctx = endpoint_ctx or EndpointContext()\n raise ResponseValidationError(\n errors=errors,\n body=response_content,\n endpoint_ctx=ctx,\n )\n serializer = field.serialize_json if dump_json else field.serialize\n return serializer(\n value,\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_defaults=exclude_defaults,\n exclude_none=exclude_none,\n )\n\n else:\n return jsonable_encoder(response_content)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "serialize_response", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L293-L333", "start_line": 293, "end_line": 333} +{"id": "fastapi/routing.py::run_endpoint_function::L336", "text": "# File: fastapi/routing.py | Symbol: run_endpoint_function\nasync def run_endpoint_function(\n *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool\n) -> Any:\n # Only called by get_request_handler. Has been split into its own function to\n # facilitate profiling endpoints, since inner functions are harder to profile.\n assert dependant.call is not None, \"dependant.call must be a function\"\n\n if is_coroutine:\n return await dependant.call(**values)\n else:\n return await run_in_threadpool(dependant.call, **values)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "run_endpoint_function", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L336-L346", "start_line": 336, "end_line": 346} +{"id": "fastapi/routing.py::_build_response_args::L349", "text": "# File: fastapi/routing.py | Symbol: _build_response_args\ndef _build_response_args(\n *, status_code: int | None, solved_result: Any\n) -> dict[str, Any]:\n response_args: dict[str, Any] = {\n \"background\": solved_result.background_tasks,\n }\n # If status_code was set, use it, otherwise use the default from the\n # response class, in the case of redirect it's 307\n current_status_code = (\n status_code if status_code else solved_result.response.status_code\n )\n if current_status_code is not None:\n response_args[\"status_code\"] = current_status_code\n if solved_result.response.status_code:\n response_args[\"status_code\"] = solved_result.response.status_code\n return response_args", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_build_response_args", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L349-L364", "start_line": 349, "end_line": 364} +{"id": "fastapi/routing.py::get_request_handler::L367", "text": "# File: fastapi/routing.py | Symbol: get_request_handler\ndef get_request_handler(\n dependant: Dependant,\n body_field: ModelField | None = None,\n status_code: int | None = None,\n response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),\n response_field: ModelField | None = None,\n response_model_include: IncEx | None = None,\n response_model_exclude: IncEx | None = None,\n response_model_by_alias: bool = True,\n response_model_exclude_unset: bool = False,\n response_model_exclude_defaults: bool = False,\n response_model_exclude_none: bool = False,\n dependency_overrides_provider: Any | None = None,\n embed_body_fields: bool = False,\n strict_content_type: bool | DefaultPlaceholder = Default(True),\n stream_item_field: ModelField | None = None,\n is_json_stream: bool = False,\n) -> Callable[[Request], Coroutine[Any, Any, Response]]:\n assert dependant.call is not None, \"dependant.call must be a function\"\n is_coroutine = dependant.is_coroutine_callable\n is_body_form = body_field and isinstance(body_field.field_info, params.Form)\n if isinstance(response_class, DefaultPlaceholder):\n actual_response_class: type[Response] = response_class.value\n else:\n actual_response_class = response_class\n is_sse_stream = lenient_issubclass(actual_response_class, EventSourceResponse)\n if isinstance(strict_content_type, DefaultPlaceholder):\n actual_strict_content_type: bool = strict_content_type.value\n else:\n actual_strict_content_type = strict_content_type\n\n async def app(request: Request) -> Response:\n response: Response | None = None\n file_stack = request.scope.get(\"fastapi_middleware_astack\")\n assert isinstance(file_stack, AsyncExitStack), (\n \"fastapi_middleware_astack not found in request scope\"\n )\n\n # Extract endpoint context for error messages\n endpoint_ctx = (\n _extract_endpoint_context(dependant.call)\n if dependant.call\n else EndpointContext()\n )\n\n if dependant.path:\n # For mounted sub-apps, include the mount path prefix\n mount_path = request.scope.get(\"root_path\", \"\").rstrip(\"/\")\n endpoint_ctx[\"path\"] = f\"{request.method} {mount_path}{dependant.path}\"\n\n # Read body and auto-close files\n try:\n body: Any = None\n if body_field:\n if is_body_form:\n body = await request.form()\n file_stack.push_async_callback(body.close)\n else:\n body_bytes = await request.body()\n if body_bytes:\n json_body: Any = Undefined\n content_type_value = request.headers.get(\"content-type\")\n if not content_type_value:\n if not actual_strict_content_type:\n json_body = await request.json()\n else:\n message = email.message.Message()\n message[\"content-type\"] = content_type_value\n if message.get_content_maintype() == \"application\":\n subtype = message.get_content_subtype()\n if subtype == \"json\" or subtype.endswith(\"+json\"):\n json_body = await request.json()\n if json_body != Undefined:\n body = json_body\n else:\n body = body_bytes\n except json.JSONDecodeError as e:\n validation_error = RequestValidationError(\n [\n {\n \"type\": \"json_invalid\",\n \"loc\": (\"body\", e.pos),\n \"msg\": \"JSON decode error\",\n \"input\": {},\n \"ctx\": {\"error\": e.msg},\n }\n ],\n body=e.doc,\n endpoint_ctx=endpoint_ctx,\n )\n raise validation_error from e\n except HTTPException:\n # If a middleware raises an HTTPException, it should be raised again\n raise\n except Exception as e:\n http_error = HTTPException(\n status_code=400, detail=\"There was an error parsing the body\"\n )\n raise http_error from e\n\n # Solve dependencies and run path operation function, auto-closing dependencies\n errors: list[Any] = []\n async_exit_stack = request.scope.get(\"fastapi_inner_astack\")\n assert isinstance(async_exit_stack, AsyncExitStack), (\n \"fastapi_inner_astack not found in request scope\"\n )\n solved_result = await solve_dependencies(\n request=request,\n dependant=dependant,\n body=cast(dict[str, Any] | FormData | bytes | None, body),\n dependency_overrides_provider=dependency_overrides_provider,\n async_exit_stack=async_exit_stack,\n embed_body_fields=embed_body_fields,\n )\n errors = solved_result.errors\n assert dependant.call # For types\n if not errors:\n # Shared serializer for stream items (JSONL and SSE).\n # Validates against stream_item_field when set, then\n # serializes to JSON bytes.\n def _serialize_data(data: Any) -> bytes:\n if stream_item_field:\n value, errors_ = stream_item_field.validate(\n data, {}, loc=(\"response\",)\n )\n if errors_:\n ctx = endpoint_ctx or EndpointContext()\n raise ResponseValidationError(\n errors=errors_,\n body=data,\n endpoint_ctx=ctx,\n )\n return stream_item_field.serialize_json(\n value,\n include=response_model_include,\n exclude=response_model_exclude,\n by_alias=response_model_by_alias,\n exclude_unset=response_model_exclude_unset,\n exclude_defaults=response_model_exclude_defaults,\n exclude_none=response_model_exclude_none,\n )\n else:\n data = jsonable_encoder(data)\n return json.dumps(data).encode(\"utf-8\")\n\n if is_sse_stream:\n # Generator endpoint: stream as Server-Sent Events\n gen = dependant.call(**solved_result.values)\n\n def _serialize_sse_item(item: Any) -> bytes:\n if isinstance(item, ServerSentEvent):\n # User controls the event structure.\n # Serialize the data payload if present.\n # For ServerSentEvent items we skip stream_item_field\n # validation (the user may mix types intentionally).\n if item.raw_data is not None:\n data_str: str | None = item.raw_data\n elif item.data is not None:\n if hasattr(item.data, \"model_dump_json\"):\n data_str = item.data.model_dump_json()\n else:\n data_str = json.dumps(jsonable_encoder(item.data))\n else:\n data_str = None\n return format_sse_event(\n data_str=data_str,\n event=item.event,\n id=item.id,\n retry=item.retry,\n comment=item.comment,\n )\n else:\n # Plain object: validate + serialize via\n # stream_item_field (if set) and wrap in data field\n return format_sse_event(\n data_str=_serialize_data(item).decode(\"utf-8\")\n )\n\n if dependant.is_async_gen_callable:\n sse_aiter: AsyncIterator[Any] = gen.__aiter__()\n else:\n sse_aiter = iterate_in_threadpool(gen)\n\n @asynccontextmanager\n async def _sse_producer_cm() -> AsyncIterator[\n ObjectReceiveStream[bytes]\n ]:\n # Use a memory stream to decouple generator iteration\n # from the keepalive timer. A producer task pulls items\n # from the generator independently, so\n # `anyio.fail_after` never wraps the generator's\n # `__anext__` directly - avoiding CancelledError that\n # would finalize the generator and also working for sync\n # generators running in a thread pool.\n #\n # This context manager is entered on the request-scoped\n # AsyncExitStack so its __aexit__ (which cancels the\n # task group) is called by the exit stack after the\n # streaming response completes — not by async generator\n # finalization via GeneratorExit.\n # Ref: https://peps.python.org/pep-0789/\n send_stream, receive_stream = anyio.create_memory_object_stream[\n bytes\n ](max_buffer_size=1)\n\n async def _producer() -> None:\n async with send_stream:\n async for raw_item in sse_aiter:\n await send_stream.send(_serialize_sse_item(raw_item))\n\n send_keepalive, receive_keepalive = (\n anyio.create_memory_object_stream[bytes](max_buffer_size=1)\n )\n\n async def _keepalive_inserter() -> None:\n \"\"\"Read from the producer and forward to the output,\n inserting keepalive comments on timeout.\"\"\"\n async with send_keepalive, receive_stream:\n try:\n while True:\n try:\n with anyio.fail_after(_PING_INTERVAL):\n data = await receive_stream.receive()\n await send_keepalive.send(data)\n except TimeoutError:\n await send_keepalive.send(KEEPALIVE_COMMENT)\n except anyio.EndOfStream:\n pass\n\n async with anyio.create_task_group() as tg:\n tg.start_soon(_producer)\n tg.start_soon(_keepalive_inserter)\n yield receive_keepalive\n tg.cancel_scope.cancel()\n\n # Enter the SSE context manager on the request-scoped\n # exit stack. The stack outlives the streaming response,\n # so __aexit__ runs via proper structured teardown, not\n # via GeneratorExit thrown into an async generator.\n sse_receive_stream = await async_exit_stack.enter_async_context(\n _sse_producer_cm()\n )\n # Ensure the receive stream is closed when the exit stack\n # unwinds, preventing ResourceWarning from __del__.\n async_exit_stack.push_async_callback(sse_receive_stream.aclose)\n\n async def _sse_with_checkpoints(\n stream: ObjectReceiveStream[bytes],\n ) -> AsyncIterator[bytes]:\n async for data in stream:\n yield data\n # Guarantee a checkpoint so cancellation can be\n # delivered even when the producer is faster than\n # the consumer and receive() never suspends.\n await anyio.sleep(0)\n\n sse_stream_content: AsyncIterator[bytes] | Iterator[bytes] = (\n _sse_with_checkpoints(sse_receive_stream)\n )\n\n response = StreamingResponse(\n sse_stream_content,\n media_type=\"text/event-stream\",\n background=solved_result.background_tasks,\n )\n response.headers[\"Cache-Control\"] = \"no-cache\"\n # For Nginx proxies to not buffer server sent events\n response.headers[\"X-Accel-Buffering\"] = \"no\"\n response.headers.raw.extend(solved_result.response.headers.raw)\n elif is_json_stream:\n # Generator endpoint: stream as JSONL\n gen = dependant.call(**solved_result.values)\n\n def _serialize_item(item: Any) -> bytes:\n return _serialize_data(item) + b\"\\n\"\n\n if dependant.is_async_gen_callable:\n\n async def _async_stream_jsonl() -> AsyncIterator[bytes]:\n async for item in gen:\n yield _serialize_item(item)\n # To allow for cancellation to trigger\n # Ref: https://github.com/fastapi/fastapi/issues/14680\n await anyio.sleep(0)\n\n jsonl_stream_content: AsyncIterator[bytes] | Iterator[bytes] = (\n _async_stream_jsonl()\n )\n else:\n\n def _sync_stream_jsonl() -> Iterator[bytes]:\n for item in gen: # ty: ignore[not-iterable]\n yield _serialize_item(item)\n\n jsonl_stream_content = _sync_stream_jsonl()\n\n response = StreamingResponse(\n jsonl_stream_content,\n media_type=\"application/jsonl\",\n background=solved_result.background_tasks,\n )\n response.headers.raw.extend(solved_result.response.headers.raw)\n elif dependant.is_async_gen_callable or dependant.is_gen_callable:\n # Raw streaming with explicit response_class (e.g. StreamingResponse)\n gen = dependant.call(**solved_result.values)\n if dependant.is_async_gen_callable:\n\n async def _async_stream_raw(\n async_gen: AsyncIterator[Any],\n ) -> AsyncIterator[Any]:\n async for chunk in async_gen:\n yield chunk\n # To allow for cancellation to trigger\n # Ref: https://github.com/fastapi/fastapi/issues/14680\n await anyio.sleep(0)\n\n gen = _async_stream_raw(gen)\n response_args = _build_response_args(\n status_code=status_code, solved_result=solved_result\n )\n response = actual_response_class(content=gen, **response_args)\n response.headers.raw.extend(solved_result.response.headers.raw)\n else:\n raw_response = await run_endpoint_function(\n dependant=dependant,\n values=solved_result.values,\n is_coroutine=is_coroutine,\n )\n if isinstance(raw_response, Response):\n if raw_response.background is None:\n raw_response.background = solved_result.background_tasks\n response = raw_response\n else:\n response_args = _build_response_args(\n status_code=status_code, solved_result=solved_result\n )\n # Use the fast path (dump_json) when no custom response\n # class was set and a response field with a TypeAdapter\n # exists. Serializes directly to JSON bytes via Pydantic's\n # Rust core, skipping the intermediate Python dict +\n # json.dumps() step.\n use_dump_json = response_field is not None and isinstance(\n response_class, DefaultPlaceholder\n )\n content = await serialize_response(\n field=response_field,\n response_content=raw_response,\n include=response_model_include,\n exclude=response_model_exclude,\n by_alias=response_model_by_alias,\n exclude_unset=response_model_exclude_unset,\n exclude_defaults=response_model_exclude_defaults,\n exclude_none=response_model_exclude_none,\n is_coroutine=is_coroutine,\n endpoint_ctx=endpoint_ctx,\n dump_json=use_dump_json,\n )\n if use_dump_json:\n response = Response(\n content=content,\n media_type=\"application/json\",\n **response_args,\n )\n else:\n response = actual_response_class(content, **response_args)\n if not is_body_allowed_for_status_code(response.status_code):\n response.body = b\"\"\n response.headers.raw.extend(solved_result.response.headers.raw)\n if errors:\n validation_error = RequestValidationError(\n errors, body=body, endpoint_ctx=endpoint_ctx\n )\n raise validation_error\n\n # Return response\n assert response\n return response\n\n return app", "source_type": "code", "path": "fastapi/routing.py", "symbol": "get_request_handler", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L367-L745", "start_line": 367, "end_line": 745} +{"id": "fastapi/routing.py::get_websocket_app::L748", "text": "# File: fastapi/routing.py | Symbol: get_websocket_app\ndef get_websocket_app(\n dependant: Dependant,\n dependency_overrides_provider: Any | None = None,\n embed_body_fields: bool = False,\n) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]:\n async def app(websocket: WebSocket) -> None:\n endpoint_ctx = (\n _extract_endpoint_context(dependant.call)\n if dependant.call\n else EndpointContext()\n )\n if dependant.path:\n # For mounted sub-apps, include the mount path prefix\n mount_path = websocket.scope.get(\"root_path\", \"\").rstrip(\"/\")\n endpoint_ctx[\"path\"] = f\"WS {mount_path}{dependant.path}\"\n async_exit_stack = websocket.scope.get(\"fastapi_inner_astack\")\n assert isinstance(async_exit_stack, AsyncExitStack), (\n \"fastapi_inner_astack not found in request scope\"\n )\n solved_result = await solve_dependencies(\n request=websocket,\n dependant=dependant,\n dependency_overrides_provider=dependency_overrides_provider,\n async_exit_stack=async_exit_stack,\n embed_body_fields=embed_body_fields,\n )\n if solved_result.errors:\n raise WebSocketRequestValidationError(\n solved_result.errors,\n endpoint_ctx=endpoint_ctx,\n )\n assert dependant.call is not None, \"dependant.call must be a function\"\n await dependant.call(**solved_result.values)\n\n return app", "source_type": "code", "path": "fastapi/routing.py", "symbol": "get_websocket_app", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L748-L782", "start_line": 748, "end_line": 782} +{"id": "fastapi/routing.py::APIWebSocketRoute::L785", "text": "# File: fastapi/routing.py | Symbol: APIWebSocketRoute\nclass APIWebSocketRoute(routing.WebSocketRoute):\n def __init__(\n self,\n path: str,\n endpoint: Callable[..., Any],\n *,\n name: str | None = None,\n dependencies: Sequence[params.Depends] | None = None,\n dependency_overrides_provider: Any | None = None,\n ) -> None:\n self.path = path\n self.endpoint = endpoint\n self.name = get_name(endpoint) if name is None else name\n self.dependencies = list(dependencies or [])\n self.path_regex, self.path_format, self.param_convertors = compile_path(path)\n (\n self.dependant,\n self._flat_dependant,\n self._embed_body_fields,\n ) = _build_dependant_with_parameterless_dependencies(\n path=self.path_format,\n call=self.endpoint,\n dependencies=self.dependencies,\n )\n self.app = websocket_session(\n get_websocket_app(\n dependant=self.dependant,\n dependency_overrides_provider=dependency_overrides_provider,\n embed_body_fields=self._embed_body_fields,\n )\n )\n\n def matches(self, scope: Scope) -> tuple[Match, Scope]:\n match, child_scope = super().matches(scope)\n if match != Match.NONE:\n child_scope[\"route\"] = self\n return match, child_scope", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIWebSocketRoute", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L785-L821", "start_line": 785, "end_line": 821} +{"id": "fastapi/routing.py::_frontend_dependency_endpoint::L835", "text": "# File: fastapi/routing.py | Symbol: _frontend_dependency_endpoint\ndef _frontend_dependency_endpoint() -> None:\n pass # pragma: no cover", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_frontend_dependency_endpoint", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L835-L836", "start_line": 835, "end_line": 836} +{"id": "fastapi/routing.py::_build_dependant_with_parameterless_dependencies::L839", "text": "# File: fastapi/routing.py | Symbol: _build_dependant_with_parameterless_dependencies\ndef _build_dependant_with_parameterless_dependencies(\n *,\n path: str,\n call: Callable[..., Any],\n dependencies: Sequence[params.Depends],\n) -> tuple[Dependant, Dependant, bool]:\n dependant = get_dependant(path=path, call=call, scope=\"function\")\n for depends in dependencies[::-1]:\n dependant.dependencies.insert(\n 0,\n get_parameterless_sub_dependant(depends=depends, path=path),\n )\n flat_dependant = get_flat_dependant(dependant)\n embed_body_fields = _should_embed_body_fields(flat_dependant.body_params)\n return dependant, flat_dependant, embed_body_fields", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_build_dependant_with_parameterless_dependencies", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L839-L853", "start_line": 839, "end_line": 853} +{"id": "fastapi/routing.py::_get_fastapi_scope::L860", "text": "# File: fastapi/routing.py | Symbol: _get_fastapi_scope\ndef _get_fastapi_scope(scope: Scope) -> dict[str, Any]:\n fastapi_scope = scope.setdefault(_FASTAPI_SCOPE_KEY, {})\n assert isinstance(fastapi_scope, dict)\n return fastapi_scope", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_get_fastapi_scope", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L860-L863", "start_line": 860, "end_line": 863} +{"id": "fastapi/routing.py::_update_scope::L866", "text": "# File: fastapi/routing.py | Symbol: _update_scope\ndef _update_scope(scope: Scope, child_scope: Scope) -> None:\n fastapi_child_scope = child_scope.get(_FASTAPI_SCOPE_KEY)\n for key, value in child_scope.items():\n if key != _FASTAPI_SCOPE_KEY:\n scope[key] = value\n if isinstance(fastapi_child_scope, dict):\n _get_fastapi_scope(scope).update(fastapi_child_scope)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_update_scope", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L866-L872", "start_line": 866, "end_line": 872} +{"id": "fastapi/routing.py::_get_scope_effective_route_context::L875", "text": "# File: fastapi/routing.py | Symbol: _get_scope_effective_route_context\ndef _get_scope_effective_route_context(scope: Scope) -> Any | None:\n return scope.get(_FASTAPI_SCOPE_KEY, {}).get(_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_get_scope_effective_route_context", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L875-L876", "start_line": 875, "end_line": 876} +{"id": "fastapi/routing.py::_get_scope_included_router::L879", "text": "# File: fastapi/routing.py | Symbol: _get_scope_included_router\ndef _get_scope_included_router(scope: Scope) -> Any | None:\n return scope.get(_FASTAPI_SCOPE_KEY, {}).get(_FASTAPI_INCLUDED_ROUTER_KEY)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_get_scope_included_router", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L879-L880", "start_line": 879, "end_line": 880} +{"id": "fastapi/routing.py::_frontend_scope_specificity::L883", "text": "# File: fastapi/routing.py | Symbol: _frontend_scope_specificity\ndef _frontend_scope_specificity(scope: Scope) -> int | None:\n specificity = scope.get(_FASTAPI_SCOPE_KEY, {}).get(\n _FASTAPI_FRONTEND_SPECIFICITY_KEY\n )\n if isinstance(specificity, int):\n return specificity\n return None", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_frontend_scope_specificity", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L883-L889", "start_line": 883, "end_line": 889} +{"id": "fastapi/routing.py::_restore_fastapi_scope_key::L892", "text": "# File: fastapi/routing.py | Symbol: _restore_fastapi_scope_key\ndef _restore_fastapi_scope_key(scope: Scope, key: str, previous: Any) -> None:\n fastapi_scope = scope.get(_FASTAPI_SCOPE_KEY)\n if not isinstance(fastapi_scope, dict):\n return\n if previous is _SCOPE_MISSING:\n fastapi_scope.pop(key, None)\n else:\n fastapi_scope[key] = previous", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_restore_fastapi_scope_key", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L892-L899", "start_line": 892, "end_line": 899} +{"id": "fastapi/routing.py::_APIRouteLike::L902", "text": "# File: fastapi/routing.py | Symbol: _APIRouteLike\nclass _APIRouteLike(Protocol):\n path: str\n endpoint: Callable[..., Any]\n stream_item_type: Any | None\n response_model: Any\n summary: str | None\n response_description: str\n deprecated: bool | None\n operation_id: str | None\n response_model_include: IncEx | None\n response_model_exclude: IncEx | None\n response_model_by_alias: bool\n response_model_exclude_unset: bool\n response_model_exclude_defaults: bool\n response_model_exclude_none: bool\n include_in_schema: bool\n response_class: type[Response] | DefaultPlaceholder\n dependency_overrides_provider: Any | None\n callbacks: list[BaseRoute] | None\n openapi_extra: dict[str, Any] | None\n generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder\n strict_content_type: bool | DefaultPlaceholder\n tags: list[str | Enum]\n responses: dict[int | str, dict[str, Any]]\n name: str\n path_regex: Any\n path_format: str\n param_convertors: dict[str, Any]\n methods: set[str]\n unique_id: str\n status_code: int | None\n response_field: ModelField | None\n stream_item_field: ModelField | None\n dependencies: list[params.Depends]\n description: str\n response_fields: dict[int | str, ModelField]\n dependant: Dependant\n _flat_dependant: Dependant\n _embed_body_fields: bool\n body_field: ModelField | None\n is_sse_stream: bool\n is_json_stream: bool", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_APIRouteLike", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L902-L943", "start_line": 902, "end_line": 943} +{"id": "fastapi/routing.py::_populate_api_route_state::L946", "text": "# File: fastapi/routing.py | Symbol: _populate_api_route_state\ndef _populate_api_route_state(\n route: _APIRouteLike,\n path: str,\n endpoint: Callable[..., Any],\n *,\n response_model: Any = Default(None),\n status_code: int | None = None,\n tags: list[str | Enum] | None = None,\n dependencies: Sequence[params.Depends] | None = None,\n summary: str | None = None,\n description: str | None = None,\n response_description: str = \"Successful Response\",\n responses: dict[int | str, dict[str, Any]] | None = None,\n deprecated: bool | None = None,\n name: str | None = None,\n methods: set[str] | list[str] | None = None,\n operation_id: str | None = None,\n response_model_include: IncEx | None = None,\n response_model_exclude: IncEx | None = None,\n response_model_by_alias: bool = True,\n response_model_exclude_unset: bool = False,\n response_model_exclude_defaults: bool = False,\n response_model_exclude_none: bool = False,\n include_in_schema: bool = True,\n response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),\n dependency_overrides_provider: Any | None = None,\n callbacks: list[BaseRoute] | None = None,\n openapi_extra: dict[str, Any] | None = None,\n generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder = Default(\n generate_unique_id\n ),\n strict_content_type: bool | DefaultPlaceholder = Default(True),\n) -> None:\n route.path = path\n route.endpoint = endpoint\n route.stream_item_type = None\n if isinstance(response_model, DefaultPlaceholder):\n return_annotation = get_typed_return_annotation(endpoint)\n if lenient_issubclass(return_annotation, Response):\n response_model = None\n else:\n stream_item = get_stream_item_type(return_annotation)\n if stream_item is not None:\n # Extract item type for JSONL or SSE streaming when\n # response_class is DefaultPlaceholder (JSONL) or\n # EventSourceResponse (SSE).\n # ServerSentEvent is excluded: it's a transport\n # wrapper, not a data model, so it shouldn't feed\n # into validation or OpenAPI schema generation.\n if (\n isinstance(response_class, DefaultPlaceholder)\n or lenient_issubclass(response_class, EventSourceResponse)\n ) and not lenient_issubclass(stream_item, ServerSentEvent):\n route.stream_item_type = stream_item\n response_model = None\n else:\n response_model = return_annotation\n route.response_model = response_model\n route.summary = summary\n route.response_description = response_description\n route.deprecated = deprecated\n route.operation_id = operation_id\n route.response_model_include = response_model_include\n route.response_model_exclude = response_model_exclude\n route.response_model_by_alias = response_model_by_alias\n route.response_model_exclude_unset = response_model_exclude_unset\n route.response_model_exclude_defaults = response_model_exclude_defaults\n route.response_model_exclude_none = response_model_exclude_none\n route.include_in_schema = include_in_schema\n route.response_class = response_class\n route.dependency_overrides_provider = dependency_overrides_provider\n route.callbacks = callbacks\n route.openapi_extra = openapi_extra\n route.generate_unique_id_function = generate_unique_id_function\n route.strict_content_type = strict_content_type\n route.tags = tags or []\n route.responses = responses or {}\n route.name = get_name(endpoint) if name is None else name\n route.path_regex, route.path_format, route.param_convertors = compile_path(path)\n if methods is None:\n methods = [\"GET\"]\n route.methods = {method.upper() for method in methods}\n if isinstance(generate_unique_id_function, DefaultPlaceholder):\n current_generate_unique_id: Callable[[Any], str] = (\n generate_unique_id_function.value\n )\n else:\n current_generate_unique_id = generate_unique_id_function\n route.unique_id = route.operation_id or current_generate_unique_id(route)\n # normalize enums e.g. http.HTTPStatus\n if isinstance(status_code, IntEnum):\n status_code = int(status_code)\n route.status_code = status_code\n if route.response_model:\n assert is_body_allowed_for_status_code(status_code), (\n f\"Status code {status_code} must not have a response body\"\n )\n response_name = \"Response_\" + route.unique_id\n route.response_field = create_model_field(\n name=response_name,\n type_=route.response_model,\n mode=\"serialization\",\n )\n else:\n route.response_field = None\n if route.stream_item_type:\n stream_item_name = \"StreamItem_\" + route.unique_id\n route.stream_item_field = create_model_field(\n name=stream_item_name,\n type_=route.stream_item_type,\n mode=\"serialization\",\n )\n else:\n route.stream_item_field = None\n route.dependencies = list(dependencies or [])\n route.description = description or inspect.cleandoc(route.endpoint.__doc__ or \"\")\n # if a \"form feed\" character (page break) is found in the description text,\n # truncate description text to the content preceding the first \"form feed\"\n route.description = route.description.split(\"\\f\")[0].strip()\n response_fields = {}\n for additional_status_code, response in route.responses.items():\n assert isinstance(response, dict), \"An additional response must be a dict\"\n model = response.get(\"model\")\n if model:\n assert is_body_allowed_for_status_code(additional_status_code), (\n f\"Status code {additional_status_code} must not have a response body\"\n )\n response_name = f\"Response_{additional_status_code}_{route.unique_id}\"\n response_field = create_model_field(\n name=response_name, type_=model, mode=\"serialization\"\n )\n response_fields[additional_status_code] = response_field\n if response_fields:\n route.response_fields = response_fields\n else:\n route.response_fields = {}\n\n assert callable(endpoint), \"An endpoint must be a callable\"\n (\n route.dependant,\n route._flat_dependant,\n route._embed_body_fields,\n ) = _build_dependant_with_parameterless_dependencies(\n path=route.path_format,\n call=route.endpoint,\n dependencies=route.dependencies,\n )\n route.body_field = get_body_field(\n flat_dependant=route._flat_dependant,\n name=route.unique_id,\n embed_body_fields=route._embed_body_fields,\n )\n # Detect generator endpoints that should stream as JSONL or SSE\n is_generator = (\n route.dependant.is_async_gen_callable or route.dependant.is_gen_callable\n )\n route.is_sse_stream = is_generator and lenient_issubclass(\n response_class, EventSourceResponse\n )\n route.is_json_stream = is_generator and isinstance(\n response_class, DefaultPlaceholder\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_populate_api_route_state", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L946-L1107", "start_line": 946, "end_line": 1107} +{"id": "fastapi/routing.py::APIRoute.__init__::L1146", "text": "# File: fastapi/routing.py | Class: APIRoute | Symbol: APIRoute.__init__\ndef __init__(\n self,\n path: str,\n endpoint: Callable[..., Any],\n *,\n response_model: Any = Default(None),\n status_code: int | None = None,\n tags: list[str | Enum] | None = None,\n dependencies: Sequence[params.Depends] | None = None,\n summary: str | None = None,\n description: str | None = None,\n response_description: str = \"Successful Response\",\n responses: dict[int | str, dict[str, Any]] | None = None,\n deprecated: bool | None = None,\n name: str | None = None,\n methods: set[str] | list[str] | None = None,\n operation_id: str | None = None,\n response_model_include: IncEx | None = None,\n response_model_exclude: IncEx | None = None,\n response_model_by_alias: bool = True,\n response_model_exclude_unset: bool = False,\n response_model_exclude_defaults: bool = False,\n response_model_exclude_none: bool = False,\n include_in_schema: bool = True,\n response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),\n dependency_overrides_provider: Any | None = None,\n callbacks: list[BaseRoute] | None = None,\n openapi_extra: dict[str, Any] | None = None,\n generate_unique_id_function: Callable[[\"APIRoute\"], str]\n | DefaultPlaceholder = Default(generate_unique_id),\n strict_content_type: bool | DefaultPlaceholder = Default(True),\n ) -> None:\n _populate_api_route_state(\n cast(_APIRouteLike, self),\n path,\n endpoint,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n name=name,\n methods=methods,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n dependency_overrides_provider=dependency_overrides_provider,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n strict_content_type=strict_content_type,\n )\n self.app = request_response(self.get_route_handler())", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRoute.__init__", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1146-L1208", "start_line": 1146, "end_line": 1208} +{"id": "fastapi/routing.py::APIRoute.get_route_handler::L1210", "text": "# File: fastapi/routing.py | Class: APIRoute | Symbol: APIRoute.get_route_handler\ndef get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:\n route = cast(_APIRouteLike, self)\n # TODO: Replace or deprecate this no-scope hook so included-route\n # effective context can be passed explicitly instead of via ContextVar.\n effective_context = _effective_route_context_var.get()\n if effective_context is not None and effective_context.original_route is self:\n route = cast(_APIRouteLike, effective_context)\n return get_request_handler(\n dependant=route.dependant,\n body_field=route.body_field,\n status_code=route.status_code,\n response_class=route.response_class,\n response_field=route.response_field,\n response_model_include=route.response_model_include,\n response_model_exclude=route.response_model_exclude,\n response_model_by_alias=route.response_model_by_alias,\n response_model_exclude_unset=route.response_model_exclude_unset,\n response_model_exclude_defaults=route.response_model_exclude_defaults,\n response_model_exclude_none=route.response_model_exclude_none,\n dependency_overrides_provider=route.dependency_overrides_provider,\n embed_body_fields=route._embed_body_fields,\n strict_content_type=route.strict_content_type,\n stream_item_field=route.stream_item_field,\n is_json_stream=route.is_json_stream,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRoute.get_route_handler", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1210-L1234", "start_line": 1210, "end_line": 1234} +{"id": "fastapi/routing.py::APIRoute.matches::L1236", "text": "# File: fastapi/routing.py | Class: APIRoute | Symbol: APIRoute.matches\ndef matches(self, scope: Scope) -> tuple[Match, Scope]:\n effective_context = _get_scope_effective_route_context(scope)\n if effective_context is not None and effective_context.original_route is self:\n match, child_scope = effective_context.matches(scope)\n else:\n match, child_scope = super().matches(scope)\n if match != Match.NONE:\n child_scope[\"route\"] = self\n return match, child_scope", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRoute.matches", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1236-L1244", "start_line": 1236, "end_line": 1244} +{"id": "fastapi/routing.py::APIRoute.handle::L1246", "text": "# File: fastapi/routing.py | Class: APIRoute | Symbol: APIRoute.handle\nasync def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n effective_context = _get_scope_effective_route_context(scope)\n if effective_context is not None and effective_context.original_route is self:\n methods = effective_context.methods\n if methods and scope[\"method\"] not in methods:\n headers = {\"Allow\": \", \".join(methods)}\n if \"app\" in scope:\n raise HTTPException(status_code=405, headers=headers)\n response = PlainTextResponse(\n \"Method Not Allowed\", status_code=405, headers=headers\n )\n await response(scope, receive, send)\n return\n token = _effective_route_context_var.set(effective_context)\n try:\n app = request_response(self.get_route_handler())\n finally:\n _effective_route_context_var.reset(token)\n await app(scope, receive, send)\n return\n await super().handle(scope, receive, send)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRoute.handle", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1246-L1266", "start_line": 1246, "end_line": 1266} +{"id": "fastapi/routing.py::_RouterIncludeContext::L1269", "text": "# File: fastapi/routing.py | Symbol: _RouterIncludeContext\n@dataclass\nclass _RouterIncludeContext:\n included_router: \"APIRouter\"\n prefix: str = \"\"\n tags: list[str | Enum] = field(default_factory=list)\n dependencies: list[params.Depends] = field(default_factory=list)\n default_response_class: type[Response] | DefaultPlaceholder = field(\n default_factory=lambda: Default(JSONResponse)\n )\n responses: dict[int | str, dict[str, Any]] = field(default_factory=dict)\n callbacks: list[BaseRoute] = field(default_factory=list)\n deprecated: bool | None = None\n include_in_schema: bool = True\n generate_unique_id_function: Callable[[APIRoute], str] | DefaultPlaceholder = field(\n default_factory=lambda: Default(generate_unique_id)\n )\n strict_content_type: bool | DefaultPlaceholder = field(\n default_factory=lambda: Default(True)\n )\n dependency_overrides_provider: Any | None = None\n\n @classmethod\n def for_include(\n cls,\n *,\n parent_router: \"APIRouter\",\n included_router: \"APIRouter\",\n prefix: str = \"\",\n tags: list[str | Enum] | None = None,\n dependencies: Sequence[params.Depends] | None = None,\n default_response_class: type[Response] | DefaultPlaceholder = Default(\n JSONResponse\n ),\n responses: dict[int | str, dict[str, Any]] | None = None,\n callbacks: list[BaseRoute] | None = None,\n deprecated: bool | None = None,\n include_in_schema: bool = True,\n generate_unique_id_function: Callable[[APIRoute], str]\n | DefaultPlaceholder = Default(generate_unique_id),\n ) -> \"_RouterIncludeContext\":\n return cls(\n included_router=included_router,\n prefix=parent_router.prefix + prefix,\n tags=[*parent_router.tags, *(tags or [])],\n dependencies=[*parent_router.dependencies, *(dependencies or [])],\n default_response_class=get_value_or_default(\n default_response_class, parent_router.default_response_class\n ),\n responses={**parent_router.responses, **(responses or {})},\n callbacks=[*parent_router.callbacks, *(callbacks or [])],\n deprecated=deprecated or parent_router.deprecated,\n include_in_schema=parent_router.include_in_schema and include_in_schema,\n generate_unique_id_function=get_value_or_default(\n generate_unique_id_function, parent_router.generate_unique_id_function\n ),\n strict_content_type=parent_router.strict_content_type,\n dependency_overrides_provider=parent_router.dependency_overrides_provider,\n )\n\n def combine(\n self, child_context: \"_RouterIncludeContext\"\n ) -> \"_RouterIncludeContext\":\n return _RouterIncludeContext(\n included_router=child_context.included_router,\n prefix=self.prefix + child_context.prefix,\n tags=[*self.tags, *child_context.tags],\n dependencies=[*self.dependencies, *child_context.dependencies],\n default_response_class=get_value_or_default(\n child_context.default_response_class, self.default_response_class\n ),\n responses={**self.responses, **child_context.responses},\n callbacks=[*self.callbacks, *child_context.callbacks],\n deprecated=self.deprecated or child_context.deprecated,\n include_in_schema=self.include_in_schema\n and child_context.include_in_schema,\n generate_unique_id_function=get_value_or_default(\n child_context.generate_unique_id_function,\n self.generate_unique_id_function,\n ),\n strict_content_type=get_value_or_default(\n child_context.strict_content_type, self.strict_content_type\n ),\n dependency_overrides_provider=self.dependency_overrides_provider,\n )\n\n def path_for(self, route: _RouteWithPath) -> str:\n return self.prefix + route.path", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_RouterIncludeContext", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1269-L1355", "start_line": 1269, "end_line": 1355} +{"id": "fastapi/routing.py::_EffectiveRouteContext.from_api_route::L1411", "text": "# File: fastapi/routing.py | Class: _EffectiveRouteContext | Symbol: _EffectiveRouteContext.from_api_route\n@classmethod\n def from_api_route(\n cls,\n *,\n original_route: APIRoute,\n include_context: _RouterIncludeContext,\n ) -> \"_EffectiveRouteContext\":\n route = cast(_APIRouteLike, original_route)\n context = cls(original_route=original_route)\n _populate_api_route_state(\n cast(_APIRouteLike, context),\n include_context.path_for(original_route),\n route.endpoint,\n response_model=route.response_model,\n status_code=route.status_code,\n tags=[*include_context.tags, *route.tags],\n dependencies=[*include_context.dependencies, *route.dependencies],\n summary=route.summary,\n description=route.description,\n response_description=route.response_description,\n responses={**include_context.responses, **route.responses},\n deprecated=route.deprecated or include_context.deprecated,\n methods=route.methods,\n operation_id=route.operation_id,\n response_model_include=route.response_model_include,\n response_model_exclude=route.response_model_exclude,\n response_model_by_alias=route.response_model_by_alias,\n response_model_exclude_unset=route.response_model_exclude_unset,\n response_model_exclude_defaults=route.response_model_exclude_defaults,\n response_model_exclude_none=route.response_model_exclude_none,\n include_in_schema=route.include_in_schema\n and include_context.include_in_schema,\n response_class=get_value_or_default(\n route.response_class,\n include_context.included_router.default_response_class,\n include_context.default_response_class,\n ),\n name=route.name,\n dependency_overrides_provider=include_context.dependency_overrides_provider,\n callbacks=[*include_context.callbacks, *(route.callbacks or [])],\n openapi_extra=route.openapi_extra,\n generate_unique_id_function=get_value_or_default(\n route.generate_unique_id_function,\n include_context.included_router.generate_unique_id_function,\n include_context.generate_unique_id_function,\n ),\n strict_content_type=get_value_or_default(\n route.strict_content_type,\n include_context.included_router.strict_content_type,\n include_context.strict_content_type,\n ),\n )\n return context", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_EffectiveRouteContext.from_api_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1411-L1463", "start_line": 1411, "end_line": 1463} +{"id": "fastapi/routing.py::_EffectiveRouteContext.from_frontend_route_group::L1465", "text": "# File: fastapi/routing.py | Class: _EffectiveRouteContext | Symbol: _EffectiveRouteContext.from_frontend_route_group\n@classmethod\n def from_frontend_route_group(\n cls,\n *,\n original_route: \"_FrontendRouteGroup\",\n include_context: _RouterIncludeContext,\n ) -> \"_EffectiveRouteContext\":\n dependencies = [*include_context.dependencies, *original_route.dependencies]\n context = cls(\n original_route=original_route,\n frontend_prefix=include_context.prefix,\n dependencies=dependencies,\n dependency_overrides_provider=include_context.dependency_overrides_provider,\n )\n (\n context.dependant,\n context._flat_dependant,\n context._embed_body_fields,\n ) = _build_dependant_with_parameterless_dependencies(\n path=\"\",\n call=_frontend_dependency_endpoint,\n dependencies=dependencies,\n )\n return context", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_EffectiveRouteContext.from_frontend_route_group", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1465-L1488", "start_line": 1465, "end_line": 1488} +{"id": "fastapi/routing.py::_EffectiveRouteContext.matches::L1490", "text": "# File: fastapi/routing.py | Class: _EffectiveRouteContext | Symbol: _EffectiveRouteContext.matches\ndef matches(self, scope: Scope) -> tuple[Match, Scope]:\n if isinstance(self.original_route, _FrontendRouteGroup):\n return self.original_route.matches_with_prefix(scope, self.frontend_prefix)\n if not isinstance(self.original_route, APIRoute):\n assert self.starlette_route is not None\n return self.starlette_route.matches(scope)\n if scope[\"type\"] != \"http\":\n return Match.NONE, {}\n route_path = get_route_path(scope)\n match = self.path_regex.match(route_path)\n if not match:\n return Match.NONE, {}\n matched_params = match.groupdict()\n for key, value in matched_params.items():\n matched_params[key] = self.param_convertors[key].convert(value)\n path_params = dict(scope.get(\"path_params\", {}))\n path_params.update(matched_params)\n child_scope = {\"endpoint\": self.endpoint, \"path_params\": path_params}\n methods = self.methods\n if methods and scope[\"method\"] not in methods:\n return Match.PARTIAL, child_scope\n return Match.FULL, child_scope", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_EffectiveRouteContext.matches", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1490-L1511", "start_line": 1490, "end_line": 1511} +{"id": "fastapi/routing.py::_EffectiveRouteContext.url_path_for::L1513", "text": "# File: fastapi/routing.py | Class: _EffectiveRouteContext | Symbol: _EffectiveRouteContext.url_path_for\ndef url_path_for(self, name: str, /, **path_params: Any) -> Any:\n if not isinstance(self.original_route, APIRoute):\n assert self.starlette_route is not None\n return self.starlette_route.url_path_for(name, **path_params)\n seen_params = set(path_params.keys())\n param_convertors = self.param_convertors\n expected_params = set(param_convertors.keys())\n if name != self.name or seen_params != expected_params:\n raise routing.NoMatchFound(name, path_params)\n path, remaining_params = routing.replace_params(\n self.path_format, param_convertors, path_params\n )\n assert not remaining_params\n return URLPath(path=path, protocol=\"http\")", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_EffectiveRouteContext.url_path_for", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1513-L1526", "start_line": 1513, "end_line": 1526} +{"id": "fastapi/routing.py::RouteContext::L1529", "text": "# File: fastapi/routing.py | Symbol: RouteContext\n@dataclass(frozen=True)\nclass RouteContext:\n route: BaseRoute\n _route_context: _EffectiveRouteContext | None = field(default=None, repr=False)\n\n @property\n def original_route(self) -> BaseRoute:\n if self._route_context is not None:\n return self._route_context.original_route\n return self.route\n\n @property\n def _effective_route(self) -> BaseRoute | _EffectiveRouteContext:\n if self._route_context is not None:\n return self._route_context\n return self.route\n\n @property\n def path(self) -> str | None:\n return getattr(self._effective_route, \"path\", None)\n\n @property\n def path_format(self) -> str | None:\n return getattr(self._effective_route, \"path_format\", None)\n\n @property\n def name(self) -> str | None:\n return getattr(self._effective_route, \"name\", None)\n\n @property\n def methods(self) -> set[str] | None:\n return getattr(self._effective_route, \"methods\", None)\n\n @property\n def endpoint(self) -> Callable[..., Any] | None:\n return getattr(self._effective_route, \"endpoint\", None)\n\n def __getattr__(self, name: str) -> Any:\n return getattr(self._effective_route, name)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "RouteContext", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1529-L1567", "start_line": 1529, "end_line": 1567} +{"id": "fastapi/routing.py::_IncludedRouter.effective_candidates::L1583", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter.effective_candidates\ndef effective_candidates(self) -> list[\"_EffectiveRouteContext | _IncludedRouter\"]:\n routes_version = self.original_router._get_routes_version()\n if routes_version == self._effective_candidates_version:\n return self._effective_candidates\n self._effective_candidates = []\n candidates = self.original_router.routes\n for route in candidates:\n if isinstance(route, _IncludedRouter):\n child_context = self.include_context.combine(route.include_context)\n child_branch = _IncludedRouter(\n original_router=route.original_router,\n include_context=child_context,\n )\n self._effective_candidates.append(child_branch)\n continue\n route_context = self._build_effective_context(route)\n if route_context is not None:\n self._effective_candidates.append(route_context)\n self._effective_candidates_version = routes_version\n return self._effective_candidates", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter.effective_candidates", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1583-L1602", "start_line": 1583, "end_line": 1602} +{"id": "fastapi/routing.py::_IncludedRouter.effective_low_priority_routes::L1604", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter.effective_low_priority_routes\ndef effective_low_priority_routes(self) -> list[\"_EffectiveRouteContext\"]:\n routes_version = self.original_router._get_routes_version()\n if routes_version == self._effective_low_priority_routes_version:\n return self._effective_low_priority_routes\n self._effective_low_priority_routes = []\n for route in self.original_router._low_priority_routes:\n route_context = self._build_effective_context(route)\n if route_context is not None:\n self._effective_low_priority_routes.append(route_context)\n for route in self.original_router.routes:\n if isinstance(route, _IncludedRouter):\n child_context = self.include_context.combine(route.include_context)\n child_branch = _IncludedRouter(\n original_router=route.original_router,\n include_context=child_context,\n )\n self._effective_low_priority_routes.extend(\n child_branch.effective_low_priority_routes()\n )\n self._effective_low_priority_routes_version = routes_version\n return self._effective_low_priority_routes", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter.effective_low_priority_routes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1604-L1624", "start_line": 1604, "end_line": 1624} +{"id": "fastapi/routing.py::_IncludedRouter._build_effective_context::L1626", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter._build_effective_context\ndef _build_effective_context(\n self, route: BaseRoute\n ) -> _EffectiveRouteContext | None:\n if isinstance(route, APIRoute):\n return _EffectiveRouteContext.from_api_route(\n original_route=route,\n include_context=self.include_context,\n )\n if isinstance(route, _FrontendRouteGroup):\n return _EffectiveRouteContext.from_frontend_route_group(\n original_route=route,\n include_context=self.include_context,\n )\n if isinstance(route, routing.Route):\n starlette_route: BaseRoute = routing.Route(\n self.include_context.path_for(route),\n endpoint=route.endpoint,\n methods=list(route.methods or []),\n name=route.name,\n include_in_schema=route.include_in_schema,\n )\n return _EffectiveRouteContext(\n original_route=route,\n starlette_route=starlette_route,\n )\n if isinstance(route, APIWebSocketRoute):\n starlette_route = APIWebSocketRoute(\n self.include_context.path_for(route),\n endpoint=route.endpoint,\n name=route.name,\n dependencies=[*self.include_context.dependencies, *route.dependencies],\n dependency_overrides_provider=(\n self.include_context.dependency_overrides_provider\n ),\n )\n return _EffectiveRouteContext(\n original_route=route,\n starlette_route=starlette_route,\n )\n if isinstance(route, routing.WebSocketRoute):\n starlette_route = routing.WebSocketRoute(\n self.include_context.path_for(route), route.endpoint, name=route.name\n )\n return _EffectiveRouteContext(\n original_route=route,\n starlette_route=starlette_route,\n )\n if isinstance(route, routing.Mount):\n starlette_route = copy.copy(route)\n starlette_route.path = self.include_context.path_for(route).rstrip(\"/\")\n (\n starlette_route.path_regex,\n starlette_route.path_format,\n starlette_route.param_convertors,\n ) = compile_path(starlette_route.path + \"/{path:path}\")\n return _EffectiveRouteContext(\n original_route=route,\n starlette_route=starlette_route,\n )\n if isinstance(route, routing.Host):\n if self.include_context.prefix:\n prefixed_app: ASGIApp = routing.Router(\n routes=[routing.Mount(self.include_context.prefix, app=route.app)]\n )\n else:\n prefixed_app = route.app\n starlette_route = routing.Host(\n route.host, app=prefixed_app, name=route.name\n )\n return _EffectiveRouteContext(\n original_route=route,\n starlette_route=starlette_route,\n )\n return None", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter._build_effective_context", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1626-L1699", "start_line": 1626, "end_line": 1699} +{"id": "fastapi/routing.py::_IncludedRouter._match::L1701", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter._match\ndef _match(\n self, scope: Scope\n ) -> tuple[Match, Scope, BaseRoute | None, _EffectiveRouteContext | None]:\n partial: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None\n for candidate in self.effective_candidates():\n if isinstance(candidate, _IncludedRouter):\n match, child_scope = candidate.matches(scope)\n route: BaseRoute = candidate\n route_context = None\n elif isinstance(candidate.original_route, APIRoute):\n route_context = candidate\n fastapi_scope = _get_fastapi_scope(scope)\n previous_context = fastapi_scope.get(\n _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, _SCOPE_MISSING\n )\n fastapi_scope[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = route_context\n try:\n match, child_scope = candidate.original_route.matches(scope)\n finally:\n _restore_fastapi_scope_key(\n scope, _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, previous_context\n )\n route = candidate.original_route\n else:\n route_context = candidate\n match, child_scope = candidate.matches(scope)\n route = candidate.starlette_route or candidate.original_route\n if match == Match.FULL:\n return match, child_scope, route, route_context\n if match == Match.PARTIAL and partial is None:\n partial = (child_scope, route, route_context)\n if partial is not None:\n child_scope, route, route_context = partial\n return Match.PARTIAL, child_scope, route, route_context\n return Match.NONE, {}, None, None", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter._match", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1701-L1735", "start_line": 1701, "end_line": 1735} +{"id": "fastapi/routing.py::_IncludedRouter.matches::L1737", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter.matches\ndef matches(self, scope: Scope) -> tuple[Match, Scope]:\n fastapi_scope = _get_fastapi_scope(scope)\n previous_router = fastapi_scope.get(\n _FASTAPI_INCLUDED_ROUTER_KEY, _SCOPE_MISSING\n )\n fastapi_scope[_FASTAPI_INCLUDED_ROUTER_KEY] = self\n try:\n match, _ = self.original_router.matches(scope)\n return match, {}\n finally:\n _restore_fastapi_scope_key(\n scope, _FASTAPI_INCLUDED_ROUTER_KEY, previous_router\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter.matches", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1737-L1749", "start_line": 1737, "end_line": 1749} +{"id": "fastapi/routing.py::_IncludedRouter.handle::L1751", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter.handle\nasync def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n _get_fastapi_scope(scope)[_FASTAPI_INCLUDED_ROUTER_KEY] = self\n await self.original_router.handle(scope, receive, send)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter.handle", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1751-L1753", "start_line": 1751, "end_line": 1753} +{"id": "fastapi/routing.py::_IncludedRouter._handle_selected::L1755", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter._handle_selected\nasync def _handle_selected(\n self, scope: Scope, receive: Receive, send: Send\n ) -> None:\n match, child_scope, route, effective_context = self._match(scope)\n if match == Match.NONE or route is None:\n await self.original_router.default(scope, receive, send)\n return\n scope.update(child_scope)\n if isinstance(route, _IncludedRouter):\n await route.handle(scope, receive, send)\n return\n if effective_context is not None:\n _get_fastapi_scope(scope)[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = (\n effective_context\n )\n original_route = effective_context.original_route\n if isinstance(original_route, APIRoute):\n scope[\"route\"] = original_route\n await original_route.handle(scope, receive, send)\n return\n await route.handle(scope, receive, send)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter._handle_selected", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1755-L1775", "start_line": 1755, "end_line": 1775} +{"id": "fastapi/routing.py::_IncludedRouter.effective_route_contexts::L1777", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter.effective_route_contexts\ndef effective_route_contexts(self) -> Iterator[_EffectiveRouteContext]:\n for candidate in self.effective_candidates():\n if isinstance(candidate, _IncludedRouter):\n yield from candidate.effective_route_contexts()\n else:\n yield candidate", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter.effective_route_contexts", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1777-L1782", "start_line": 1777, "end_line": 1782} +{"id": "fastapi/routing.py::_IncludedRouter.url_path_for::L1784", "text": "# File: fastapi/routing.py | Class: _IncludedRouter | Symbol: _IncludedRouter.url_path_for\ndef url_path_for(self, name: str, /, **path_params: Any) -> Any:\n for route_context in self.effective_route_contexts():\n try:\n return route_context.url_path_for(name, **path_params)\n except routing.NoMatchFound:\n pass\n raise routing.NoMatchFound(name, path_params)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_IncludedRouter.url_path_for", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1784-L1790", "start_line": 1784, "end_line": 1790} +{"id": "fastapi/routing.py::_iter_included_route_candidates::L1793", "text": "# File: fastapi/routing.py | Symbol: _iter_included_route_candidates\ndef _iter_included_route_candidates(routes: Sequence[BaseRoute]) -> Iterator[BaseRoute]:\n for route, route_context in _iter_routes_with_context(routes):\n if route_context is not None and route_context.starlette_route is not None:\n yield route_context.starlette_route\n else:\n yield route", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_iter_included_route_candidates", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1793-L1798", "start_line": 1793, "end_line": 1798} +{"id": "fastapi/routing.py::iter_route_contexts::L1801", "text": "# File: fastapi/routing.py | Symbol: iter_route_contexts\ndef iter_route_contexts(\n routes: Sequence[BaseRoute | RouteContext],\n) -> Iterator[RouteContext]:\n for route in routes:\n if isinstance(route, RouteContext):\n yield route\n continue\n for original_route, route_context in _iter_routes_with_context([route]):\n if route_context is None:\n yield RouteContext(original_route)\n else:\n yield RouteContext(original_route, route_context)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "iter_route_contexts", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1801-L1812", "start_line": 1801, "end_line": 1812} +{"id": "fastapi/routing.py::_iter_routes_with_context::L1815", "text": "# File: fastapi/routing.py | Symbol: _iter_routes_with_context\ndef _iter_routes_with_context(\n routes: Sequence[BaseRoute],\n) -> Iterator[tuple[BaseRoute, _EffectiveRouteContext | None]]:\n for route in routes:\n if isinstance(route, _IncludedRouter):\n for route_context in route.effective_route_contexts():\n yield route_context.original_route, route_context\n else:\n yield route, None", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_iter_routes_with_context", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1815-L1823", "start_line": 1815, "end_line": 1823} +{"id": "fastapi/routing.py::_normalize_frontend_path::L1826", "text": "# File: fastapi/routing.py | Symbol: _normalize_frontend_path\ndef _normalize_frontend_path(path: str) -> str:\n if not path:\n raise AssertionError(\"A frontend path cannot be empty\")\n if not path.startswith(\"/\"):\n raise AssertionError(\"A frontend path must start with '/'\")\n if path != \"/\":\n path = path.rstrip(\"/\")\n return path", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_normalize_frontend_path", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1826-L1833", "start_line": 1826, "end_line": 1833} +{"id": "fastapi/routing.py::_join_frontend_paths::L1836", "text": "# File: fastapi/routing.py | Symbol: _join_frontend_paths\ndef _join_frontend_paths(prefix: str, path: str) -> str:\n if not prefix:\n return path\n if path == \"/\":\n return prefix\n return prefix + path", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_join_frontend_paths", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1836-L1841", "start_line": 1836, "end_line": 1841} +{"id": "fastapi/routing.py::_frontend_path_specificity::L1844", "text": "# File: fastapi/routing.py | Symbol: _frontend_path_specificity\ndef _frontend_path_specificity(path: str) -> int:\n if path == \"/\":\n return 0\n return len(path)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_frontend_path_specificity", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1844-L1847", "start_line": 1844, "end_line": 1847} +{"id": "fastapi/routing.py::_get_resolved_absolute_path::L1850", "text": "# File: fastapi/routing.py | Symbol: _get_resolved_absolute_path\ndef _get_resolved_absolute_path(path: str | os.PathLike[str]) -> str:\n return os.path.realpath(os.fspath(path))", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_get_resolved_absolute_path", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1850-L1851", "start_line": 1850, "end_line": 1851} +{"id": "fastapi/routing.py::_FrontendStaticFiles::L1854", "text": "# File: fastapi/routing.py | Symbol: _FrontendStaticFiles\nclass _FrontendStaticFiles(StaticFiles):\n def __init__(\n self,\n *,\n directory: str | os.PathLike[str],\n fallback: Literal[\"auto\", \"index.html\", \"404.html\"] | None,\n check_dir: bool = True,\n ) -> None:\n self.fallback = fallback\n if check_dir and not os.path.isdir(directory):\n raise RuntimeError(\n f\"Frontend directory '{directory}' does not exist. \"\n f\"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'\"\n )\n super().__init__(\n directory=directory,\n html=True,\n check_dir=check_dir,\n follow_symlink=False,\n )\n if check_dir and fallback in {\"index.html\", \"404.html\"}:\n self._check_fallback_file(fallback)\n\n def _check_fallback_file(self, fallback: str) -> None:\n _, stat_result = self.lookup_path(fallback)\n if stat_result is None or not stat.S_ISREG(stat_result.st_mode):\n raise RuntimeError(\n f\"Frontend fallback file '{fallback}' does not exist in \"\n f\"directory '{self.directory}'. Resolved absolute directory: \"\n f\"'{self._get_resolved_directory()}'\"\n )\n\n def _get_resolved_directory(self) -> str:\n assert self.directory is not None\n return _get_resolved_absolute_path(self.directory)\n\n def get_path(self, scope: Scope) -> str:\n path = _get_fastapi_scope(scope).get(_FASTAPI_FRONTEND_PATH_KEY, \"\")\n assert isinstance(path, str)\n return os.path.normpath(os.path.join(*path.split(\"/\")))\n\n async def get_response(self, path: str, scope: Scope) -> Response:\n if scope[\"method\"] not in (\"GET\", \"HEAD\"):\n if await self._lookup_static_resource(path) is not None:\n raise HTTPException(status_code=405)\n raise HTTPException(status_code=404)\n\n static_resource = await self._lookup_static_resource(path)\n if static_resource is not None:\n full_path, stat_result, is_directory_index = static_resource\n if is_directory_index and not scope[\"path\"].endswith(\"/\"):\n url = URL(scope=scope)\n url = url.replace(path=url.path + \"/\")\n return RedirectResponse(url=url)\n return self.file_response(full_path, stat_result, scope)\n\n if self.fallback == \"404.html\" or (\n self.fallback == \"auto\" and self._fallback_file_exists(\"404.html\")\n ):\n return await self._fallback_response(\"404.html\", scope, status_code=404)\n\n if (\n self.fallback == \"index.html\"\n or (self.fallback == \"auto\" and self._fallback_file_exists(\"index.html\"))\n ) and _is_frontend_navigation_request(scope):\n return await self._fallback_response(\"index.html\", scope, status_code=200)\n\n raise HTTPException(status_code=404)\n\n async def _lookup_path(self, path: str) -> tuple[str, os.stat_result | None]:\n try:\n return await run_in_threadpool(self.lookup_path, path)\n except PermissionError:\n raise HTTPException(status_code=401) from None\n except OSError as exc:\n if exc.errno == errno.ENAMETOOLONG:\n raise HTTPException(status_code=404) from None\n raise exc\n except ValueError:\n raise HTTPException(status_code=404) from None\n\n async def _lookup_static_resource(\n self, path: str\n ) -> tuple[str, os.stat_result, bool] | None:\n full_path, stat_result = await self._lookup_path(path)\n if stat_result is None:\n return None\n if stat.S_ISREG(stat_result.st_mode):\n return full_path, stat_result, False\n if stat.S_ISDIR(stat_result.st_mode):\n index_path = os.path.join(path, \"index.html\")\n full_path, stat_result = await self._lookup_path(index_path)\n if stat_result is not None and stat.S_ISREG(stat_result.st_mode):\n return full_path, stat_result, True\n return None\n\n def _fallback_file_exists(self, fallback: str) -> bool:\n _, stat_result = self.lookup_path(fallback)\n return stat_result is not None and stat.S_ISREG(stat_result.st_mode)\n\n async def _fallback_response(\n self, fallback: str, scope: Scope, *, status_code: int\n ) -> Response:\n full_path, stat_result = await run_in_threadpool(self.lookup_path, fallback)\n if stat_result is None or not stat.S_ISREG(stat_result.st_mode):\n raise RuntimeError(\n f\"Frontend fallback file '{fallback}' does not exist in \"\n f\"directory '{self.directory}'. Resolved absolute directory: \"\n f\"'{self._get_resolved_directory()}'\"\n )\n return self.file_response(\n full_path, stat_result, scope, status_code=status_code\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_FrontendStaticFiles", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1854-L1966", "start_line": 1854, "end_line": 1966} +{"id": "fastapi/routing.py::_iter_accept_media_types::L1969", "text": "# File: fastapi/routing.py | Symbol: _iter_accept_media_types\ndef _iter_accept_media_types(accept: str) -> Iterator[tuple[str, float]]:\n for raw_value in accept.split(\",\"):\n message = email.message.Message()\n message[\"content-type\"] = raw_value.strip()\n q = message.get_param(\"q\")\n quality = 1.0\n if isinstance(q, str):\n try:\n quality = float(q)\n except ValueError:\n pass\n yield (\n f\"{message.get_content_maintype()}/{message.get_content_subtype()}\",\n quality,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_iter_accept_media_types", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1969-L1983", "start_line": 1969, "end_line": 1983} +{"id": "fastapi/routing.py::_is_frontend_navigation_request::L1986", "text": "# File: fastapi/routing.py | Symbol: _is_frontend_navigation_request\ndef _is_frontend_navigation_request(scope: Scope) -> bool:\n route_path = get_route_path(scope)\n final_segment = route_path.rsplit(\"/\", 1)[-1]\n if os.path.splitext(final_segment)[1]:\n return False\n request = Request(scope)\n wildcard_accepted = False\n html_rejected = False\n for media_type, quality in _iter_accept_media_types(\n request.headers.get(\"accept\", \"\")\n ):\n if media_type in {\"text/html\", \"application/xhtml+xml\"}:\n if quality == 0:\n html_rejected = True\n else:\n return True\n elif media_type == \"*/*\" and quality != 0:\n wildcard_accepted = True\n return wildcard_accepted and not html_rejected", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_is_frontend_navigation_request", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1986-L2004", "start_line": 1986, "end_line": 2004} +{"id": "fastapi/routing.py::_FrontendRoute::L2007", "text": "# File: fastapi/routing.py | Symbol: _FrontendRoute\nclass _FrontendRoute(BaseRoute):\n def __init__(\n self,\n path: str,\n *,\n directory: str | os.PathLike[str],\n fallback: Literal[\"auto\", \"index.html\", \"404.html\"] | None = \"auto\",\n check_dir: bool = True,\n ) -> None:\n if fallback not in {\"auto\", \"index.html\", \"404.html\", None}:\n raise AssertionError(\n \"fallback must be 'auto', 'index.html', '404.html', or None\"\n )\n self.path = _normalize_frontend_path(path)\n self.methods = {\"GET\", \"HEAD\"}\n self.app = _FrontendStaticFiles(\n directory=directory, fallback=fallback, check_dir=check_dir\n )\n\n def matches(self, scope: Scope) -> tuple[Match, Scope]:\n return self.matches_with_path(scope, self.path)\n\n def matches_with_path(self, scope: Scope, path: str) -> tuple[Match, Scope]:\n if scope[\"type\"] != \"http\":\n return Match.NONE, {}\n frontend_path = self._get_frontend_path(path, get_route_path(scope))\n if frontend_path is None:\n return Match.NONE, {}\n child_scope = {\n _FASTAPI_SCOPE_KEY: {\n _FASTAPI_FRONTEND_PATH_KEY: frontend_path,\n _FASTAPI_FRONTEND_SPECIFICITY_KEY: _frontend_path_specificity(path),\n }\n }\n if scope[\"method\"] not in self.methods:\n return Match.PARTIAL, child_scope\n return Match.FULL, child_scope\n\n def _get_frontend_path(self, path: str, route_path: str) -> str | None:\n if path == \"/\":\n return route_path.lstrip(\"/\")\n if route_path == path:\n return \"\"\n prefix = path + \"/\"\n if route_path.startswith(prefix):\n return route_path[len(prefix) :]\n return None\n\n async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n await self.app(scope, receive, send)\n\n def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:\n raise NoMatchFound(name, path_params)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_FrontendRoute", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2007-L2059", "start_line": 2007, "end_line": 2059} +{"id": "fastapi/routing.py::_FrontendRouteGroup::L2062", "text": "# File: fastapi/routing.py | Symbol: _FrontendRouteGroup\nclass _FrontendRouteGroup(BaseRoute):\n def __init__(\n self,\n *,\n dependencies: Sequence[params.Depends] | None = None,\n dependency_overrides_provider: Any | None = None,\n ) -> None:\n self.routes: list[_FrontendRoute] = []\n self.dependencies = list(dependencies or [])\n self.dependency_overrides_provider = dependency_overrides_provider\n (\n self.dependant,\n self._flat_dependant,\n self._embed_body_fields,\n ) = _build_dependant_with_parameterless_dependencies(\n path=\"\",\n call=_frontend_dependency_endpoint,\n dependencies=self.dependencies,\n )\n\n def add_frontend_route(\n self,\n path: str,\n *,\n directory: str | os.PathLike[str],\n fallback: Literal[\"auto\", \"index.html\", \"404.html\"] | None = \"auto\",\n check_dir: bool = True,\n ) -> None:\n self.routes.append(\n _FrontendRoute(\n path,\n directory=directory,\n fallback=fallback,\n check_dir=check_dir,\n )\n )\n\n def matches(self, scope: Scope) -> tuple[Match, Scope]:\n match, child_scope, _ = self._match(scope, prefix=\"\")\n return match, child_scope\n\n def matches_with_prefix(self, scope: Scope, prefix: str) -> tuple[Match, Scope]:\n match, child_scope, _ = self._match(scope, prefix=prefix)\n return match, child_scope\n\n def _match(\n self, scope: Scope, *, prefix: str\n ) -> tuple[Match, Scope, _FrontendRoute | None]:\n full: tuple[Scope, _FrontendRoute, int] | None = None\n partial: tuple[Scope, _FrontendRoute, int] | None = None\n for route in self.routes:\n path = _join_frontend_paths(prefix, route.path)\n match, child_scope = route.matches_with_path(scope, path)\n specificity = _frontend_path_specificity(path)\n if match == Match.FULL:\n if full is None or specificity > full[2]:\n full = (child_scope, route, specificity)\n elif match == Match.PARTIAL:\n if partial is None or specificity > partial[2]:\n partial = (child_scope, route, specificity)\n if full is not None:\n child_scope, route, _ = full\n return Match.FULL, child_scope, route\n if partial is not None:\n child_scope, route, _ = partial\n return Match.PARTIAL, child_scope, route\n return Match.NONE, {}, None\n\n async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n effective_context = _get_scope_effective_route_context(scope)\n if (\n isinstance(effective_context, _EffectiveRouteContext)\n and effective_context.original_route is self\n ):\n prefix = effective_context.frontend_prefix\n dependant = effective_context.dependant\n dependency_overrides_provider = (\n effective_context.dependency_overrides_provider\n )\n embed_body_fields = effective_context._embed_body_fields\n else:\n prefix = \"\"\n dependant = self.dependant\n dependency_overrides_provider = self.dependency_overrides_provider\n embed_body_fields = self._embed_body_fields\n match, child_scope, route = self._match(scope, prefix=prefix)\n if match == Match.NONE or route is None:\n raise HTTPException(status_code=404)\n _update_scope(scope, child_scope)\n if match == Match.FULL and dependant and dependant.dependencies:\n async with self._solve_dependencies(\n scope,\n receive,\n send,\n dependant=dependant,\n dependency_overrides_provider=dependency_overrides_provider,\n embed_body_fields=embed_body_fields,\n ):\n await route.handle(scope, receive, send)\n return\n await route.handle(scope, receive, send)\n\n def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:\n raise NoMatchFound(name, path_params)\n\n # TODO: probably move this out of the Route / Route Group, same in APIRoute\n # this should probably be top level FastAPI logic, not part of APIRoute and\n # duplicated here\n @asynccontextmanager\n async def _solve_dependencies(\n self,\n scope: Scope,\n receive: Receive,\n send: Send,\n *,\n dependant: Dependant,\n dependency_overrides_provider: Any | None,\n embed_body_fields: bool,\n ) -> AsyncIterator[None]:\n request = Request(scope, receive, send)\n previous_inner_astack = scope.get(\"fastapi_inner_astack\", _SCOPE_MISSING)\n previous_function_astack = scope.get(\"fastapi_function_astack\", _SCOPE_MISSING)\n try:\n async with AsyncExitStack() as request_stack:\n scope[\"fastapi_inner_astack\"] = request_stack\n async with AsyncExitStack() as function_stack:\n scope[\"fastapi_function_astack\"] = function_stack\n solved_result = await solve_dependencies(\n request=request,\n dependant=dependant,\n dependency_overrides_provider=dependency_overrides_provider,\n async_exit_stack=request_stack,\n embed_body_fields=embed_body_fields,\n )\n if solved_result.errors:\n raise RequestValidationError(solved_result.errors)\n yield\n finally:\n if previous_inner_astack is _SCOPE_MISSING:\n scope.pop(\"fastapi_inner_astack\", None)\n else:\n scope[\"fastapi_inner_astack\"] = previous_inner_astack\n if previous_function_astack is _SCOPE_MISSING:\n scope.pop(\"fastapi_function_astack\", None)\n else:\n scope[\"fastapi_function_astack\"] = previous_function_astack", "source_type": "code", "path": "fastapi/routing.py", "symbol": "_FrontendRouteGroup", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2062-L2207", "start_line": 2062, "end_line": 2207} +{"id": "fastapi/routing.py::APIRouter.__init__::L2237", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.__init__\ndef __init__(\n self,\n *,\n prefix: Annotated[str, Doc(\"An optional path prefix for the router.\")] = \"\",\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n \"\"\"\n ),\n ] = None,\n default_response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n routes: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n You normally wouldn't use this parameter with FastAPI, it is inherited\n from Starlette and supported for compatibility.\n\n In FastAPI, you normally would use the *path operation methods*,\n like `router.get()`, `router.post()`, etc.\n \"\"\"\n ),\n ] = None,\n redirect_slashes: Annotated[\n bool,\n Doc(\n \"\"\"\n Whether to detect and redirect slashes in URLs when the client doesn't\n use the same format.\n \"\"\"\n ),\n ] = True,\n default: Annotated[\n ASGIApp | None,\n Doc(\n \"\"\"\n Default function handler for this router. Used to handle\n 404 Not Found errors.\n \"\"\"\n ),\n ] = None,\n dependency_overrides_provider: Annotated[\n Any | None,\n Doc(\n \"\"\"\n Only used internally by FastAPI to handle dependency overrides.\n\n You shouldn't need to use it. It normally points to the `FastAPI` app\n object.\n \"\"\"\n ),\n ] = None,\n route_class: Annotated[\n type[APIRoute],\n Doc(\n \"\"\"\n Custom route (*path operation*) class to be used by this router.\n\n Read more about it in the\n [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).\n \"\"\"\n ),\n ] = APIRoute,\n on_startup: Annotated[\n Sequence[Callable[[], Any]] | None,\n Doc(\n \"\"\"\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n ),\n ] = None,\n on_shutdown: Annotated[\n Sequence[Callable[[], Any]] | None,\n Doc(\n \"\"\"\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n ),\n ] = None,\n # the generic to Lifespan[AppType] is the type of the top level application\n # which the router cannot know statically, so we use typing.Any\n lifespan: Annotated[\n Lifespan[Any] | None,\n Doc(\n \"\"\"\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) all the *path operations* in this router in the\n generated OpenAPI.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n strict_content_type: Annotated[\n bool,\n Doc(\n \"\"\"\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n \"\"\"\n ),\n ] = Default(True),\n ) -> None:\n # Determine the lifespan context to use\n if lifespan is None:\n # Use the default lifespan that runs on_startup/on_shutdown handlers\n lifespan_context: Lifespan[Any] = _DefaultLifespan(self)\n elif inspect.isasyncgenfunction(lifespan):\n lifespan_context = asynccontextmanager(lifespan)\n elif inspect.isgeneratorfunction(lifespan):\n lifespan_context = _wrap_gen_lifespan_context(lifespan)\n else:\n lifespan_context = lifespan\n self.lifespan_context = lifespan_context\n\n super().__init__(\n routes=routes,\n redirect_slashes=redirect_slashes,\n default=default,\n lifespan=lifespan_context,\n )\n if prefix:\n assert prefix.startswith(\"/\"), \"A path prefix must start with '/'\"\n assert not prefix.endswith(\"/\"), (\n \"A path prefix must not end with '/', as the routes will start with '/'\"\n )\n\n # Handle on_startup/on_shutdown locally since Starlette removed support\n # Ref: https://github.com/Kludex/starlette/pull/3117\n # TODO: deprecate this once the lifespan (or alternative) interface is improved\n self.on_startup: list[Callable[[], Any]] = (\n [] if on_startup is None else list(on_startup)\n )\n self.on_shutdown: list[Callable[[], Any]] = (\n [] if on_shutdown is None else list(on_shutdown)\n )\n\n self.prefix = prefix\n self.tags: list[str | Enum] = tags or []\n self.dependencies = list(dependencies or [])\n self.deprecated = deprecated\n self.include_in_schema = include_in_schema\n self.responses = responses or {}\n self.callbacks = callbacks or []\n self.dependency_overrides_provider = dependency_overrides_provider\n self.route_class = route_class\n self.default_response_class = default_response_class\n self.generate_unique_id_function = generate_unique_id_function\n self.strict_content_type = strict_content_type\n self._routes_version = 0\n self._low_priority_routes: list[BaseRoute] = []\n self._frontend_routes: _FrontendRouteGroup | None = None", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.__init__", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2237-L2523", "start_line": 2237, "end_line": 2523} +{"id": "fastapi/routing.py::APIRouter._mark_routes_changed::L2525", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._mark_routes_changed\ndef _mark_routes_changed(self) -> None:\n self._routes_version += 1", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._mark_routes_changed", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2525-L2526", "start_line": 2525, "end_line": 2526} +{"id": "fastapi/routing.py::APIRouter._get_routes_version::L2528", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._get_routes_version\ndef _get_routes_version(self, seen: set[int] | None = None) -> int:\n if seen is None:\n seen = set()\n router_id = id(self)\n if router_id in seen:\n return self._routes_version\n seen.add(router_id)\n version = self._routes_version\n for route in self.routes:\n if isinstance(route, _IncludedRouter):\n version += route.original_router._get_routes_version(seen)\n return version", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._get_routes_version", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2528-L2539", "start_line": 2528, "end_line": 2539} +{"id": "fastapi/routing.py::APIRouter._contains_router::L2541", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._contains_router\ndef _contains_router(\n self, router: \"APIRouter\", seen: set[int] | None = None\n ) -> bool:\n if seen is None:\n seen = set()\n router_id = id(self)\n if router_id in seen:\n return False\n seen.add(router_id)\n for route in self.routes:\n if not isinstance(route, _IncludedRouter):\n continue\n if route.original_router is router:\n return True\n if route.original_router._contains_router(router, seen):\n return True\n return False", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._contains_router", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2541-L2557", "start_line": 2541, "end_line": 2557} +{"id": "fastapi/routing.py::APIRouter.add_route::L2559", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.add_route\ndef add_route(\n self,\n path: str,\n endpoint: Callable[[Request], Awaitable[Response] | Response],\n methods: Collection[str] | None = None,\n name: str | None = None,\n include_in_schema: bool = True,\n ) -> None:\n super().add_route(\n path,\n endpoint,\n methods=methods,\n name=name,\n include_in_schema=include_in_schema,\n )\n self._mark_routes_changed()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.add_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2559-L2574", "start_line": 2559, "end_line": 2574} +{"id": "fastapi/routing.py::APIRouter.add_websocket_route::L2576", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.add_websocket_route\ndef add_websocket_route(\n self,\n path: str,\n endpoint: Callable[[WebSocket], Awaitable[None]],\n name: str | None = None,\n ) -> None:\n super().add_websocket_route(path, endpoint, name=name)\n self._mark_routes_changed()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.add_websocket_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2576-L2583", "start_line": 2576, "end_line": 2583} +{"id": "fastapi/routing.py::APIRouter.frontend::L2585", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.frontend\ndef frontend(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path prefix where the frontend build should be served.\n \"\"\"\n ),\n ],\n *,\n directory: Annotated[\n str | os.PathLike[str],\n Doc(\n \"\"\"\n The directory containing the static frontend build output.\n \"\"\"\n ),\n ],\n fallback: Annotated[\n Literal[\"auto\", \"index.html\", \"404.html\"] | None,\n Doc(\n \"\"\"\n The fallback file behavior for missing frontend paths.\n \"\"\"\n ),\n ] = \"auto\",\n check_dir: Annotated[\n bool,\n Doc(\n \"\"\"\n Check that the frontend directory exists when the app is created.\n \"\"\"\n ),\n ] = True,\n ) -> None:\n \"\"\"\n Serve a static frontend build as low-priority routes.\n\n Use this for frontend tools that build static files into a directory,\n such as `dist`. **FastAPI** path operations are checked first, and\n the frontend files are checked only if no normal route matched.\n\n A typical project could look like this:\n\n ```text\n .\n ├── pyproject.toml\n ├── app\n │ ├── __init__.py\n │ └── main.py\n └── dist\n ├── index.html\n └── assets\n └── app.js\n ```\n\n Then in `app/main.py`:\n\n ```python\n from fastapi import APIRouter, FastAPI\n\n app = FastAPI()\n router = APIRouter()\n router.frontend(\"/\", directory=\"dist\")\n app.include_router(router)\n ```\n \"\"\"\n normalized_path = _normalize_frontend_path(path)\n if self._frontend_routes is None:\n self._frontend_routes = _FrontendRouteGroup(\n dependencies=self.dependencies,\n dependency_overrides_provider=self.dependency_overrides_provider,\n )\n self._low_priority_routes.append(self._frontend_routes)\n self._frontend_routes.add_frontend_route(\n _join_frontend_paths(self.prefix, normalized_path),\n directory=directory,\n fallback=fallback,\n check_dir=check_dir,\n )\n self._mark_routes_changed()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.frontend", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2585-L2666", "start_line": 2585, "end_line": 2666} +{"id": "fastapi/routing.py::APIRouter.app::L2668", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.app\nasync def app(self, scope: Scope, receive: Receive, send: Send) -> None:\n assert scope[\"type\"] in (\"http\", \"websocket\", \"lifespan\")\n\n if \"router\" not in scope:\n scope[\"router\"] = self\n\n if scope[\"type\"] == \"lifespan\":\n await self.lifespan(scope, receive, send)\n return\n\n partial: tuple[BaseRoute, Scope] | None = None\n for route in self.routes:\n match, child_scope = route.matches(scope)\n if match == Match.FULL:\n scope.update(child_scope)\n await route.handle(scope, receive, send)\n return\n if match == Match.PARTIAL and partial is None:\n partial = (route, child_scope)\n\n if partial is not None:\n route, child_scope = partial\n scope.update(child_scope)\n await route.handle(scope, receive, send)\n return\n\n route_path = get_route_path(scope)\n if scope[\"type\"] == \"http\" and self.redirect_slashes and route_path != \"/\":\n redirect_scope = dict(scope)\n if route_path.endswith(\"/\"):\n redirect_scope[\"path\"] = redirect_scope[\"path\"].rstrip(\"/\")\n else:\n redirect_scope[\"path\"] = redirect_scope[\"path\"] + \"/\"\n\n for route in self.routes:\n match, _ = route.matches(redirect_scope)\n if match != Match.NONE:\n redirect_url = URL(scope=redirect_scope)\n response = RedirectResponse(url=str(redirect_url))\n await response(scope, receive, send)\n return\n\n (\n low_priority_match,\n low_priority_scope,\n low_priority_route,\n low_priority_context,\n ) = self._match_low_priority(scope)\n if low_priority_match != Match.NONE and low_priority_route is not None:\n _update_scope(scope, low_priority_scope)\n if low_priority_context is not None:\n _get_fastapi_scope(scope)[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = (\n low_priority_context\n )\n original_route = low_priority_context.original_route\n if isinstance(original_route, APIRoute):\n scope[\"route\"] = original_route\n await original_route.handle(scope, receive, send)\n return\n await low_priority_route.handle(scope, receive, send)\n return\n\n await self.default(scope, receive, send)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.app", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2668-L2730", "start_line": 2668, "end_line": 2730} +{"id": "fastapi/routing.py::APIRouter.handle::L2732", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.handle\nasync def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n included_router = _get_scope_included_router(scope)\n if (\n isinstance(included_router, _IncludedRouter)\n and included_router.original_router is self\n ):\n await included_router._handle_selected(scope, receive, send)\n return\n await self.app(scope, receive, send)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.handle", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2732-L2740", "start_line": 2732, "end_line": 2740} +{"id": "fastapi/routing.py::APIRouter.matches::L2742", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.matches\ndef matches(self, scope: Scope) -> tuple[Match, Scope]:\n included_router = _get_scope_included_router(scope)\n if (\n isinstance(included_router, _IncludedRouter)\n and included_router.original_router is self\n ):\n match, child_scope, _, _ = included_router._match(scope)\n return match, child_scope\n return Match.NONE, {}", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.matches", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2742-L2750", "start_line": 2742, "end_line": 2750} +{"id": "fastapi/routing.py::APIRouter._iter_low_priority_routes::L2752", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._iter_low_priority_routes\ndef _iter_low_priority_routes(\n self,\n ) -> Iterator[BaseRoute | _EffectiveRouteContext]:\n yield from self._low_priority_routes\n for route in self.routes:\n if isinstance(route, _IncludedRouter):\n yield from route.effective_low_priority_routes()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._iter_low_priority_routes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2752-L2758", "start_line": 2752, "end_line": 2758} +{"id": "fastapi/routing.py::APIRouter._match_low_priority::L2760", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._match_low_priority\ndef _match_low_priority(\n self, scope: Scope\n ) -> tuple[Match, Scope, BaseRoute | None, _EffectiveRouteContext | None]:\n full: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None\n partial: tuple[Scope, BaseRoute, _EffectiveRouteContext | None] | None = None\n for candidate in self._iter_low_priority_routes():\n route: BaseRoute\n if isinstance(candidate, _EffectiveRouteContext):\n route_context: _EffectiveRouteContext | None = candidate\n original_route = candidate.original_route\n if isinstance(original_route, APIRoute):\n fastapi_scope = _get_fastapi_scope(scope)\n previous_context = fastapi_scope.get(\n _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY, _SCOPE_MISSING\n )\n fastapi_scope[_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY] = route_context\n try:\n match, child_scope = original_route.matches(scope)\n finally:\n _restore_fastapi_scope_key(\n scope,\n _FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY,\n previous_context,\n )\n route = original_route\n else:\n match, child_scope = candidate.matches(scope)\n route = candidate.starlette_route or original_route\n else:\n route_context = None\n match, child_scope = candidate.matches(scope)\n route = candidate\n if match == Match.FULL:\n if full is None or self._frontend_match_is_more_specific(\n child_scope, full[0]\n ):\n full = (child_scope, route, route_context)\n elif match == Match.PARTIAL:\n if partial is None or self._frontend_match_is_more_specific(\n child_scope, partial[0]\n ):\n partial = (child_scope, route, route_context)\n if full is not None:\n child_scope, route, route_context = full\n return Match.FULL, child_scope, route, route_context\n if partial is not None:\n child_scope, route, route_context = partial\n return Match.PARTIAL, child_scope, route, route_context\n return Match.NONE, {}, None, None", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._match_low_priority", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2760-L2808", "start_line": 2760, "end_line": 2808} +{"id": "fastapi/routing.py::APIRouter._frontend_match_is_more_specific::L2810", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._frontend_match_is_more_specific\ndef _frontend_match_is_more_specific(\n self, child_scope: Scope, previous_child_scope: Scope\n ) -> bool:\n specificity = _frontend_scope_specificity(child_scope)\n previous_specificity = _frontend_scope_specificity(previous_child_scope)\n if specificity is None or previous_specificity is None:\n return False\n return specificity > previous_specificity", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._frontend_match_is_more_specific", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2810-L2817", "start_line": 2810, "end_line": 2817} +{"id": "fastapi/routing.py::APIRouter.route::L2819", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.route\ndef route(\n self,\n path: str,\n methods: Collection[str] | None = None,\n name: str | None = None,\n include_in_schema: bool = True,\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_route(\n path,\n func,\n methods=methods,\n name=name,\n include_in_schema=include_in_schema,\n )\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2819-L2836", "start_line": 2819, "end_line": 2836} +{"id": "fastapi/routing.py::APIRouter.add_api_route::L2838", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.add_api_route\ndef add_api_route(\n self,\n path: str,\n endpoint: Callable[..., Any],\n *,\n response_model: Any = Default(None),\n status_code: int | None = None,\n tags: list[str | Enum] | None = None,\n dependencies: Sequence[params.Depends] | None = None,\n summary: str | None = None,\n description: str | None = None,\n response_description: str = \"Successful Response\",\n responses: dict[int | str, dict[str, Any]] | None = None,\n deprecated: bool | None = None,\n methods: set[str] | list[str] | None = None,\n operation_id: str | None = None,\n response_model_include: IncEx | None = None,\n response_model_exclude: IncEx | None = None,\n response_model_by_alias: bool = True,\n response_model_exclude_unset: bool = False,\n response_model_exclude_defaults: bool = False,\n response_model_exclude_none: bool = False,\n include_in_schema: bool = True,\n response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),\n name: str | None = None,\n route_class_override: type[APIRoute] | None = None,\n callbacks: list[BaseRoute] | None = None,\n openapi_extra: dict[str, Any] | None = None,\n generate_unique_id_function: Callable[[APIRoute], str]\n | DefaultPlaceholder = Default(generate_unique_id),\n strict_content_type: bool | DefaultPlaceholder = Default(True),\n ) -> None:\n route_class = route_class_override or self.route_class\n responses = responses or {}\n combined_responses = {**self.responses, **responses}\n current_response_class = get_value_or_default(\n response_class, self.default_response_class\n )\n current_tags = self.tags.copy()\n if tags:\n current_tags.extend(tags)\n current_dependencies = self.dependencies.copy()\n if dependencies:\n current_dependencies.extend(dependencies)\n current_callbacks = self.callbacks.copy()\n if callbacks:\n current_callbacks.extend(callbacks)\n current_generate_unique_id = get_value_or_default(\n generate_unique_id_function, self.generate_unique_id_function\n )\n route = route_class(\n self.prefix + path,\n endpoint=endpoint,\n response_model=response_model,\n status_code=status_code,\n tags=current_tags,\n dependencies=current_dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=combined_responses,\n deprecated=deprecated or self.deprecated,\n methods=methods,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema and self.include_in_schema,\n response_class=current_response_class,\n name=name,\n dependency_overrides_provider=self.dependency_overrides_provider,\n callbacks=current_callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=current_generate_unique_id,\n strict_content_type=get_value_or_default(\n strict_content_type, self.strict_content_type\n ),\n )\n self.routes.append(route)\n self._mark_routes_changed()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.add_api_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2838-L2920", "start_line": 2838, "end_line": 2920} +{"id": "fastapi/routing.py::APIRouter.api_route::L2922", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.api_route\ndef api_route(\n self,\n path: str,\n *,\n response_model: Any = Default(None),\n status_code: int | None = None,\n tags: list[str | Enum] | None = None,\n dependencies: Sequence[params.Depends] | None = None,\n summary: str | None = None,\n description: str | None = None,\n response_description: str = \"Successful Response\",\n responses: dict[int | str, dict[str, Any]] | None = None,\n deprecated: bool | None = None,\n methods: list[str] | None = None,\n operation_id: str | None = None,\n response_model_include: IncEx | None = None,\n response_model_exclude: IncEx | None = None,\n response_model_by_alias: bool = True,\n response_model_exclude_unset: bool = False,\n response_model_exclude_defaults: bool = False,\n response_model_exclude_none: bool = False,\n include_in_schema: bool = True,\n response_class: type[Response] = Default(JSONResponse),\n name: str | None = None,\n callbacks: list[BaseRoute] | None = None,\n openapi_extra: dict[str, Any] | None = None,\n generate_unique_id_function: Callable[[APIRoute], str] = Default(\n generate_unique_id\n ),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_api_route(\n path,\n func,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=methods,\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.api_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2922-L2982", "start_line": 2922, "end_line": 2982} +{"id": "fastapi/routing.py::APIRouter.add_api_websocket_route::L2984", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.add_api_websocket_route\ndef add_api_websocket_route(\n self,\n path: str,\n endpoint: Callable[..., Any],\n name: str | None = None,\n *,\n dependencies: Sequence[params.Depends] | None = None,\n ) -> None:\n current_dependencies = self.dependencies.copy()\n if dependencies:\n current_dependencies.extend(dependencies)\n\n route = APIWebSocketRoute(\n self.prefix + path,\n endpoint=endpoint,\n name=name,\n dependencies=current_dependencies,\n dependency_overrides_provider=self.dependency_overrides_provider,\n )\n self.routes.append(route)\n self._mark_routes_changed()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.add_api_websocket_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L2984-L3004", "start_line": 2984, "end_line": 3004} +{"id": "fastapi/routing.py::APIRouter.websocket::L3006", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.websocket\ndef websocket(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n WebSocket path.\n \"\"\"\n ),\n ],\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n A name for the WebSocket. Only used internally.\n \"\"\"\n ),\n ] = None,\n *,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be used for this\n WebSocket.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n \"\"\"\n ),\n ] = None,\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Decorate a WebSocket function.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n **Example**\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI, WebSocket\n\n app = FastAPI()\n router = APIRouter()\n\n @router.websocket(\"/ws\")\n async def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n while True:\n data = await websocket.receive_text()\n await websocket.send_text(f\"Message text was: {data}\")\n\n app.include_router(router)\n ```\n \"\"\"\n\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_api_websocket_route(\n path, func, name=name, dependencies=dependencies\n )\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.websocket", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L3006-L3071", "start_line": 3006, "end_line": 3071} +{"id": "fastapi/routing.py::APIRouter.websocket_route::L3073", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.websocket_route\ndef websocket_route(\n self, path: str, name: str | None = None\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_websocket_route(path, func, name=name)\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.websocket_route", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L3073-L3080", "start_line": 3073, "end_line": 3080} +{"id": "fastapi/routing.py::APIRouter.include_router::L3082", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.include_router\ndef include_router(\n self,\n router: Annotated[\"APIRouter\", Doc(\"The `APIRouter` to include.\")],\n *,\n prefix: Annotated[str, Doc(\"An optional path prefix for the router.\")] = \"\",\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n \"\"\"\n ),\n ] = None,\n default_response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include (or not) all the *path operations* in this router in the\n generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = True,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> None:\n \"\"\"\n Include another `APIRouter` in the same current `APIRouter`.\n\n Read more about it in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n\n app = FastAPI()\n internal_router = APIRouter()\n users_router = APIRouter()\n\n @users_router.get(\"/users/\")\n def read_users():\n return [{\"name\": \"Rick\"}, {\"name\": \"Morty\"}]\n\n internal_router.include_router(users_router)\n app.include_router(internal_router)\n ```\n \"\"\"\n assert self is not router, (\n \"Cannot include the same APIRouter instance into itself. \"\n \"Did you mean to include a different router?\"\n )\n assert not router._contains_router(self), (\n \"Cannot include an APIRouter instance that already includes this router. \"\n \"Did you mean to include a different router?\"\n )\n if prefix:\n assert prefix.startswith(\"/\"), \"A path prefix must start with '/'\"\n assert not prefix.endswith(\"/\"), (\n \"A path prefix must not end with '/', as the routes will start with '/'\"\n )\n else:\n for route, route_context in _iter_routes_with_context(router.routes):\n if route_context is None:\n path = getattr(route, \"path\", None)\n name = getattr(route, \"name\", \"unknown\")\n elif route_context.starlette_route is not None:\n path = getattr(route_context.starlette_route, \"path\", None)\n name = getattr(route_context.starlette_route, \"name\", \"unknown\")\n else:\n path = route_context.path\n name = route_context.name\n if path is not None and not path:\n raise FastAPIError(\n f\"Prefix and path cannot be both empty (path operation: {name})\"\n )\n include_context = _RouterIncludeContext.for_include(\n parent_router=self,\n included_router=router,\n prefix=prefix,\n tags=tags,\n dependencies=dependencies,\n default_response_class=default_response_class,\n responses=responses,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n generate_unique_id_function=generate_unique_id_function,\n )\n self.routes.append(\n _IncludedRouter(original_router=router, include_context=include_context)\n )\n self._mark_routes_changed()\n for handler in router.on_startup:\n self.add_event_handler(\"startup\", handler)\n for handler in router.on_shutdown:\n self.add_event_handler(\"shutdown\", handler)\n self.lifespan_context = _merge_lifespan_context(\n self.lifespan_context,\n router.lifespan_context,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.include_router", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L3082-L3269", "start_line": 3082, "end_line": 3269} +{"id": "fastapi/routing.py::APIRouter.get::L3271", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.get\ndef get(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP GET operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n\n app = FastAPI()\n router = APIRouter()\n\n @router.get(\"/items/\")\n def read_items():\n return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"GET\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.get", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L3271-L3646", "start_line": 3271, "end_line": 3646} +{"id": "fastapi/routing.py::APIRouter.put::L3648", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.put\ndef put(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP PUT operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n router = APIRouter()\n\n @router.put(\"/items/{item_id}\")\n def replace_item(item_id: str, item: Item):\n return {\"message\": \"Item replaced\", \"id\": item_id}\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"PUT\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.put", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L3648-L4028", "start_line": 3648, "end_line": 4028} +{"id": "fastapi/routing.py::APIRouter.post::L4030", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.post\ndef post(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP POST operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n router = APIRouter()\n\n @router.post(\"/items/\")\n def create_item(item: Item):\n return {\"message\": \"Item created\"}\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"POST\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.post", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L4030-L4410", "start_line": 4030, "end_line": 4410} +{"id": "fastapi/routing.py::APIRouter.delete::L4412", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.delete\ndef delete(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP DELETE operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n\n app = FastAPI()\n router = APIRouter()\n\n @router.delete(\"/items/{item_id}\")\n def delete_item(item_id: str):\n return {\"message\": \"Item deleted\"}\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"DELETE\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.delete", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L4412-L4787", "start_line": 4412, "end_line": 4787} +{"id": "fastapi/routing.py::APIRouter.options::L4789", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.options\ndef options(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP OPTIONS operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n\n app = FastAPI()\n router = APIRouter()\n\n @router.options(\"/items/\")\n def get_item_options():\n return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"OPTIONS\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.options", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L4789-L5164", "start_line": 4789, "end_line": 5164} +{"id": "fastapi/routing.py::APIRouter.head::L5166", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.head\ndef head(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP HEAD operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n router = APIRouter()\n\n @router.head(\"/items/\", status_code=204)\n def get_items_headers(response: Response):\n response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"HEAD\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.head", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L5166-L5546", "start_line": 5166, "end_line": 5546} +{"id": "fastapi/routing.py::APIRouter.patch::L5548", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.patch\ndef patch(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP PATCH operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n router = APIRouter()\n\n @router.patch(\"/items/\")\n def update_item(item: Item):\n return {\"message\": \"Item updated in place\"}\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"PATCH\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.patch", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L5548-L5928", "start_line": 5548, "end_line": 5928} +{"id": "fastapi/routing.py::APIRouter.trace::L5930", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.trace\ndef trace(\n self,\n path: Annotated[\n str,\n Doc(\n \"\"\"\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n \"\"\"\n ),\n ],\n *,\n response_model: Annotated[\n Any,\n Doc(\n \"\"\"\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n \"\"\"\n ),\n ] = Default(None),\n status_code: Annotated[\n int | None,\n Doc(\n \"\"\"\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n \"\"\"\n ),\n ] = None,\n tags: Annotated[\n list[str | Enum] | None,\n Doc(\n \"\"\"\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n \"\"\"\n ),\n ] = None,\n dependencies: Annotated[\n Sequence[params.Depends] | None,\n Doc(\n \"\"\"\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n \"\"\"\n ),\n ] = None,\n summary: Annotated[\n str | None,\n Doc(\n \"\"\"\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n \"\"\"\n ),\n ] = None,\n response_description: Annotated[\n str,\n Doc(\n \"\"\"\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = \"Successful Response\",\n responses: Annotated[\n dict[int | str, dict[str, Any]] | None,\n Doc(\n \"\"\"\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n operation_id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = None,\n response_model_include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = None,\n response_model_by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n \"\"\"\n ),\n ] = True,\n response_model_exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n \"\"\"\n ),\n ] = False,\n response_model_exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n \"\"\"\n ),\n ] = False,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n \"\"\"\n ),\n ] = True,\n response_class: Annotated[\n type[Response],\n Doc(\n \"\"\"\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n \"\"\"\n ),\n ] = Default(JSONResponse),\n name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Name for this *path operation*. Only used internally.\n \"\"\"\n ),\n ] = None,\n callbacks: Annotated[\n list[BaseRoute] | None,\n Doc(\n \"\"\"\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n \"\"\"\n ),\n ] = None,\n openapi_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n \"\"\"\n ),\n ] = None,\n generate_unique_id_function: Annotated[\n Callable[[APIRoute], str],\n Doc(\n \"\"\"\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n \"\"\"\n ),\n ] = Default(generate_unique_id),\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add a *path operation* using an HTTP TRACE operation.\n\n ## Example\n\n ```python\n from fastapi import APIRouter, FastAPI\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n description: str | None = None\n\n app = FastAPI()\n router = APIRouter()\n\n @router.trace(\"/items/{item_id}\")\n def trace_item(item_id: str):\n return None\n\n app.include_router(router)\n ```\n \"\"\"\n return self.api_route(\n path=path,\n response_model=response_model,\n status_code=status_code,\n tags=tags,\n dependencies=dependencies,\n summary=summary,\n description=description,\n response_description=response_description,\n responses=responses,\n deprecated=deprecated,\n methods=[\"TRACE\"],\n operation_id=operation_id,\n response_model_include=response_model_include,\n response_model_exclude=response_model_exclude,\n response_model_by_alias=response_model_by_alias,\n response_model_exclude_unset=response_model_exclude_unset,\n response_model_exclude_defaults=response_model_exclude_defaults,\n response_model_exclude_none=response_model_exclude_none,\n include_in_schema=include_in_schema,\n response_class=response_class,\n name=name,\n callbacks=callbacks,\n openapi_extra=openapi_extra,\n generate_unique_id_function=generate_unique_id_function,\n )", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.trace", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L5930-L6310", "start_line": 5930, "end_line": 6310} +{"id": "fastapi/routing.py::APIRouter._startup::L6313", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._startup\nasync def _startup(self) -> None:\n \"\"\"\n Run any `.on_startup` event handlers.\n\n This method is kept for backward compatibility after Starlette removed\n support for on_startup/on_shutdown handlers.\n\n Ref: https://github.com/Kludex/starlette/pull/3117\n \"\"\"\n for handler in self.on_startup:\n if is_async_callable(handler):\n await handler()\n else:\n handler()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._startup", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L6313-L6326", "start_line": 6313, "end_line": 6326} +{"id": "fastapi/routing.py::APIRouter._shutdown::L6329", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter._shutdown\nasync def _shutdown(self) -> None:\n \"\"\"\n Run any `.on_shutdown` event handlers.\n\n This method is kept for backward compatibility after Starlette removed\n support for on_startup/on_shutdown handlers.\n\n Ref: https://github.com/Kludex/starlette/pull/3117\n \"\"\"\n for handler in self.on_shutdown:\n if is_async_callable(handler):\n await handler()\n else:\n handler()", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter._shutdown", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L6329-L6342", "start_line": 6329, "end_line": 6342} +{"id": "fastapi/routing.py::APIRouter.add_event_handler::L6345", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.add_event_handler\ndef add_event_handler(\n self,\n event_type: str,\n func: Callable[[], Any],\n ) -> None:\n \"\"\"\n Add an event handler function for startup or shutdown.\n\n This method is kept for backward compatibility after Starlette removed\n support for on_startup/on_shutdown handlers.\n\n Ref: https://github.com/Kludex/starlette/pull/3117\n \"\"\"\n assert event_type in (\"startup\", \"shutdown\")\n if event_type == \"startup\":\n self.on_startup.append(func)\n else:\n self.on_shutdown.append(func)", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.add_event_handler", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L6345-L6362", "start_line": 6345, "end_line": 6362} +{"id": "fastapi/routing.py::APIRouter.on_event::L6364", "text": "# File: fastapi/routing.py | Class: APIRouter | Symbol: APIRouter.on_event\n@deprecated(\n \"\"\"\n on_event is deprecated, use lifespan event handlers instead.\n\n Read more about it in the\n [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n \"\"\"\n )\n def on_event(\n self,\n event_type: Annotated[\n str,\n Doc(\n \"\"\"\n The type of event. `startup` or `shutdown`.\n \"\"\"\n ),\n ],\n ) -> Callable[[DecoratedCallable], DecoratedCallable]:\n \"\"\"\n Add an event handler for the router.\n\n `on_event` is deprecated, use `lifespan` event handlers instead.\n\n Read more about it in the\n [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n \"\"\"\n\n def decorator(func: DecoratedCallable) -> DecoratedCallable:\n self.add_event_handler(event_type, func)\n return func\n\n return decorator", "source_type": "code", "path": "fastapi/routing.py", "symbol": "APIRouter.on_event", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L6364-L6396", "start_line": 6364, "end_line": 6396} +{"id": "fastapi/routing.py::", "text": "# File: fastapi/routing.py | Symbol: \nimport contextlib\nimport copy\nimport email.message\nimport errno\nimport functools\nimport inspect\nimport json\nimport os\nimport stat\nimport types\nfrom collections.abc import (\n AsyncIterator,\n Awaitable,\n Callable,\n Collection,\n Coroutine,\n Generator,\n Iterator,\n Mapping,\n Sequence,\n)\nfrom contextlib import (\n AbstractAsyncContextManager,\n AbstractContextManager,\n AsyncExitStack,\n asynccontextmanager,\n)\nfrom contextvars import ContextVar\nfrom dataclasses import dataclass, field\nfrom enum import Enum, IntEnum\nfrom typing import (\n Annotated,\n Any,\n Literal,\n Protocol,\n TypeVar,\n cast,\n)\nimport anyio\nfrom annotated_doc import Doc\nfrom anyio.abc import ObjectReceiveStream\nfrom fastapi import params\nfrom fastapi._compat import (\n ModelField,\n Undefined,\n lenient_issubclass,\n)\nfrom fastapi.datastructures import Default, DefaultPlaceholder\nfrom fastapi.dependencies.models import Dependant\nfrom fastapi.dependencies.utils import (\n _should_embed_body_fields,\n get_body_field,\n get_dependant,\n get_flat_dependant,\n get_parameterless_sub_dependant,\n get_stream_item_type,\n get_typed_return_annotation,\n solve_dependencies,\n)\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.exceptions import (\n EndpointContext,\n FastAPIError,\n RequestValidationError,\n ResponseValidationError,\n WebSocketRequestValidationError,\n)\nfrom fastapi.sse import (\n _PING_INTERVAL,\n KEEPALIVE_COMMENT,\n EventSourceResponse,\n ServerSentEvent,\n format_sse_event,\n)\nfrom fastapi.types import DecoratedCallable, IncEx\nfrom fastapi.utils import (\n create_model_field,\n generate_unique_id,\n get_value_or_default,\n is_body_allowed_for_status_code,\n)\nfrom starlette import routing\nfrom starlette._exception_handler import wrap_app_handling_exceptions\nfrom starlette._utils import get_route_path, is_async_callable\nfrom starlette.concurrency import iterate_in_threadpool, run_in_threadpool\nfrom starlette.datastructures import URL, FormData, URLPath\nfrom starlette.exceptions import HTTPException\nfrom starlette.requests import Request\nfrom starlette.responses import (\n JSONResponse,\n PlainTextResponse,\n RedirectResponse,\n Response,\n StreamingResponse,\n)\nfrom starlette.routing import (\n BaseRoute,\n Match,\n NoMatchFound,\n compile_path,\n get_name,\n)\nfrom starlette.routing import Mount as Mount # noqa\nfrom starlette.staticfiles import StaticFiles\nfrom starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send\nfrom starlette.websockets import WebSocket\nfrom typing_extensions import deprecated\n# Copy of starlette.routing.request_response modified to include the\n# dependencies' AsyncExitStack\n# Copy of starlette.routing.websocket_session modified to include the\n# dependencies' AsyncExitStack\n_T = TypeVar(\"_T\")\n# Vendored from starlette.routing to avoid importing private symbols\n# Vendored from starlette.routing to avoid importing private symbols\n# Cache for endpoint context to avoid re-extracting on every request\n_endpoint_context_cache: dict[int, EndpointContext] = {}\n_FASTAPI_SCOPE_KEY = \"fastapi\"\n_FASTAPI_EFFECTIVE_ROUTE_CONTEXT_KEY = \"effective_route_context\"\n_FASTAPI_FRONTEND_PATH_KEY = \"frontend_path\"\n_FASTAPI_FRONTEND_SPECIFICITY_KEY = \"frontend_specificity\"\n_FASTAPI_INCLUDED_ROUTER_KEY = \"included_router\"\n_effective_route_context_var: ContextVar[Any | None] = ContextVar(\n \"fastapi_effective_route_context\", default=None\n)\n_SCOPE_MISSING = object()\nclass APIRoute(routing.Route):\n stream_item_type: Any | None\n response_model: Any\n summary: str | None\n response_description: str\n deprecated: bool | None\n operation_id: str | None\n response_model_include: IncEx | None\n response_model_exclude: IncEx | None\n response_model_by_alias: bool\n response_model_exclude_unset: bool\n response_model_exclude_defaults: bool\n response_model_exclude_none: bool\n include_in_schema: bool\n response_class: type[Response] | DefaultPlaceholder\n dependency_overrides_provider: Any | None\n callbacks: list[BaseRoute] | None\n openapi_extra: dict[str, Any] | None\n generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder\n strict_content_type: bool | DefaultPlaceholder\n tags: list[str | Enum]\n responses: dict[int | str, dict[str, Any]]\n unique_id: str\n status_code: int | None\n response_field: ModelField | None\n stream_item_field: ModelField | None\n dependencies: list[params.Depends]\n description: str\n response_fields: dict[int | str, ModelField]\n dependant: Dependant\n _flat_dependant: Dependant\n _embed_body_fields: bool\n body_field: ModelField | None\n is_sse_stream: bool\n is_json_stream: bool\n@dataclass\nclass _EffectiveRouteContext:\n original_route: BaseRoute\n starlette_route: BaseRoute | None = None\n frontend_prefix: str = \"\"\n path: str = \"\"\n endpoint: Callable[..., Any] | None = None\n stream_item_type: Any | None = None\n response_model: Any = None\n summary: str | None = None\n response_description: str = \"Successful Response\"\n deprecated: bool | None = None\n operation_id: str | None = None\n response_model_include: IncEx | None = None\n response_model_exclude: IncEx | None = None\n response_model_by_alias: bool = True\n response_model_exclude_unset: bool = False\n response_model_exclude_defaults: bool = False\n response_model_exclude_none: bool = False\n include_in_schema: bool = True\n response_class: type[Response] | DefaultPlaceholder = field(\n default_factory=lambda: Default(JSONResponse)\n )\n dependency_overrides_provider: Any | None = None\n callbacks: list[BaseRoute] | None = None\n openapi_extra: dict[str, Any] | None = None\n generate_unique_id_function: Callable[[Any], str] | DefaultPlaceholder = field(\n default_factory=lambda: Default(generate_unique_id)\n )\n strict_content_type: bool | DefaultPlaceholder = field(\n default_factory=lambda: Default(True)\n )\n tags: list[str | Enum] = field(default_factory=list)\n responses: dict[int | str, dict[str, Any]] = field(default_factory=dict)\n name: str = \"\"\n path_regex: Any = None\n path_format: str = \"\"\n param_convertors: dict[str, Any] = field(default_factory=dict)\n methods: set[str] = field(default_factory=set)\n unique_id: str = \"\"\n status_code: int | None = None\n response_field: ModelField | None = None\n stream_item_field: ModelField | None = None\n dependencies: list[params.Depends] = field(default_factory=list)\n description: str = \"\"\n response_fields: dict[int | str, ModelField] = field(default_factory=dict)\n dependant: Dependant | None = None\n _flat_dependant: Dependant | None = None\n _embed_body_fields: bool = False\n body_field: ModelField | None = None\n is_sse_stream: bool = False\n is_json_stream: bool = False\n@dataclass\nclass _IncludedRouter(BaseRoute):\n original_router: \"APIRouter\"\n include_context: _RouterIncludeContext\n _effective_candidates: list[\"_EffectiveRouteContext | _IncludedRouter\"] = field(\n default_factory=list\n )\n _effective_candidates_version: int | None = None\n _effective_low_priority_routes: list[\"_EffectiveRouteContext\"] = field(\n default_factory=list\n )\n _effective_low_priority_routes_version: int | None = None\nclass APIRouter(routing.Router):\n \"\"\"\n `APIRouter` class, used to group *path operations*, for example to structure\n an app in multiple files. It would then be included in the `FastAPI` app, or\n in another `APIRouter` (ultimately included in the app).\n Read more about it in the\n [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/).\n ## Example\n ```python\n from fastapi import APIRouter, FastAPI\n app = FastAPI()\n router = APIRouter()\n @router.get(\"/users/\", tags=[\"users\"])\n async def read_users():\n return [{\"username\": \"Rick\"}, {\"username\": \"Morty\"}]\n app.include_router(router)\n ```\n \"\"\"\n # TODO: remove this once the lifespan (or alternative) interface is improved\n # TODO: remove this once the lifespan (or alternative) interface is improved\n # TODO: remove this once the lifespan (or alternative) interface is improved", "source_type": "code", "path": "fastapi/routing.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/routing.py#L1-L6344", "start_line": 1, "end_line": 6344} {"id": "fastapi/security/__init__.py::", "text": "# File: fastapi/security/__init__.py | Symbol: \nfrom .api_key import APIKeyCookie as APIKeyCookie\nfrom .api_key import APIKeyHeader as APIKeyHeader\nfrom .api_key import APIKeyQuery as APIKeyQuery\nfrom .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentials\nfrom .http import HTTPBasic as HTTPBasic\nfrom .http import HTTPBasicCredentials as HTTPBasicCredentials\nfrom .http import HTTPBearer as HTTPBearer\nfrom .http import HTTPDigest as HTTPDigest\nfrom .oauth2 import OAuth2 as OAuth2\nfrom .oauth2 import OAuth2AuthorizationCodeBearer as OAuth2AuthorizationCodeBearer\nfrom .oauth2 import OAuth2PasswordBearer as OAuth2PasswordBearer\nfrom .oauth2 import OAuth2PasswordRequestForm as OAuth2PasswordRequestForm\nfrom .oauth2 import OAuth2PasswordRequestFormStrict as OAuth2PasswordRequestFormStrict\nfrom .oauth2 import SecurityScopes as SecurityScopes\nfrom .open_id_connect_url import OpenIdConnect as OpenIdConnect", "source_type": "code", "path": "fastapi/security/__init__.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/__init__.py#L1-L15", "start_line": 1, "end_line": 15} {"id": "fastapi/security/api_key.py::APIKeyBase::L11", "text": "# File: fastapi/security/api_key.py | Symbol: APIKeyBase\nclass APIKeyBase(SecurityBase):\n model: APIKey\n\n def __init__(\n self,\n location: APIKeyIn,\n name: str,\n description: str | None,\n scheme_name: str | None,\n auto_error: bool,\n ):\n self.auto_error = auto_error\n\n self.model: APIKey = APIKey(\n **{\"in\": location}, # ty: ignore[invalid-argument-type]\n name=name,\n description=description,\n )\n self.scheme_name = scheme_name or self.__class__.__name__\n\n def make_not_authenticated_error(self) -> HTTPException:\n \"\"\"\n The WWW-Authenticate header is not standardized for API Key authentication but\n the HTTP specification requires that an error of 401 \"Unauthorized\" must\n include a WWW-Authenticate header.\n\n Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized\n\n For this, this method sends a custom challenge `APIKey`.\n \"\"\"\n return HTTPException(\n status_code=HTTP_401_UNAUTHORIZED,\n detail=\"Not authenticated\",\n headers={\"WWW-Authenticate\": \"APIKey\"},\n )\n\n def check_api_key(self, api_key: str | None) -> str | None:\n if not api_key:\n if self.auto_error:\n raise self.make_not_authenticated_error()\n return None\n return api_key", "source_type": "code", "path": "fastapi/security/api_key.py", "symbol": "APIKeyBase", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/api_key.py#L11-L52", "start_line": 11, "end_line": 52} {"id": "fastapi/security/api_key.py::APIKeyQuery::L55", "text": "# File: fastapi/security/api_key.py | Symbol: APIKeyQuery\nclass APIKeyQuery(APIKeyBase):\n \"\"\"\n API key authentication using a query parameter.\n\n This defines the name of the query parameter that should be provided in the request\n with the API key and integrates that into the OpenAPI documentation. It extracts\n the key value sent in the query parameter automatically and provides it as the\n dependency result. But it doesn't define how to send that API key to the client.\n\n ## Usage\n\n Create an instance object and use that object as the dependency in `Depends()`.\n\n The dependency result will be a string containing the key value.\n\n ## Example\n\n ```python\n from fastapi import Depends, FastAPI\n from fastapi.security import APIKeyQuery\n\n app = FastAPI()\n\n query_scheme = APIKeyQuery(name=\"api_key\")\n\n\n @app.get(\"/items/\")\n async def read_items(api_key: str = Depends(query_scheme)):\n return {\"api_key\": api_key}\n ```\n \"\"\"\n\n def __init__(\n self,\n *,\n name: Annotated[\n str,\n Doc(\"Query parameter name.\"),\n ],\n scheme_name: Annotated[\n str | None,\n Doc(\n \"\"\"\n Security scheme name.\n\n It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Security scheme description.\n\n It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n auto_error: Annotated[\n bool,\n Doc(\n \"\"\"\n By default, if the query parameter is not provided, `APIKeyQuery` will\n automatically cancel the request and send the client an error.\n\n If `auto_error` is set to `False`, when the query parameter is not\n available, instead of erroring out, the dependency result will be\n `None`.\n\n This is useful when you want to have optional authentication.\n\n It is also useful when you want to have authentication that can be\n provided in one of multiple optional ways (for example, in a query\n parameter or in an HTTP Bearer token).\n \"\"\"\n ),\n ] = True,\n ):\n super().__init__(\n location=APIKeyIn.query,\n name=name,\n scheme_name=scheme_name,\n description=description,\n auto_error=auto_error,\n )\n\n async def __call__(self, request: Request) -> str | None:\n api_key = request.query_params.get(self.model.name)\n return self.check_api_key(api_key)", "source_type": "code", "path": "fastapi/security/api_key.py", "symbol": "APIKeyQuery", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/api_key.py#L55-L144", "start_line": 55, "end_line": 144}