{"id": "README.md::README.md::L1", "text": "# Doc: README.md | Page: README.md | Section: README.md\n

\n \"FastAPI\"\n

\n

\n FastAPI framework, high performance, easy to learn, fast to code, ready for production\n

\n

\n\n \"Test\"\n\n\n \"Coverage\"\n\n\n \"Package\n\n\n \"Supported\n\n

\n\n---\n\n**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com)\n\n**Source Code**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)\n\n---\n\nFastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.\n\nThe key features are:\n\n* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).\n* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *\n* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *\n* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.\n* **Easy**: Designed to be easy to use and learn. Less time reading docs.\n* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.\n* **Robust**: Get production-ready code. With automatic interactive documentation.\n* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (previously known as Swagger) and [JSON Schema](https://json-schema.org/).\n\n* estimation based on tests conducted by an internal development team, building production applications.", "source_type": "doc", "path": "README.md", "symbol": "README.md", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L1-L44", "start_line": 1, "end_line": 44} {"id": "README.md::Sponsors::L45", "text": "# Doc: README.md | Page: README.md | Section: Sponsors\n## Sponsors\n\n\n### Keystone Sponsor\n\n\n\n### Gold Sponsors\n\n\n\n\n\n\n\n\n\n\n### Silver Sponsors\n\n\n\n\n\n\n\n\n\n\n[Other sponsors](https://fastapi.tiangolo.com/fastapi-people/#sponsors)", "source_type": "doc", "path": "README.md", "symbol": "Sponsors", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L45-L75", "start_line": 45, "end_line": 75} {"id": "README.md::Opinions::L76", "text": "# Doc: README.md | Page: README.md | Section: Opinions\n## Opinions\n\n\n\n
\n\n\"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._\"\n\n
Kabir Khan - Microsoft (ref)
\n\n---\n\n\"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_\"\n\n
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
\n\n---\n\n\"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_\"\n\n
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
\n\n---\n\n\"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._\"\n\n
Deon Pillsbury - Cisco (ref)
\n\n---\n\n
", "source_type": "doc", "path": "README.md", "symbol": "Opinions", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L76-L107", "start_line": 76, "end_line": 107} {"id": "README.md::FastAPI Conf::L108", "text": "# Doc: README.md | Page: README.md | Section: FastAPI Conf\n## FastAPI Conf\n\n[**FastAPI Conf '26**](https://fastapiconf.com) is happening on **October 28, 2026** in **Amsterdam, NL**. All about FastAPI, right from the source. 🎤\n\n\"FastAPI", "source_type": "doc", "path": "README.md", "symbol": "FastAPI Conf", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L108-L113", "start_line": 108, "end_line": 113} {"id": "README.md::FastAPI mini documentary::L114", "text": "# Doc: README.md | Page: README.md | Section: FastAPI mini documentary\n## FastAPI mini documentary\n\nThere's a [FastAPI mini documentary](https://www.youtube.com/watch?v=mpR8ngthqiE) released at the end of 2025, you can watch it online:\n\n\"FastAPI", "source_type": "doc", "path": "README.md", "symbol": "FastAPI mini documentary", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L114-L119", "start_line": 114, "end_line": 119} {"id": "README.md::**Typer**, the FastAPI of CLIs::L120", "text": "# Doc: README.md | Page: README.md | Section: **Typer**, the FastAPI of CLIs\n## **Typer**, the FastAPI of CLIs\n\n\n\nIf you are building a CLI app to be used in the terminal instead of a web API, check out [**Typer**](https://typer.tiangolo.com/).\n\n**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀", "source_type": "doc", "path": "README.md", "symbol": "**Typer**, the FastAPI of CLIs", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L120-L127", "start_line": 120, "end_line": 127} {"id": "README.md::Requirements::L128", "text": "# Doc: README.md | Page: README.md | Section: Requirements\n## Requirements\n\nFastAPI stands on the shoulders of giants:\n\n* [Starlette](https://www.starlette.dev/) for the web parts.\n* [Pydantic](https://docs.pydantic.dev/) for the data parts.", "source_type": "doc", "path": "README.md", "symbol": "Requirements", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L128-L134", "start_line": 128, "end_line": 134} {"id": "README.md::Installation::L135", "text": "# Doc: README.md | Page: README.md | Section: Installation\n## Installation\n\nCreate and activate a [virtual environment](https://fastapi.tiangolo.com/virtual-environments/) and then install FastAPI:\n\n
\n\n```console\n$ pip install \"fastapi[standard]\"\n\n---> 100%\n```\n\n
\n\n**Note**: Make sure you put `\"fastapi[standard]\"` in quotes to ensure it works in all terminals.", "source_type": "doc", "path": "README.md", "symbol": "Installation", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L135-L150", "start_line": 135, "end_line": 150} {"id": "README.md::Example::L151", "text": "# Doc: README.md | Page: README.md | Section: Example\n## Example\n\n### Create it\n\nCreate a file `main.py` with:\n\n```Python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/items/{item_id}\")\ndef read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n```\n\n
\nOr use async def...\n\nIf your code uses `async` / `await`, use `async def`:\n\n```Python hl_lines=\"7 12\"\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n```\n\n**Note**:\n\nIf you don't know, check the _\"In a hurry?\"_ section about [`async` and `await` in the docs](https://fastapi.tiangolo.com/async/#in-a-hurry).\n\n
\n\n### Run it\n\nRun the server with:\n\n
\n\n```console\n$ fastapi dev\n\n ╭────────── FastAPI CLI - Development mode ───────────╮\n │ │\n │ Serving at: http://127.0.0.1:8000 │\n │ │\n │ API docs: http://127.0.0.1:8000/docs │\n │ │\n │ Running in development mode, for production use: │\n │ │\n │ fastapi run │\n │ │\n ╰─────────────────────────────────────────────────────╯\n\nINFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\nINFO: Started reloader process [2248755] using WatchFiles\nINFO: Started server process [2248757]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\n```\n\n
\n\n
\nAbout the command fastapi dev...\n\nThe command `fastapi dev` reads your `main.py` file automatically, detects the **FastAPI** app in it, and starts a server using [Uvicorn](https://www.uvicorn.dev).\n\nBy default, `fastapi dev` will start with auto-reload enabled for local development.\n\nYou can read more about it in the [FastAPI CLI docs](https://fastapi.tiangolo.com/fastapi-cli/).\n\n
\n\n### Check it\n\nOpen your browser at [http://127.0.0.1:8000/items/5?q=somequery](http://127.0.0.1:8000/items/5?q=somequery).\n\nYou will see the JSON response as:\n\n```JSON\n{\"item_id\": 5, \"q\": \"somequery\"}\n```\n\nYou already created an API that:\n\n* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.\n* Both _paths_ take `GET` operations (also known as HTTP _methods_).\n* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.\n* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.\n\n### Interactive API docs\n\nNow go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see the automatic interactive API documentation (provided by [Swagger UI](https://github.com/swagger-api/swagger-ui)):\n\n![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)\n\n### Alternative API docs\n\nAnd now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).\n\nYou will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):\n\n![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)", "source_type": "doc", "path": "README.md", "symbol": "Example", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L151-L274", "start_line": 151, "end_line": 274} {"id": "README.md::Example upgrade::L275", "text": "# Doc: README.md | Page: README.md | Section: Example upgrade\n## Example upgrade\n\nNow modify the file `main.py` to receive a body from a `PUT` request.\n\nDeclare the body using standard Python types, thanks to Pydantic.\n\n```Python hl_lines=\"2 7-10 23-25\"\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n price: float\n is_offer: bool | None = None\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/items/{item_id}\")\ndef read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n\n\n@app.put(\"/items/{item_id}\")\ndef update_item(item_id: int, item: Item):\n return {\"item_name\": item.name, \"item_id\": item_id}\n```\n\nThe `fastapi dev` server should reload automatically.\n\n### Interactive API docs upgrade\n\nNow go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\n* The interactive API documentation will be automatically updated, including the new body:\n\n![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)\n\n* Click on the button \"Try it out\", it allows you to fill the parameters and directly interact with the API:\n\n![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)\n\n* Then click on the \"Execute\" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:\n\n![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)\n\n### Alternative API docs upgrade\n\nAnd now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).\n\n* The alternative documentation will also reflect the new query parameter and body:\n\n![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)\n\n### Recap\n\nIn summary, you declare **once** the types of parameters, body, etc. as function parameters.\n\nYou do that with standard modern Python types.\n\nYou don't have to learn a new syntax, the methods or classes of a specific library, etc.\n\nJust standard **Python**.\n\nFor example, for an `int`:\n\n```Python\nitem_id: int\n```\n\nor for a more complex `Item` model:\n\n```Python\nitem: Item\n```\n\n...and with that single declaration you get:\n\n* Editor support, including:\n * Completion.\n * Type checks.\n* Validation of data:\n * Automatic and clear errors when the data is invalid.\n * Validation even for deeply nested JSON objects.\n* Conversion of input data: coming from the network to Python data and types. Reading from:\n * JSON.\n * Path parameters.\n * Query parameters.\n * Cookies.\n * Headers.\n * Forms.\n * Files.\n* Conversion of output data: converting from Python data and types to network data (as JSON):\n * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).\n * `datetime` objects.\n * `UUID` objects.\n * Database models.\n * ...and many more.\n* Automatic interactive API documentation, including 2 alternative user interfaces:\n * Swagger UI.\n * ReDoc.\n\n---\n\nComing back to the previous code example, **FastAPI** will:\n\n* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.\n* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.\n * If it is not, the client will see a useful, clear error.\n* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.\n * As the `q` parameter is declared with `= None`, it is optional.\n * Without the `None` it would be required (as is the body in the case with `PUT`).\n* For `PUT` requests to `/items/{item_id}`, read the body as JSON:\n * Check that it has a required attribute `name` that should be a `str`.\n * Check that it has a required attribute `price` that has to be a `float`.\n * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.\n * All this would also work for deeply nested JSON objects.\n* Convert from and to JSON automatically.\n* Document everything with OpenAPI, that can be used by:\n * Interactive documentation systems.\n * Automatic client code generation systems, for many languages.\n* Provide 2 interactive documentation web interfaces directly.\n\n---\n\nWe just scratched the surface, but you already get the idea of how it all works.\n\nTry changing the line with:\n\n```Python\n return {\"item_name\": item.name, \"item_id\": item_id}\n```\n\n...from:\n\n```Python\n ... \"item_name\": item.name ...\n```\n\n...to:\n\n```Python\n ... \"item_price\": item.price ...\n```\n\n...and see how your editor will auto-complete the attributes and know their types:\n\n![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)\n\nFor a more complete example including more features, see the Tutorial - User Guide.\n\n**Spoiler alert**: the tutorial - user guide includes:\n\n* Declaration of **parameters** from other different places such as: **headers**, **cookies**, **form fields** and **files**.\n* How to set **validation constraints** such as `maximum_length` or `regex`.\n* A very powerful and easy to use **Dependency Injection** system.\n* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.\n* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).\n* **GraphQL** integration with [Strawberry](https://strawberry.rocks) and other libraries.\n* Many extra features (thanks to Starlette) such as:\n * **WebSockets**\n * extremely easy tests based on HTTPX and `pytest`\n * **CORS**\n * **Cookie Sessions**\n * ...and more.\n\n### Deploy your app (optional)\n\nYou can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀\n\n
\n\n```console\n$ fastapi deploy\n\nDeploying to FastAPI Cloud...\n\n✅ Deployment successful!\n\n🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev\n```\n\n
\n\nThe CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.\n\nThat's it! Now you can access your app at that URL. ✨\n\n#### About FastAPI Cloud\n\n**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**.\n\nIt streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort.\n\nIt brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉\n\nFastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨\n\n#### Deploy to other cloud providers\n\nFastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.\n\nFollow your cloud provider's guides to deploy FastAPI apps with them. 🤓", "source_type": "doc", "path": "README.md", "symbol": "Example upgrade", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L275-L484", "start_line": 275, "end_line": 484} {"id": "README.md::Performance::L485", "text": "# Doc: README.md | Page: README.md | Section: Performance\n## Performance\n\nIndependent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as [one of the fastest Python frameworks available](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)\n\nTo understand more about it, see the section [Benchmarks](https://fastapi.tiangolo.com/benchmarks/).", "source_type": "doc", "path": "README.md", "symbol": "Performance", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L485-L490", "start_line": 485, "end_line": 490} {"id": "README.md::Dependencies::L491", "text": "# Doc: README.md | Page: README.md | Section: Dependencies\n## Dependencies\n\nFastAPI depends on Pydantic and Starlette.\n\n### `standard` Dependencies\n\nWhen you install FastAPI with `pip install \"fastapi[standard]\"` it comes with the `standard` group of optional dependencies:\n\nUsed by Pydantic:\n\n* [`email-validator`](https://github.com/JoshData/python-email-validator) - for email validation.\n\nUsed by Starlette:\n\n* [`httpx`](https://www.python-httpx.org) - Required if you want to use the `TestClient`.\n* [`jinja2`](https://jinja.palletsprojects.com) - Required if you want to use the default template configuration.\n* [`python-multipart`](https://github.com/Kludex/python-multipart) - Required if you want to support form \"parsing\", with `request.form()`.\n\nUsed by FastAPI:\n\n* [`uvicorn`](https://www.uvicorn.dev) - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.\n* `fastapi-cli[standard]` - to provide the `fastapi` command.\n * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [FastAPI Cloud](https://fastapicloud.com).\n\n### Without `standard` Dependencies\n\nIf you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install \"fastapi[standard]\"`.\n\n### Without `fastapi-cloud-cli`\n\nIf you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install \"fastapi[standard-no-fastapi-cloud-cli]\"`.\n\n### Additional Optional Dependencies\n\nThere are some additional dependencies you might want to install.\n\nAdditional optional Pydantic dependencies:\n\n* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.\n* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.\n\nAdditional optional FastAPI dependencies:\n\n* [`orjson`](https://github.com/ijl/orjson) - Required if you want to use `ORJSONResponse`.\n* [`ujson`](https://github.com/esnme/ultrajson) - Required if you want to use `UJSONResponse`.", "source_type": "doc", "path": "README.md", "symbol": "Dependencies", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L491-L536", "start_line": 491, "end_line": 536} {"id": "README.md::License::L537", "text": "# Doc: README.md | Page: README.md | Section: License\n## License\n\nThis project is licensed under the terms of the MIT license.", "source_type": "doc", "path": "README.md", "symbol": "License", "url": "https://github.com/fastapi/fastapi/blob/master/README.md#L537-L539", "start_line": 537, "end_line": 539} {"id": "docs/en/docs/_llm-test.md::LLM test file { #llm-test-file }::L1", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: LLM test file { #llm-test-file }\n# LLM test file { #llm-test-file }\n\nThis document tests if the LLM, which translates the documentation, understands the `general_prompt` in `scripts/translate.py` and the language specific prompt in `docs/{language code}/llm-prompt.md`. The language specific prompt is appended to `general_prompt`.\n\nTests added here will be seen by all designers of language specific prompts.\n\nUse as follows:\n\n* Have a language specific prompt - `docs/{language code}/llm-prompt.md`.\n* Do a fresh translation of this document into your desired target language (see e.g. the `translate-page` command of the `translate.py`). This will create the translation under `docs/{language code}/docs/_llm-test.md`.\n* Check if things are okay in the translation.\n* If necessary, improve your language specific prompt, the general prompt, or the English document.\n* Then manually fix the remaining issues in the translation, so that it is a good translation.\n* Retranslate, having the good translation in place. The ideal result would be that the LLM makes no changes anymore to the translation. That means that the general prompt and your language specific prompt are as good as they can be (It will sometimes make a few seemingly random changes, the reason is that [LLMs are not deterministic algorithms](https://doublespeak.chat/#/handbook#deterministic-output)).\n\nThe tests:", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "LLM test file { #llm-test-file }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L1-L17", "start_line": 1, "end_line": 17} {"id": "docs/en/docs/_llm-test.md::Code snippets { #code-snippets }::L18", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: Code snippets { #code-snippets }\n## Code snippets { #code-snippets }\n\n//// tab | Test\n\nThis is a code snippet: `foo`. And this is another code snippet: `bar`. And another one: `baz quux`.\n\n////\n\n//// tab | Info\n\nContent of code snippets should be left as is.\n\nSee section `### Content of code snippets` in the general prompt in `scripts/translate.py`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "Code snippets { #code-snippets }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L18-L33", "start_line": 18, "end_line": 33} {"id": "docs/en/docs/_llm-test.md::Quotes { #quotes }::L34", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: Quotes { #quotes }\n## Quotes { #quotes }\n\n//// tab | Test\n\nYesterday, my friend wrote: \"If you spell incorrectly correctly, you have spelled it incorrectly\". To which I answered: \"Correct, but 'incorrectly' is incorrectly not '\"incorrectly\"'\".\n\n/// note\n\nThe LLM will probably translate this wrong. Interesting is only if it keeps the fixed translation when retranslating.\n\n///\n\n////\n\n//// tab | Info\n\nThe prompt designer may choose if they want to convert neutral quotes to typographic quotes. It is okay to leave them as is.\n\nSee for example section `### Quotes` in `docs/de/llm-prompt.md`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "Quotes { #quotes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L34-L55", "start_line": 34, "end_line": 55} {"id": "docs/en/docs/_llm-test.md::Quotes in code snippets { #quotes-in-code-snippets }::L56", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: Quotes in code snippets { #quotes-in-code-snippets }\n## Quotes in code snippets { #quotes-in-code-snippets }\n\n//// tab | Test\n\n`pip install \"foo[bar]\"`\n\nExamples for string literals in code snippets: `\"this\"`, `'that'`.\n\nA difficult example for string literals in code snippets: `f\"I like {'oranges' if orange else \"apples\"}\"`\n\nHardcore: `Yesterday, my friend wrote: \"If you spell incorrectly correctly, you have spelled it incorrectly\". To which I answered: \"Correct, but 'incorrectly' is incorrectly not '\"incorrectly\"'\"`\n\n////\n\n//// tab | Info\n\n... However, quotes inside code snippets must stay as is.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "Quotes in code snippets { #quotes-in-code-snippets }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L56-L75", "start_line": 56, "end_line": 75} {"id": "docs/en/docs/_llm-test.md::code blocks { #code-blocks }::L76", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: code blocks { #code-blocks }\n## code blocks { #code-blocks }\n\n//// tab | Test\n\nA Bash code example...\n\n```bash\n# Print a greeting to the universe\necho \"Hello universe\"\n```\n\n...and a console code example...\n\n```console\n$ fastapi run main.py\n FastAPI Starting server\n Searching for package file structure\n```\n\n...and another console code example...\n\n```console\n// Create a directory \"Code\"\n$ mkdir code\n// Switch into that directory\n$ cd code\n```\n\n...and a Python code example...\n\n```Python\nwont_work() # This won't work 😱\nworks(foo=\"bar\") # This works 🎉\n```\n\n...and that's it.\n\n////\n\n//// tab | Info\n\nCode in code blocks should not be modified, with the exception of comments.\n\nSee section `### Content of code blocks` in the general prompt in `scripts/translate.py`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "code blocks { #code-blocks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L76-L122", "start_line": 76, "end_line": 122} {"id": "docs/en/docs/_llm-test.md::Tabs and colored boxes { #tabs-and-colored-boxes }::L123", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: Tabs and colored boxes { #tabs-and-colored-boxes }\n## Tabs and colored boxes { #tabs-and-colored-boxes }\n\n//// tab | Test\n\n/// note\nSome text\n///\n\n/// note | Technical details\nSome text\n///\n\n/// tip\nSome text\n///\n\n/// warning\nSome text\n///\n\n/// danger\nSome text\n///\n\n////\n\n//// tab | Info\n\nTabs and `Info`/`Note`/`Warning`/etc. blocks should have the translation of their title added after a vertical bar (`|`).\n\nSee sections `### Special blocks` and `### Tab blocks` in the general prompt in `scripts/translate.py`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "Tabs and colored boxes { #tabs-and-colored-boxes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L123-L156", "start_line": 123, "end_line": 156} {"id": "docs/en/docs/_llm-test.md::Web- and internal links { #web-and-internal-links }::L157", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: Web- and internal links { #web-and-internal-links }\n## Web- and internal links { #web-and-internal-links }\n\n//// tab | Test\n\nThe link text should get translated, the link address should remain unchanged:\n\n* [Link to heading above](#code-snippets)\n* [Internal link](index.md#installation)\n* [External link](https://sqlmodel.tiangolo.com/)\n* [Link to a style](https://fastapi.tiangolo.com/css/styles.css)\n* [Link to a script](https://fastapi.tiangolo.com/js/logic.js)\n* [Link to an image](https://fastapi.tiangolo.com/img/foo.jpg)\n\nThe link text should get translated, the link address should point to the translation:\n\n* [FastAPI link](https://fastapi.tiangolo.com/)\n\n////\n\n//// tab | Info\n\nLinks should be translated, but their address shall remain unchanged. An exception are absolute links to pages of the FastAPI documentation. In that case it should link to the translation.\n\nSee section `### Links` in the general prompt in `scripts/translate.py`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "Web- and internal links { #web-and-internal-links }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L157-L183", "start_line": 157, "end_line": 183} {"id": "docs/en/docs/_llm-test.md::HTML \"abbr\" elements { #html-abbr-elements }::L184", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: HTML \"abbr\" elements { #html-abbr-elements }\n## HTML \"abbr\" elements { #html-abbr-elements }\n\n//// tab | Test\n\nHere are some things wrapped in HTML \"abbr\" elements (Some are invented):\n\n### The abbr gives a full phrase { #the-abbr-gives-a-full-phrase }\n\n* GTD\n* lt\n* XWT\n* PSGI\n\n### The abbr gives a full phrase and an explanation { #the-abbr-gives-a-full-phrase-and-an-explanation }\n\n* MDN\n* I/O.\n\n////\n\n//// tab | Info\n\n\"title\" attributes of \"abbr\" elements are translated following some specific instructions.\n\nTranslations can add their own \"abbr\" elements which the LLM should not remove. E.g. to explain English words.\n\nSee section `### HTML abbr elements` in the general prompt in `scripts/translate.py`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "HTML \"abbr\" elements { #html-abbr-elements }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L184-L213", "start_line": 184, "end_line": 213} {"id": "docs/en/docs/_llm-test.md::HTML \"dfn\" elements { #html-dfn-elements }::L214", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: HTML \"dfn\" elements { #html-dfn-elements }\n## HTML \"dfn\" elements { #html-dfn-elements }\n\n* cluster\n* ", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "HTML \"dfn\" elements { #html-dfn-elements }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L214-L218", "start_line": 214, "end_line": 218} {"id": "docs/en/docs/_llm-test.md::Headings { #headings }::L219", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: Headings { #headings }\n## Headings { #headings }\n\n//// tab | Test\n\n### Develop a webapp - a tutorial { #develop-a-webapp-a-tutorial }\n\nHello.\n\n### Type hints and -annotations { #type-hints-and-annotations }\n\nHello again.\n\n### Super- and subclasses { #super-and-subclasses }\n\nHello again.\n\n////\n\n//// tab | Info\n\nThe only hard rule for headings is that the LLM leaves the hash part inside curly brackets unchanged, which ensures that links do not break.\n\nSee section `### Headings` in the general prompt in `scripts/translate.py`.\n\nFor some language specific instructions, see e.g. section `### Headings` in `docs/de/llm-prompt.md`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "Headings { #headings }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L219-L246", "start_line": 219, "end_line": 246} {"id": "docs/en/docs/_llm-test.md::Terms used in the docs { #terms-used-in-the-docs }::L247", "text": "# Doc: docs/en/docs/_llm-test.md | Page: LLM test file { #llm-test-file } | Section: Terms used in the docs { #terms-used-in-the-docs }\n## Terms used in the docs { #terms-used-in-the-docs }\n\n//// tab | Test\n\n* you\n* your\n\n* e.g.\n* etc.\n\n* `foo` as an `int`\n* `bar` as a `str`\n* `baz` as a `list`\n\n* the Tutorial - User guide\n* the Advanced User Guide\n* the SQLModel docs\n* the API docs\n* the automatic docs\n\n* Data Science\n* Deep Learning\n* Machine Learning\n* Dependency Injection\n* HTTP Basic authentication\n* HTTP Digest\n* ISO format\n* the JSON Schema standard\n* the JSON schema\n* the schema definition\n* Password Flow\n* Mobile\n\n* deprecated\n* designed\n* invalid\n* on the fly\n* standard\n* default\n* case-sensitive\n* case-insensitive\n\n* to serve the application\n* to serve the page\n\n* the app\n* the application\n\n* the request\n* the response\n* the error response\n\n* the path operation\n* the path operation decorator\n* the path operation function\n\n* the body\n* the request body\n* the response body\n* the JSON body\n* the form body\n* the file body\n* the function body\n\n* the parameter\n* the body parameter\n* the path parameter\n* the query parameter\n* the cookie parameter\n* the header parameter\n* the form parameter\n* the function parameter\n\n* the event\n* the startup event\n* the startup of the server\n* the shutdown event\n* the lifespan event\n\n* the handler\n* the event handler\n* the exception handler\n* to handle\n\n* the model\n* the Pydantic model\n* the data model\n* the database model\n* the form model\n* the model object\n\n* the class\n* the base class\n* the parent class\n* the subclass\n* the child class\n* the sibling class\n* the class method\n\n* the header\n* the headers\n* the authorization header\n* the `Authorization` header\n* the forwarded header\n\n* the dependency injection system\n* the dependency\n* the dependable\n* the dependant\n\n* I/O bound\n* CPU bound\n* concurrency\n* parallelism\n* multiprocessing\n\n* the env var\n* the environment variable\n* the `PATH`\n* the `PATH` variable\n\n* the authentication\n* the authentication provider\n* the authorization\n* the authorization form\n* the authorization provider\n* the user authenticates\n* the system authenticates the user\n\n* the CLI\n* the command line interface\n\n* the server\n* the client\n\n* the cloud provider\n* the cloud service\n\n* the development\n* the development stages\n\n* the dict\n* the dictionary\n* the enumeration\n* the enum\n* the enum member\n\n* the encoder\n* the decoder\n* to encode\n* to decode\n\n* the exception\n* to raise\n\n* the expression\n* the statement\n\n* the frontend\n* the backend\n\n* the GitHub discussion\n* the GitHub issue\n\n* the performance\n* the performance optimization\n\n* the return type\n* the return value\n\n* the security\n* the security scheme\n\n* the task\n* the background task\n* the task function\n\n* the template\n* the template engine\n\n* the type annotation\n* the type hint\n\n* the server worker\n* the Uvicorn worker\n* the Gunicorn Worker\n* the worker process\n* the worker class\n* the workload\n\n* the deployment\n* to deploy\n\n* the SDK\n* the software development kit\n\n* the `APIRouter`\n* the `requirements.txt`\n* the Bearer Token\n* the breaking change\n* the bug\n* the button\n* the callable\n* the code\n* the commit\n* the context manager\n* the coroutine\n* the database session\n* the disk\n* the domain\n* the engine\n* the fake X\n* the HTTP GET method\n* the item\n* the library\n* the lifespan\n* the lock\n* the middleware\n* the mobile application\n* the module\n* the mounting\n* the network\n* the origin\n* the override\n* the payload\n* the processor\n* the property\n* the proxy\n* the pull request\n* the query\n* the RAM\n* the remote machine\n* the status code\n* the string\n* the tag\n* the web framework\n* the wildcard\n* to return\n* to validate\n\n////\n\n//// tab | Info\n\nThis is neither a complete nor a normative list of (mostly) technical terms seen in the docs. It may be helpful for the prompt designer to figure out for which terms the LLM needs a helping hand. For example when it keeps reverting a good translation to a suboptimal translation. Or when it has problems conjugating/declinating a term in your language.\n\nSee e.g. section `### List of English terms and their preferred German translations` in `docs/de/llm-prompt.md`.\n\n////", "source_type": "doc", "path": "docs/en/docs/_llm-test.md", "symbol": "Terms used in the docs { #terms-used-in-the-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/_llm-test.md#L247-L495", "start_line": 247, "end_line": 495} {"id": "docs/en/docs/about/index.md::About { #about }::L1", "text": "# Doc: docs/en/docs/about/index.md | Page: About { #about } | Section: About { #about }\n# About { #about }\n\nAbout FastAPI, its design, inspiration and more. 🤓", "source_type": "doc", "path": "docs/en/docs/about/index.md", "symbol": "About { #about }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/about/index.md#L1-L3", "start_line": 1, "end_line": 3} {"id": "docs/en/docs/advanced/additional-responses.md::Additional Responses in OpenAPI { #additional-responses-in-openapi }::L1", "text": "# Doc: docs/en/docs/advanced/additional-responses.md | Page: Additional Responses in OpenAPI { #additional-responses-in-openapi } | Section: Additional Responses in OpenAPI { #additional-responses-in-openapi }\n# Additional Responses in OpenAPI { #additional-responses-in-openapi }\n\n/// warning\n\nThis is a rather advanced topic.\n\nIf you are starting with **FastAPI**, you might not need this.\n\n///\n\nYou can declare additional responses, with additional status codes, media types, descriptions, etc.\n\nThose additional responses will be included in the OpenAPI schema, so they will also appear in the API docs.\n\nBut for those additional responses you have to make sure you return a `Response` like `JSONResponse` directly, with your status code and content.", "source_type": "doc", "path": "docs/en/docs/advanced/additional-responses.md", "symbol": "Additional Responses in OpenAPI { #additional-responses-in-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-responses.md#L1-L16", "start_line": 1, "end_line": 16} {"id": "docs/en/docs/advanced/additional-responses.md::Additional Response with `model` { #additional-response-with-model }::L17", "text": "# Doc: docs/en/docs/advanced/additional-responses.md | Page: Additional Responses in OpenAPI { #additional-responses-in-openapi } | Section: Additional Response with `model` { #additional-response-with-model }\n## Additional Response with `model` { #additional-response-with-model }\n\nYou can pass to your *path operation decorators* a parameter `responses`.\n\nIt receives a `dict`: the keys are status codes for each response (like `200`), and the values are other `dict`s with the information for each of them.\n\nEach of those response `dict`s can have a key `model`, containing a Pydantic model, just like `response_model`.\n\n**FastAPI** will take that model, generate its JSON Schema and include it in the correct place in OpenAPI.\n\nFor example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write:\n\n{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}\n\n/// note\n\nKeep in mind that you have to return the `JSONResponse` directly.\n\n///\n\n/// note\n\nThe `model` key is not part of OpenAPI.\n\n**FastAPI** will take the Pydantic model from there, generate the JSON Schema, and put it in the correct place.\n\nThe correct place is:\n\n* In the key `content`, that has as value another JSON object (`dict`) that contains:\n * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains:\n * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place.\n * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc.\n\n///\n\nThe generated responses in the OpenAPI for this *path operation* will be:\n\n```JSON hl_lines=\"3-12\"\n{\n \"responses\": {\n \"404\": {\n \"description\": \"Additional Response\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/Message\"\n }\n }\n }\n },\n \"200\": {\n \"description\": \"Successful Response\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/Item\"\n }\n }\n }\n },\n \"422\": {\n \"description\": \"Validation Error\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/HTTPValidationError\"\n }\n }\n }\n }\n }\n}\n```\n\nThe schemas are referenced to another place inside the OpenAPI schema:\n\n```JSON hl_lines=\"4-16\"\n{\n \"components\": {\n \"schemas\": {\n \"Message\": {\n \"title\": \"Message\",\n \"required\": [\n \"message\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"message\": {\n \"title\": \"Message\",\n \"type\": \"string\"\n }\n }\n },\n \"Item\": {\n \"title\": \"Item\",\n \"required\": [\n \"id\",\n \"value\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"title\": \"Id\",\n \"type\": \"string\"\n },\n \"value\": {\n \"title\": \"Value\",\n \"type\": \"string\"\n }\n }\n },\n \"ValidationError\": {\n \"title\": \"ValidationError\",\n \"required\": [\n \"loc\",\n \"msg\",\n \"type\"\n ],\n \"type\": \"object\",\n \"properties\": {\n \"loc\": {\n \"title\": \"Location\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"msg\": {\n \"title\": \"Message\",\n \"type\": \"string\"\n },\n \"type\": {\n \"title\": \"Error Type\",\n \"type\": \"string\"\n }\n }\n },\n \"HTTPValidationError\": {\n \"title\": \"HTTPValidationError\",\n \"type\": \"object\",\n \"properties\": {\n \"detail\": {\n \"title\": \"Detail\",\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/components/schemas/ValidationError\"\n }\n }\n }\n }\n }\n }\n}\n```", "source_type": "doc", "path": "docs/en/docs/advanced/additional-responses.md", "symbol": "Additional Response with `model` { #additional-response-with-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-responses.md#L17-L171", "start_line": 17, "end_line": 171} {"id": "docs/en/docs/advanced/additional-responses.md::Additional media types for the main response { #additional-media-types-for-the-main-response }::L172", "text": "# Doc: docs/en/docs/advanced/additional-responses.md | Page: Additional Responses in OpenAPI { #additional-responses-in-openapi } | Section: Additional media types for the main response { #additional-media-types-for-the-main-response }\n## Additional media types for the main response { #additional-media-types-for-the-main-response }\n\nYou can use this same `responses` parameter to add different media types for the same main response.\n\nFor example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image:\n\n{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}\n\n/// note\n\nNotice that you have to return the image using a `FileResponse` directly.\n\n///\n\n/// note\n\nUnless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).\n\nBut if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/additional-responses.md", "symbol": "Additional media types for the main response { #additional-media-types-for-the-main-response }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-responses.md#L172-L193", "start_line": 172, "end_line": 193} {"id": "docs/en/docs/advanced/additional-responses.md::Combining information { #combining-information }::L194", "text": "# Doc: docs/en/docs/advanced/additional-responses.md | Page: Additional Responses in OpenAPI { #additional-responses-in-openapi } | Section: Combining information { #combining-information }\n## Combining information { #combining-information }\n\nYou can also combine response information from multiple places, including the `response_model`, `status_code`, and `responses` parameters.\n\nYou can declare a `response_model`, using the default status code `200` (or a custom one if you need), and then declare additional information for that same response in `responses`, directly in the OpenAPI schema.\n\n**FastAPI** will keep the additional information from `responses`, and combine it with the JSON Schema from your model.\n\nFor example, you can declare a response with a status code `404` that uses a Pydantic model and has a custom `description`.\n\nAnd a response with a status code `200` that uses your `response_model`, but includes a custom `example`:\n\n{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}\n\nIt will all be combined and included in your OpenAPI, and shown in the API docs:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/additional-responses.md", "symbol": "Combining information { #combining-information }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-responses.md#L194-L211", "start_line": 194, "end_line": 211} {"id": "docs/en/docs/advanced/additional-responses.md::Combine predefined responses and custom ones { #combine-predefined-responses-and-custom-ones }::L212", "text": "# Doc: docs/en/docs/advanced/additional-responses.md | Page: Additional Responses in OpenAPI { #additional-responses-in-openapi } | Section: Combine predefined responses and custom ones { #combine-predefined-responses-and-custom-ones }\n## Combine predefined responses and custom ones { #combine-predefined-responses-and-custom-ones }\n\nYou might want to have some predefined responses that apply to many *path operations*, but you want to combine them with custom responses needed by each *path operation*.\n\nFor those cases, you can use the Python technique of \"unpacking\" a `dict` with `**dict_to_unpack`:\n\n```Python\nold_dict = {\n \"old key\": \"old value\",\n \"second old key\": \"second old value\",\n}\nnew_dict = {**old_dict, \"new key\": \"new value\"}\n```\n\nHere, `new_dict` will contain all the key-value pairs from `old_dict` plus the new key-value pair:\n\n```Python\n{\n \"old key\": \"old value\",\n \"second old key\": \"second old value\",\n \"new key\": \"new value\",\n}\n```\n\nYou can use that technique to reuse some predefined responses in your *path operations* and combine them with additional custom ones.\n\nFor example:\n\n{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}", "source_type": "doc", "path": "docs/en/docs/advanced/additional-responses.md", "symbol": "Combine predefined responses and custom ones { #combine-predefined-responses-and-custom-ones }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-responses.md#L212-L241", "start_line": 212, "end_line": 241} {"id": "docs/en/docs/advanced/additional-responses.md::More information about OpenAPI responses { #more-information-about-openapi-responses }::L242", "text": "# Doc: docs/en/docs/advanced/additional-responses.md | Page: Additional Responses in OpenAPI { #additional-responses-in-openapi } | Section: More information about OpenAPI responses { #more-information-about-openapi-responses }\n## More information about OpenAPI responses { #more-information-about-openapi-responses }\n\nTo see what exactly you can include in the responses, you can check these sections in the OpenAPI specification:\n\n* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), it includes the `Response Object`.\n* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`.", "source_type": "doc", "path": "docs/en/docs/advanced/additional-responses.md", "symbol": "More information about OpenAPI responses { #more-information-about-openapi-responses }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-responses.md#L242-L247", "start_line": 242, "end_line": 247} {"id": "docs/en/docs/advanced/additional-status-codes.md::Additional Status Codes { #additional-status-codes }::L1", "text": "# Doc: docs/en/docs/advanced/additional-status-codes.md | Page: Additional Status Codes { #additional-status-codes } | Section: Additional Status Codes { #additional-status-codes }\n# Additional Status Codes { #additional-status-codes }\n\nBy default, **FastAPI** will return the responses using a `JSONResponse`, putting the content you return from your *path operation* inside of that `JSONResponse`.\n\nIt will use the default status code or the one you set in your *path operation*.", "source_type": "doc", "path": "docs/en/docs/advanced/additional-status-codes.md", "symbol": "Additional Status Codes { #additional-status-codes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-status-codes.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/advanced/additional-status-codes.md::Additional status codes { #additional-status-codes_1 }::L7", "text": "# Doc: docs/en/docs/advanced/additional-status-codes.md | Page: Additional Status Codes { #additional-status-codes } | Section: Additional status codes { #additional-status-codes_1 }\n## Additional status codes { #additional-status-codes_1 }\n\nIf you want to return additional status codes apart from the main one, you can do that by returning a `Response` directly, like a `JSONResponse`, and set the additional status code directly.\n\nFor example, let's say that you want to have a *path operation* that allows updating items, and returns HTTP status codes of 200 \"OK\" when successful.\n\nBut you also want it to accept new items. And when the items didn't exist before, it creates them, and returns an HTTP status code of 201 \"Created\".\n\nTo achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:\n\n{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}\n\n/// warning\n\nWhen you return a `Response` directly, like in the example above, it will be returned directly.\n\nIt won't be serialized with a model, etc.\n\nMake sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).\n\n///\n\n/// note | Technical Details\n\nYou could also use `from starlette.responses import JSONResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/additional-status-codes.md", "symbol": "Additional status codes { #additional-status-codes_1 }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-status-codes.md#L7-L36", "start_line": 7, "end_line": 36} {"id": "docs/en/docs/advanced/additional-status-codes.md::OpenAPI and API docs { #openapi-and-api-docs }::L37", "text": "# Doc: docs/en/docs/advanced/additional-status-codes.md | Page: Additional Status Codes { #additional-status-codes } | Section: OpenAPI and API docs { #openapi-and-api-docs }\n## OpenAPI and API docs { #openapi-and-api-docs }\n\nIf you return additional status codes and responses directly, they won't be included in the OpenAPI schema (the API docs), because FastAPI doesn't have a way to know beforehand what you are going to return.\n\nBut you can document that in your code, using: [Additional Responses](additional-responses.md).", "source_type": "doc", "path": "docs/en/docs/advanced/additional-status-codes.md", "symbol": "OpenAPI and API docs { #openapi-and-api-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/additional-status-codes.md#L37-L41", "start_line": 37, "end_line": 41} {"id": "docs/en/docs/advanced/advanced-dependencies.md::Advanced Dependencies { #advanced-dependencies }::L1", "text": "# Doc: docs/en/docs/advanced/advanced-dependencies.md | Page: Advanced Dependencies { #advanced-dependencies } | Section: Advanced Dependencies { #advanced-dependencies }\n# Advanced Dependencies { #advanced-dependencies }", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-dependencies.md", "symbol": "Advanced Dependencies { #advanced-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-dependencies.md#L1-L2", "start_line": 1, "end_line": 2} {"id": "docs/en/docs/advanced/advanced-dependencies.md::Parameterized dependencies { #parameterized-dependencies }::L3", "text": "# Doc: docs/en/docs/advanced/advanced-dependencies.md | Page: Advanced Dependencies { #advanced-dependencies } | Section: Parameterized dependencies { #parameterized-dependencies }\n## Parameterized dependencies { #parameterized-dependencies }\n\nAll the dependencies we have seen are a fixed function or class.\n\nBut there could be cases where you want to be able to set parameters on the dependency, without having to declare many different functions or classes.\n\nLet's imagine that we want to have a dependency that checks if the query parameter `q` contains some fixed content.\n\nBut we want to be able to parameterize that fixed content.", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-dependencies.md", "symbol": "Parameterized dependencies { #parameterized-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-dependencies.md#L3-L12", "start_line": 3, "end_line": 12} {"id": "docs/en/docs/advanced/advanced-dependencies.md::A \"callable\" instance { #a-callable-instance }::L13", "text": "# Doc: docs/en/docs/advanced/advanced-dependencies.md | Page: Advanced Dependencies { #advanced-dependencies } | Section: A \"callable\" instance { #a-callable-instance }\n## A \"callable\" instance { #a-callable-instance }\n\nIn Python there's a way to make an instance of a class a \"callable\".\n\nNot the class itself (which is already a callable), but an instance of that class.\n\nTo do that, we declare a method `__call__`:\n\n{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}\n\nIn this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-dependencies.md", "symbol": "A \"callable\" instance { #a-callable-instance }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-dependencies.md#L13-L24", "start_line": 13, "end_line": 24} {"id": "docs/en/docs/advanced/advanced-dependencies.md::Parameterize the instance { #parameterize-the-instance }::L25", "text": "# Doc: docs/en/docs/advanced/advanced-dependencies.md | Page: Advanced Dependencies { #advanced-dependencies } | Section: Parameterize the instance { #parameterize-the-instance }\n## Parameterize the instance { #parameterize-the-instance }\n\nAnd now, we can use `__init__` to declare the parameters of the instance that we can use to \"parameterize\" the dependency:\n\n{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}\n\nIn this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-dependencies.md", "symbol": "Parameterize the instance { #parameterize-the-instance }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-dependencies.md#L25-L32", "start_line": 25, "end_line": 32} {"id": "docs/en/docs/advanced/advanced-dependencies.md::Create an instance { #create-an-instance }::L33", "text": "# Doc: docs/en/docs/advanced/advanced-dependencies.md | Page: Advanced Dependencies { #advanced-dependencies } | Section: Create an instance { #create-an-instance }\n## Create an instance { #create-an-instance }\n\nWe could create an instance of this class with:\n\n{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}\n\nAnd that way we are able to \"parameterize\" our dependency, that now has `\"bar\"` inside of it, as the attribute `checker.fixed_content`.", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-dependencies.md", "symbol": "Create an instance { #create-an-instance }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-dependencies.md#L33-L40", "start_line": 33, "end_line": 40} {"id": "docs/en/docs/advanced/advanced-dependencies.md::Use the instance as a dependency { #use-the-instance-as-a-dependency }::L41", "text": "# Doc: docs/en/docs/advanced/advanced-dependencies.md | Page: Advanced Dependencies { #advanced-dependencies } | Section: Use the instance as a dependency { #use-the-instance-as-a-dependency }\n## Use the instance as a dependency { #use-the-instance-as-a-dependency }\n\nThen, we could use this `checker` in a `Depends(checker)`, instead of `Depends(FixedContentQueryChecker)`, because the dependency is the instance, `checker`, not the class itself.\n\nAnd when solving the dependency, **FastAPI** will call this `checker` like:\n\n```Python\nchecker(q=\"somequery\")\n```\n\n...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`:\n\n{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}\n\n/// tip\n\nAll this might seem contrived. And it might not be very clear how it is useful yet.\n\nThese examples are intentionally simple, but show how it all works.\n\nIn the chapters about security, there are utility functions that are implemented in this same way.\n\nIf you understood all this, you already know how those utility tools for security work underneath.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-dependencies.md", "symbol": "Use the instance as a dependency { #use-the-instance-as-a-dependency }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-dependencies.md#L41-L66", "start_line": 41, "end_line": 66} {"id": "docs/en/docs/advanced/advanced-dependencies.md::Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }::L67", "text": "# Doc: docs/en/docs/advanced/advanced-dependencies.md | Page: Advanced Dependencies { #advanced-dependencies } | Section: Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }\n## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }\n\n/// warning\n\nYou most probably don't need these technical details.\n\nThese details are useful mainly if you had a FastAPI application older than 0.121.0 and you are facing issues with dependencies with `yield`.\n\n///\n\nDependencies with `yield` have evolved over time to account for the different use cases and to fix some issues, here's a summary of what has changed.\n\n### Dependencies with `yield` and `scope` { #dependencies-with-yield-and-scope }\n\nIn version 0.121.0, FastAPI added support for `Depends(scope=\"function\")` for dependencies with `yield`.\n\nUsing `Depends(scope=\"function\")`, the exit code after `yield` is executed right after the *path operation function* is finished, before the response is sent back to the client.\n\nAnd when using `Depends(scope=\"request\")` (the default), the exit code after `yield` is executed after the response is sent.\n\nYou can read more about it in the docs for [Dependencies with `yield` - Early exit and `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).\n\n### Dependencies with `yield` and `StreamingResponse`, Technical Details { #dependencies-with-yield-and-streamingresponse-technical-details }\n\nBefore FastAPI 0.118.0, if you used a dependency with `yield`, it would run the exit code after the *path operation function* returned but right before sending the response.\n\nThe intention was to avoid holding resources for longer than necessary, waiting for the response to travel through the network.\n\nThis change also meant that if you returned a `StreamingResponse`, the exit code of the dependency with `yield` would have been already run.\n\nFor example, if you had a database session in a dependency with `yield`, the `StreamingResponse` would not be able to use that session while streaming data because the session would have already been closed in the exit code after `yield`.\n\nThis behavior was reverted in 0.118.0, to make the exit code after `yield` be executed after the response is sent.\n\n/// note\n\nAs you will see below, this is very similar to the behavior before version 0.106.0, but with several improvements and bug fixes for corner cases.\n\n///\n\n#### Use Cases with Early Exit Code { #use-cases-with-early-exit-code }\n\nThere are some use cases with specific conditions that could benefit from the old behavior of running the exit code of dependencies with `yield` before sending the response.\n\nFor example, imagine you have code that uses a database session in a dependency with `yield` only to verify a user, but the database session is never used again in the *path operation function*, only in the dependency, **and** the response takes a long time to be sent, like a `StreamingResponse` that sends data slowly, but for some reason doesn't use the database.\n\nIn this case, the database session would be held until the response is finished being sent, but if you don't use it, then it wouldn't be necessary to hold it.\n\nHere's how it could look:\n\n{* ../../docs_src/dependencies/tutorial013_an_py310.py *}\n\nThe exit code, the automatic closing of the `Session` in:\n\n{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}\n\n...would be run after the response finishes sending the slow data:\n\n{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}\n\nBut as `generate_stream()` doesn't use the database session, it is not really necessary to keep the session open while sending the response.\n\nIf you have this specific use case using SQLModel (or SQLAlchemy), you could explicitly close the session after you don't need it anymore:\n\n{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}\n\nThat way the session would release the database connection, so other requests could use it.\n\nIf you have a different use case that needs to exit early from a dependency with `yield`, please create a [GitHub Discussion Question](https://github.com/fastapi/fastapi/discussions/new?category=questions) with your specific use case and why you would benefit from having early closing for dependencies with `yield`.\n\nIf there are compelling use cases for early closing in dependencies with `yield`, I would consider adding a new way to opt in to early closing.\n\n### Dependencies with `yield` and `except`, Technical Details { #dependencies-with-yield-and-except-technical-details }\n\nBefore FastAPI 0.110.0, if you used a dependency with `yield`, and then you captured an exception with `except` in that dependency, and you didn't raise the exception again, the exception would be automatically raised/forwarded to any exception handlers or the internal server error handler.\n\nThis was changed in version 0.110.0 to fix unhandled memory consumption from forwarded exceptions without a handler (internal server errors), and to make it consistent with the behavior of regular Python code.\n\n### Background Tasks and Dependencies with `yield`, Technical Details { #background-tasks-and-dependencies-with-yield-technical-details }\n\nBefore FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../tutorial/handling-errors.md#install-custom-exception-handlers) would have already run.\n\nThis was designed this way mainly to allow using the same objects \"yielded\" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished.\n\nThis was changed in FastAPI 0.106.0 with the intention to not hold resources while waiting for the response to travel through the network.\n\n/// tip\n\nAdditionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection).\n\nSo, this way you will probably have cleaner code.\n\n///\n\nIf you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`.\n\nFor example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function.", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-dependencies.md", "symbol": "Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-dependencies.md#L67-L163", "start_line": 67, "end_line": 163} {"id": "docs/en/docs/advanced/advanced-python-types.md::Advanced Python Types { #advanced-python-types }::L1", "text": "# Doc: docs/en/docs/advanced/advanced-python-types.md | Page: Advanced Python Types { #advanced-python-types } | Section: Advanced Python Types { #advanced-python-types }\n# Advanced Python Types { #advanced-python-types }\n\nHere are some additional ideas that might be useful when working with Python types.", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-python-types.md", "symbol": "Advanced Python Types { #advanced-python-types }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-python-types.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/advanced/advanced-python-types.md::Using `Union` or `Optional` { #using-union-or-optional }::L5", "text": "# Doc: docs/en/docs/advanced/advanced-python-types.md | Page: Advanced Python Types { #advanced-python-types } | Section: Using `Union` or `Optional` { #using-union-or-optional }\n## Using `Union` or `Optional` { #using-union-or-optional }\n\nIf your code for some reason can't use `|`, for example if it's not in a type annotation but in something like `response_model=`, instead of using the vertical bar (`|`) you can use `Union` from `typing`.\n\nFor example, you could declare that something could be a `str` or `None`:\n\n```python\nfrom typing import Union\n\n\ndef say_hi(name: Union[str, None]):\n print(f\"Hi {name}!\")\n```\n\n`typing` also has a shortcut to declare that something could be `None`, with `Optional`.\n\nHere's a tip from my very **subjective** point of view:\n\n* 🚨 Avoid using `Optional[SomeType]`\n* Instead ✨ **use `Union[SomeType, None]`** ✨.\n\nBoth are equivalent and underneath they are the same, but I would recommend `Union` instead of `Optional` because the word \"**optional**\" would seem to imply that the value is optional, and it actually means \"it can be `None`\", even if it's not optional and is still required.\n\nI think `Union[SomeType, None]` is more explicit about what it means.\n\nIt's just about the words and names. But those words can affect how you and your teammates think about the code.\n\nAs an example, let's take this function:\n\n```python\nfrom typing import Optional\n\n\ndef say_hi(name: Optional[str]):\n print(f\"Hey {name}!\")\n```\n\nThe parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:\n\n```Python\nsay_hi() # Oh, no, this throws an error! 😱\n```\n\nThe `name` parameter is **still required** (not *optional*) because it doesn't have a default value. Still, `name` accepts `None` as the value:\n\n```Python\nsay_hi(name=None) # This works, None is valid 🎉\n```\n\nThe good news is, in most cases, you will be able to simply use `|` to define unions of types:\n\n```python\ndef say_hi(name: str | None):\n print(f\"Hey {name}!\")\n```\n\nSo, normally you don't have to worry about names like `Optional` and `Union`. 😎", "source_type": "doc", "path": "docs/en/docs/advanced/advanced-python-types.md", "symbol": "Using `Union` or `Optional` { #using-union-or-optional }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/advanced-python-types.md#L5-L61", "start_line": 5, "end_line": 61} {"id": "docs/en/docs/advanced/async-tests.md::Async Tests { #async-tests }::L1", "text": "# Doc: docs/en/docs/advanced/async-tests.md | Page: Async Tests { #async-tests } | Section: Async Tests { #async-tests }\n# Async Tests { #async-tests }\n\nYou have already seen how to test your **FastAPI** applications using the provided `TestClient`. Up to now, you have only seen how to write synchronous tests, without using `async` functions.\n\nBeing able to use asynchronous functions in your tests could be useful, for example, when you're querying your database asynchronously. Imagine you want to test sending requests to your FastAPI application and then verify that your backend successfully wrote the correct data in the database, while using an async database library.\n\nLet's look at how we can make that work.", "source_type": "doc", "path": "docs/en/docs/advanced/async-tests.md", "symbol": "Async Tests { #async-tests }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/async-tests.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/advanced/async-tests.md::pytest.mark.anyio { #pytest-mark-anyio }::L9", "text": "# Doc: docs/en/docs/advanced/async-tests.md | Page: Async Tests { #async-tests } | Section: pytest.mark.anyio { #pytest-mark-anyio }\n## pytest.mark.anyio { #pytest-mark-anyio }\n\nIf we want to call asynchronous functions in our tests, our test functions have to be asynchronous. AnyIO provides a neat plugin for this, that allows us to specify that some test functions are to be called asynchronously.", "source_type": "doc", "path": "docs/en/docs/advanced/async-tests.md", "symbol": "pytest.mark.anyio { #pytest-mark-anyio }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/async-tests.md#L9-L12", "start_line": 9, "end_line": 12} {"id": "docs/en/docs/advanced/async-tests.md::HTTPX { #httpx }::L13", "text": "# Doc: docs/en/docs/advanced/async-tests.md | Page: Async Tests { #async-tests } | Section: HTTPX { #httpx }\n## HTTPX { #httpx }\n\nEven if your **FastAPI** application uses normal `def` functions instead of `async def`, it is still an `async` application underneath.\n\nThe `TestClient` does some magic inside to call the asynchronous FastAPI application in your normal `def` test functions, using standard pytest. But that magic doesn't work anymore when we're using it inside asynchronous functions. By running our tests asynchronously, we can no longer use the `TestClient` inside our test functions.\n\nThe `TestClient` is based on [HTTPX](https://www.python-httpx.org), and luckily, we can use it directly to test the API.", "source_type": "doc", "path": "docs/en/docs/advanced/async-tests.md", "symbol": "HTTPX { #httpx }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/async-tests.md#L13-L20", "start_line": 13, "end_line": 20} {"id": "docs/en/docs/advanced/async-tests.md::Example { #example }::L21", "text": "# Doc: docs/en/docs/advanced/async-tests.md | Page: Async Tests { #async-tests } | Section: Example { #example }\n## Example { #example }\n\nFor a simple example, let's consider a file structure similar to the one described in [Bigger Applications](../tutorial/bigger-applications.md) and [Testing](../tutorial/testing.md):\n\n```\n.\n├── app\n│   ├── __init__.py\n│   ├── main.py\n│   └── test_main.py\n```\n\nThe file `main.py` would have:\n\n{* ../../docs_src/async_tests/app_a_py310/main.py *}\n\nThe file `test_main.py` would have the tests for `main.py`, it could look like this now:\n\n{* ../../docs_src/async_tests/app_a_py310/test_main.py *}", "source_type": "doc", "path": "docs/en/docs/advanced/async-tests.md", "symbol": "Example { #example }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/async-tests.md#L21-L40", "start_line": 21, "end_line": 40} {"id": "docs/en/docs/advanced/async-tests.md::Run it { #run-it }::L41", "text": "# Doc: docs/en/docs/advanced/async-tests.md | Page: Async Tests { #async-tests } | Section: Run it { #run-it }\n## Run it { #run-it }\n\nYou can run your tests as usual via:\n\n
\n\n```console\n$ pytest\n\n---> 100%\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/advanced/async-tests.md", "symbol": "Run it { #run-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/async-tests.md#L41-L54", "start_line": 41, "end_line": 54} {"id": "docs/en/docs/advanced/async-tests.md::In Detail { #in-detail }::L55", "text": "# Doc: docs/en/docs/advanced/async-tests.md | Page: Async Tests { #async-tests } | Section: In Detail { #in-detail }\n## In Detail { #in-detail }\n\nThe marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously:\n\n{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[7] *}\n\n/// tip\n\nNote that the test function is now `async def` instead of just `def` as before when using the `TestClient`.\n\n///\n\nThen we can create an `AsyncClient` with the app, and send async requests to it, using `await`.\n\n{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[9:12] *}\n\nThis is the equivalent to:\n\n```Python\nresponse = client.get('/')\n```\n\n...that we used to make our requests with the `TestClient`.\n\n/// tip\n\nNote that we're using async/await with the new `AsyncClient` - the request is asynchronous.\n\n///\n\n/// warning\n\nIf your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from [florimondmanca/asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/async-tests.md", "symbol": "In Detail { #in-detail }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/async-tests.md#L55-L90", "start_line": 55, "end_line": 90} {"id": "docs/en/docs/advanced/async-tests.md::Other Asynchronous Function Calls { #other-asynchronous-function-calls }::L91", "text": "# Doc: docs/en/docs/advanced/async-tests.md | Page: Async Tests { #async-tests } | Section: Other Asynchronous Function Calls { #other-asynchronous-function-calls }\n## Other Asynchronous Function Calls { #other-asynchronous-function-calls }\n\nAs the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code.\n\n/// tip\n\nIf you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using [MongoDB's MotorClient](https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop)), remember to instantiate objects that need an event loop only within async functions, e.g. an `@app.on_event(\"startup\")` callback.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/async-tests.md", "symbol": "Other Asynchronous Function Calls { #other-asynchronous-function-calls }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/async-tests.md#L91-L99", "start_line": 91, "end_line": 99} {"id": "docs/en/docs/advanced/behind-a-proxy.md::Behind a Proxy { #behind-a-proxy }::L1", "text": "# Doc: docs/en/docs/advanced/behind-a-proxy.md | Page: Behind a Proxy { #behind-a-proxy } | Section: Behind a Proxy { #behind-a-proxy }\n# Behind a Proxy { #behind-a-proxy }\n\nIn many situations, you would use a **proxy** like Traefik or Nginx in front of your FastAPI app.\n\nThese proxies could handle HTTPS certificates and other things.", "source_type": "doc", "path": "docs/en/docs/advanced/behind-a-proxy.md", "symbol": "Behind a Proxy { #behind-a-proxy }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/behind-a-proxy.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/advanced/behind-a-proxy.md::Proxy Forwarded Headers { #proxy-forwarded-headers }::L7", "text": "# Doc: docs/en/docs/advanced/behind-a-proxy.md | Page: Behind a Proxy { #behind-a-proxy } | Section: Proxy Forwarded Headers { #proxy-forwarded-headers }\n## Proxy Forwarded Headers { #proxy-forwarded-headers }\n\nA **proxy** in front of your application would normally set some headers on the fly before sending the requests to your **server** to let the server know that the request was **forwarded** by the proxy, letting it know the original (public) URL, including the domain, that it is using HTTPS, etc.\n\nThe **server** program (for example **Uvicorn** via **FastAPI CLI**) is capable of interpreting these headers, and then passing that information to your application.\n\nBut for security, as the server doesn't know it is behind a trusted proxy, it won't interpret those headers.\n\n/// note | Technical Details\n\nThe proxy headers are:\n\n* [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For)\n* [X-Forwarded-Proto](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Proto)\n* [X-Forwarded-Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Host)\n\n///\n\n### Enable Proxy Forwarded Headers { #enable-proxy-forwarded-headers }\n\nYou can start FastAPI CLI with the *CLI Option* `--forwarded-allow-ips` and pass the IP addresses that should be trusted to read those forwarded headers.\n\nIf you set it to `--forwarded-allow-ips=\"*\"` it would trust all the incoming IPs.\n\nIf your **server** is behind a trusted **proxy** and only the proxy talks to it, this would make it accept whatever is the IP of that **proxy**.\n\n
\n\n```console\n$ fastapi run --forwarded-allow-ips=\"*\"\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\n### Redirects with HTTPS { #redirects-with-https }\n\nFor example, let's say you define a *path operation* `/items/`:\n\n{* ../../docs_src/behind_a_proxy/tutorial001_01_py310.py hl[6] *}\n\nIf the client tries to go to `/items`, by default, it would be redirected to `/items/`.\n\nBut before setting the *CLI Option* `--forwarded-allow-ips` it could redirect to `http://localhost:8000/items/`.\n\nBut maybe your application is hosted at `https://mysuperapp.com`, and the redirection should be to `https://mysuperapp.com/items/`.\n\nBy setting `--proxy-headers` now FastAPI would be able to redirect to the right location. 😎\n\n```\nhttps://mysuperapp.com/items/\n```\n\n/// tip\n\nIf you want to learn more about HTTPS, check the guide [About HTTPS](../deployment/https.md).\n\n///\n\n### How Proxy Forwarded Headers Work { #how-proxy-forwarded-headers-work }\n\nHere's a visual representation of how the **proxy** adds forwarded headers between the client and the **application server**:\n\n```mermaid\nsequenceDiagram\n participant Client\n participant Proxy as Proxy/Load Balancer\n participant Server as FastAPI Server\n\n Client->>Proxy: HTTPS Request
Host: mysuperapp.com
Path: /items\n\n Note over Proxy: Proxy adds forwarded headers\n\n Proxy->>Server: HTTP Request
X-Forwarded-For: [client IP]
X-Forwarded-Proto: https
X-Forwarded-Host: mysuperapp.com
Path: /items\n\n Note over Server: Server interprets headers
(if --forwarded-allow-ips is set)\n\n Server->>Proxy: HTTP Response
with correct HTTPS URLs\n\n Proxy->>Client: HTTPS Response\n```\n\nThe **proxy** intercepts the original client request and adds the special *forwarded* headers (`X-Forwarded-*`) before passing the request to the **application server**.\n\nThese headers preserve information about the original request that would otherwise be lost:\n\n* **X-Forwarded-For**: The original client's IP address\n* **X-Forwarded-Proto**: The original protocol (`https`)\n* **X-Forwarded-Host**: The original host (`mysuperapp.com`)\n\nWhen **FastAPI CLI** is configured with `--forwarded-allow-ips`, it trusts these headers and uses them, for example to generate the correct URLs in redirects.", "source_type": "doc", "path": "docs/en/docs/advanced/behind-a-proxy.md", "symbol": "Proxy Forwarded Headers { #proxy-forwarded-headers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/behind-a-proxy.md#L7-L99", "start_line": 7, "end_line": 99} {"id": "docs/en/docs/advanced/behind-a-proxy.md::Proxy with a stripped path prefix { #proxy-with-a-stripped-path-prefix }::L100", "text": "# Doc: docs/en/docs/advanced/behind-a-proxy.md | Page: Behind a Proxy { #behind-a-proxy } | Section: Proxy with a stripped path prefix { #proxy-with-a-stripped-path-prefix }\n## Proxy with a stripped path prefix { #proxy-with-a-stripped-path-prefix }\n\nYou could have a proxy that adds a path prefix to your application.\n\nIn these cases you can use `root_path` to configure your application.\n\nThe `root_path` is a mechanism provided by the ASGI specification (that FastAPI is built on, through Starlette).\n\nThe `root_path` is used to handle these specific cases.\n\nAnd it's also used internally when mounting sub-applications.\n\nHaving a proxy with a stripped path prefix, in this case, means that you could declare a path at `/app` in your code, but then, you add a layer on top (the proxy) that would put your **FastAPI** application under a path like `/api/v1`.\n\nIn this case, the original path `/app` would actually be served at `/api/v1/app`.\n\nEven though all your code is written assuming there's just `/app`.\n\n{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[6] *}\n\nAnd the proxy would be **\"stripping\"** the **path prefix** on the fly before transmitting the request to the app server (probably Uvicorn via FastAPI CLI), keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`.\n\nUp to here, everything would work as normally.\n\nBut then, when you open the integrated docs UI (the frontend), it would expect to get the OpenAPI schema at `/openapi.json`, instead of `/api/v1/openapi.json`.\n\nSo, the frontend (that runs in the browser) would try to reach `/openapi.json` and wouldn't be able to get the OpenAPI schema.\n\nBecause we have a proxy with a path prefix of `/api/v1` for our app, the frontend needs to fetch the OpenAPI schema at `/api/v1/openapi.json`.\n\n```mermaid\ngraph LR\n\nbrowser(\"Browser\")\nproxy[\"Proxy on http://0.0.0.0:9999/api/v1/app\"]\nserver[\"Server on http://127.0.0.1:8000/app\"]\n\nbrowser --> proxy\nproxy --> server\n```\n\n/// tip\n\nThe IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server.\n\n///\n\nThe docs UI would also need the OpenAPI schema to declare that this API `server` is located at `/api/v1` (behind the proxy). For example:\n\n```JSON hl_lines=\"4-8\"\n{\n \"openapi\": \"3.1.0\",\n // More stuff here\n \"servers\": [\n {\n \"url\": \"/api/v1\"\n }\n ],\n \"paths\": {\n // More stuff here\n }\n}\n```\n\nIn this example, the \"Proxy\" could be something like **Traefik**. And the server would be something like FastAPI CLI with **Uvicorn**, running your FastAPI application.\n\n### Providing the `root_path` { #providing-the-root-path }\n\nTo achieve this, you can use the command line option `--root-path` like:\n\n
\n\n```console\n$ fastapi run main.py --forwarded-allow-ips=\"*\" --root-path /api/v1\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nIf you use Hypercorn, it also has the option `--root-path`.\n\n/// note | Technical Details\n\nThe ASGI specification defines a `root_path` for this use case.\n\nAnd the `--root-path` command line option provides that `root_path`.\n\n///\n\n### Checking the current `root_path` { #checking-the-current-root-path }\n\nYou can get the current `root_path` used by your application for each request, it is part of the `scope` dictionary (that's part of the ASGI spec).\n\nHere we are including it in the message just for demonstration purposes.\n\n{* ../../docs_src/behind_a_proxy/tutorial001_py310.py hl[8] *}\n\nThen, if you start Uvicorn with:\n\n
\n\n```console\n$ fastapi run main.py --forwarded-allow-ips=\"*\" --root-path /api/v1\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nThe response would be something like:\n\n```JSON\n{\n \"message\": \"Hello World\",\n \"root_path\": \"/api/v1\"\n}\n```\n\n### Setting the `root_path` in the FastAPI app { #setting-the-root-path-in-the-fastapi-app }\n\nAlternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app:\n\n{* ../../docs_src/behind_a_proxy/tutorial002_py310.py hl[3] *}\n\nPassing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn.\n\n### About `root_path` { #about-root-path }\n\nKeep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app.\n\nBut if you go with your browser to [http://127.0.0.1:8000/app](http://127.0.0.1:8000/app) you will see the normal response:\n\n```JSON\n{\n \"message\": \"Hello World\",\n \"root_path\": \"/api/v1\"\n}\n```\n\nSo, it won't expect to be accessed at `http://127.0.0.1:8000/api/v1/app`.\n\nUvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, and then it would be the proxy's responsibility to add the extra `/api/v1` prefix on top.", "source_type": "doc", "path": "docs/en/docs/advanced/behind-a-proxy.md", "symbol": "Proxy with a stripped path prefix { #proxy-with-a-stripped-path-prefix }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/behind-a-proxy.md#L100-L243", "start_line": 100, "end_line": 243} {"id": "docs/en/docs/advanced/behind-a-proxy.md::About proxies with a stripped path prefix { #about-proxies-with-a-stripped-path-prefix }::L244", "text": "# Doc: docs/en/docs/advanced/behind-a-proxy.md | Page: Behind a Proxy { #behind-a-proxy } | Section: About proxies with a stripped path prefix { #about-proxies-with-a-stripped-path-prefix }\n## About proxies with a stripped path prefix { #about-proxies-with-a-stripped-path-prefix }\n\nKeep in mind that a proxy with stripped path prefix is only one of the ways to configure it.\n\nProbably in many cases the default will be that the proxy doesn't have a stripped path prefix.\n\nIn a case like that (without a stripped path prefix), the proxy would listen on something like `https://myawesomeapp.com`, and then if the browser goes to `https://myawesomeapp.com/api/v1/app` and your server (e.g. Uvicorn) listens on `http://127.0.0.1:8000` the proxy (without a stripped path prefix) would access Uvicorn at the same path: `http://127.0.0.1:8000/api/v1/app`.", "source_type": "doc", "path": "docs/en/docs/advanced/behind-a-proxy.md", "symbol": "About proxies with a stripped path prefix { #about-proxies-with-a-stripped-path-prefix }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/behind-a-proxy.md#L244-L251", "start_line": 244, "end_line": 251} {"id": "docs/en/docs/advanced/behind-a-proxy.md::Testing locally with Traefik { #testing-locally-with-traefik }::L252", "text": "# Doc: docs/en/docs/advanced/behind-a-proxy.md | Page: Behind a Proxy { #behind-a-proxy } | Section: Testing locally with Traefik { #testing-locally-with-traefik }\n## Testing locally with Traefik { #testing-locally-with-traefik }\n\nYou can easily run the experiment locally with a stripped path prefix using [Traefik](https://docs.traefik.io/).\n\n[Download Traefik](https://github.com/containous/traefik/releases), it's a single binary, you can extract the compressed file and run it directly from the terminal.\n\nThen create a file `traefik.toml` with:\n\n```TOML hl_lines=\"3\"\n[entryPoints]\n [entryPoints.http]\n address = \":9999\"\n\n[providers]\n [providers.file]\n filename = \"routes.toml\"\n```\n\nThis tells Traefik to listen on port 9999 and to use another file `routes.toml`.\n\n/// tip\n\nWe are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges.\n\n///\n\nNow create that other file `routes.toml`:\n\n```TOML hl_lines=\"5 12 20\"\n[http]\n [http.middlewares]\n\n [http.middlewares.api-stripprefix.stripPrefix]\n prefixes = [\"/api/v1\"]\n\n [http.routers]\n\n [http.routers.app-http]\n entryPoints = [\"http\"]\n service = \"app\"\n rule = \"PathPrefix(`/api/v1`)\"\n middlewares = [\"api-stripprefix\"]\n\n [http.services]\n\n [http.services.app]\n [http.services.app.loadBalancer]\n [[http.services.app.loadBalancer.servers]]\n url = \"http://127.0.0.1:8000\"\n```\n\nThis file configures Traefik to use the path prefix `/api/v1`.\n\nAnd then Traefik will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`.\n\nNow start Traefik:\n\n
\n\n```console\n$ ./traefik --configFile=traefik.toml\n\nINFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml\n```\n\n
\n\nAnd now start your app, using the `--root-path` option:\n\n
\n\n```console\n$ fastapi run main.py --forwarded-allow-ips=\"*\" --root-path /api/v1\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\n### Check the responses { #check-the-responses }\n\nNow, if you go to the URL with the port for Uvicorn: [http://127.0.0.1:8000/app](http://127.0.0.1:8000/app), you will see the normal response:\n\n```JSON\n{\n \"message\": \"Hello World\",\n \"root_path\": \"/api/v1\"\n}\n```\n\n/// tip\n\nNotice that even though you are accessing it at `http://127.0.0.1:8000/app` it shows the `root_path` of `/api/v1`, taken from the option `--root-path`.\n\n///\n\nAnd now open the URL with the port for Traefik, including the path prefix: [http://127.0.0.1:9999/api/v1/app](http://127.0.0.1:9999/api/v1/app).\n\nWe get the same response:\n\n```JSON\n{\n \"message\": \"Hello World\",\n \"root_path\": \"/api/v1\"\n}\n```\n\nbut this time at the URL with the prefix path provided by the proxy: `/api/v1`.\n\nOf course, the idea here is that everyone would access the app through the proxy, so the version with the path prefix `/api/v1` is the \"correct\" one.\n\nAnd the version without the path prefix (`http://127.0.0.1:8000/app`), provided by Uvicorn directly, would be exclusively for the _proxy_ (Traefik) to access it.\n\nThat demonstrates how the Proxy (Traefik) uses the path prefix and how the server (Uvicorn) uses the `root_path` from the option `--root-path`.\n\n### Check the docs UI { #check-the-docs-ui }\n\nBut here's the fun part. ✨\n\nThe \"official\" way to access the app would be through the proxy with the path prefix that we defined. So, as we would expect, if you try the docs UI served by Uvicorn directly, without the path prefix in the URL, it won't work, because it expects to be accessed through the proxy.\n\nYou can check it at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs):\n\n\n\nBut if we access the docs UI at the \"official\" URL using the proxy with port `9999`, at `/api/v1/docs`, it works correctly! 🎉\n\nYou can check it at [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs):\n\n\n\nRight as we wanted it. ✔️\n\nThis is because FastAPI uses this `root_path` to create the default `server` in OpenAPI with the URL provided by `root_path`.", "source_type": "doc", "path": "docs/en/docs/advanced/behind-a-proxy.md", "symbol": "Testing locally with Traefik { #testing-locally-with-traefik }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/behind-a-proxy.md#L252-L386", "start_line": 252, "end_line": 386} {"id": "docs/en/docs/advanced/behind-a-proxy.md::Additional servers { #additional-servers }::L387", "text": "# Doc: docs/en/docs/advanced/behind-a-proxy.md | Page: Behind a Proxy { #behind-a-proxy } | Section: Additional servers { #additional-servers }\n## Additional servers { #additional-servers }\n\n/// warning\n\nThis is a more advanced use case. Feel free to skip it.\n\n///\n\nBy default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`.\n\nBut you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with both a staging and a production environment.\n\nIf you pass a custom list of `servers` and there's a `root_path` (because your API lives behind a proxy), **FastAPI** will insert a \"server\" with this `root_path` at the beginning of the list.\n\nFor example:\n\n{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}\n\nWill generate an OpenAPI schema like:\n\n```JSON hl_lines=\"5-7\"\n{\n \"openapi\": \"3.1.0\",\n // More stuff here\n \"servers\": [\n {\n \"url\": \"/api/v1\"\n },\n {\n \"url\": \"https://stag.example.com\",\n \"description\": \"Staging environment\"\n },\n {\n \"url\": \"https://prod.example.com\",\n \"description\": \"Production environment\"\n }\n ],\n \"paths\": {\n // More stuff here\n }\n}\n```\n\n/// tip\n\nNotice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`.\n\n///\n\nIn the docs UI at [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) it would look like:\n\n\n\n/// tip\n\nThe docs UI will interact with the server that you select.\n\n///\n\n/// note | Technical Details\n\nThe `servers` property in the OpenAPI specification is optional.\n\nIf you don't specify the `servers` parameter and `root_path` is equal to `/`, the `servers` property in the generated OpenAPI schema will be omitted entirely by default, which is the equivalent of a single server with a `url` value of `/`.\n\n///\n\n### Disable automatic server from `root_path` { #disable-automatic-server-from-root-path }\n\nIf you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`:\n\n{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}\n\nand then it won't include it in the OpenAPI schema.", "source_type": "doc", "path": "docs/en/docs/advanced/behind-a-proxy.md", "symbol": "Additional servers { #additional-servers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/behind-a-proxy.md#L387-L461", "start_line": 387, "end_line": 461} {"id": "docs/en/docs/advanced/behind-a-proxy.md::Mounting a sub-application { #mounting-a-sub-application }::L462", "text": "# Doc: docs/en/docs/advanced/behind-a-proxy.md | Page: Behind a Proxy { #behind-a-proxy } | Section: Mounting a sub-application { #mounting-a-sub-application }\n## Mounting a sub-application { #mounting-a-sub-application }\n\nIf you need to mount a sub-application (as described in [Sub Applications - Mounts](sub-applications.md)) while also using a proxy with `root_path`, you can do it normally, as you would expect.\n\nFastAPI will internally use the `root_path` smartly, so it will just work. ✨", "source_type": "doc", "path": "docs/en/docs/advanced/behind-a-proxy.md", "symbol": "Mounting a sub-application { #mounting-a-sub-application }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/behind-a-proxy.md#L462-L466", "start_line": 462, "end_line": 466} {"id": "docs/en/docs/advanced/custom-response.md::Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others }::L1", "text": "# Doc: docs/en/docs/advanced/custom-response.md | Page: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others } | Section: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others }\n# Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others }\n\nBy default, **FastAPI** will return JSON responses.\n\nYou can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md).\n\nBut if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific \"media type\", in the HTTP header `Content-Type` as part of the generated OpenAPI).\n\nBut you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter.\n\nThe contents that you return from your *path operation function* will be put inside of that `Response`.\n\n/// note\n\nIf you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/custom-response.md", "symbol": "Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/custom-response.md#L1-L18", "start_line": 1, "end_line": 18} {"id": "docs/en/docs/advanced/custom-response.md::JSON Responses { #json-responses }::L19", "text": "# Doc: docs/en/docs/advanced/custom-response.md | Page: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others } | Section: JSON Responses { #json-responses }\n## JSON Responses { #json-responses }\n\nBy default FastAPI returns JSON responses.\n\nIf you declare a [Response Model](../tutorial/response-model.md) FastAPI will use it to serialize the data to JSON, using Pydantic.\n\nIf you don't declare a response model, FastAPI will use the `jsonable_encoder` explained in [JSON Compatible Encoder](../tutorial/encoder.md) and put it in a `JSONResponse`.\n\nIf you declare a `response_class` with a JSON media type (`application/json`), like is the case with the `JSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*. But the data won't be serialized to JSON bytes with Pydantic, instead it will be converted with the `jsonable_encoder` and then passed to the `JSONResponse` class, which will serialize it to bytes using the standard JSON library in Python.\n\n### JSON Performance { #json-performance }\n\nIn short, if you want the maximum performance, use a [Response Model](../tutorial/response-model.md) and don't declare a `response_class` in the *path operation decorator*.\n\n{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}", "source_type": "doc", "path": "docs/en/docs/advanced/custom-response.md", "symbol": "JSON Responses { #json-responses }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/custom-response.md#L19-L34", "start_line": 19, "end_line": 34} {"id": "docs/en/docs/advanced/custom-response.md::HTML Response { #html-response }::L35", "text": "# Doc: docs/en/docs/advanced/custom-response.md | Page: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others } | Section: HTML Response { #html-response }\n## HTML Response { #html-response }\n\nTo return a response with HTML directly from **FastAPI**, use `HTMLResponse`.\n\n* Import `HTMLResponse`.\n* Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*.\n\n{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}\n\n/// note\n\nThe parameter `response_class` will also be used to define the \"media type\" of the response.\n\nIn this case, the HTTP header `Content-Type` will be set to `text/html`.\n\nAnd it will be documented as such in OpenAPI.\n\n///\n\n### Return a `Response` { #return-a-response }\n\nAs seen in [Return a Response directly](response-directly.md), you can also override the response directly in your *path operation*, by returning it.\n\nThe same example from above, returning an `HTMLResponse`, could look like:\n\n{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}\n\n/// warning\n\nA `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.\n\n///\n\n/// note\n\nOf course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned.\n\n///\n\n### Document in OpenAPI and override `Response` { #document-in-openapi-and-override-response }\n\nIf you want to override the response from inside of the function but at the same time document the \"media type\" in OpenAPI, you can use the `response_class` parameter AND return a `Response` object.\n\nThe `response_class` will then be used only to document the OpenAPI *path operation*, but your `Response` will be used as is.\n\n#### Return an `HTMLResponse` directly { #return-an-htmlresponse-directly }\n\nFor example, it could be something like:\n\n{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}\n\nIn this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`.\n\nBy returning the result of calling `generate_html_response()`, you are already returning a `Response` that will override the default **FastAPI** behavior.\n\nBut as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** will know how to document it in OpenAPI and the interactive docs as HTML with `text/html`:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/custom-response.md", "symbol": "HTML Response { #html-response }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/custom-response.md#L35-L93", "start_line": 35, "end_line": 93} {"id": "docs/en/docs/advanced/custom-response.md::Available responses { #available-responses }::L94", "text": "# Doc: docs/en/docs/advanced/custom-response.md | Page: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others } | Section: Available responses { #available-responses }\n## Available responses { #available-responses }\n\nHere are some of the available responses.\n\nKeep in mind that you can use `Response` to return anything else, or even create a custom sub-class.\n\n/// note | Technical Details\n\nYou could also use `from starlette.responses import HTMLResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.\n\n///\n\n### `Response` { #response }\n\nThe main `Response` class, all the other responses inherit from it.\n\nYou can return it directly.\n\nIt accepts the following parameters:\n\n* `content` - A `str` or `bytes`.\n* `status_code` - An `int` HTTP status code.\n* `headers` - A `dict` of strings.\n* `media_type` - A `str` giving the media type. E.g. `\"text/html\"`.\n\nFastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types.\n\n{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}\n\n### `HTMLResponse` { #htmlresponse }\n\nTakes some text or bytes and returns an HTML response, as you read above.\n\n### `PlainTextResponse` { #plaintextresponse }\n\nTakes some text or bytes and returns a plain text response.\n\n{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}\n\n### `JSONResponse` { #jsonresponse }\n\nTakes some data and returns an `application/json` encoded response.\n\nThis is the default response used in **FastAPI**, as you read above.\n\n/// note | Technical Details\n\nBut if you declare a response model or return type, that will be used directly to serialize the data to JSON, and a response with the right media type for JSON will be returned directly, without using the `JSONResponse` class.\n\nThis is the ideal way to get the best performance.\n\n///\n\n### `RedirectResponse` { #redirectresponse }\n\nReturns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default.\n\nYou can return a `RedirectResponse` directly:\n\n{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}\n\n---\n\nOr you can use it in the `response_class` parameter:\n\n\n{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}\n\nIf you do that, then you can return the URL directly from your *path operation* function.\n\nIn this case, the `status_code` used will be the default one for the `RedirectResponse`, which is `307`.\n\n---\n\nYou can also use the `status_code` parameter combined with the `response_class` parameter:\n\n{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}\n\n### `StreamingResponse` { #streamingresponse }\n\nTakes an async generator or a normal generator/iterator (a function with `yield`) and streams the response body.\n\n{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}\n\n/// note | Technical Details\n\nAn `async` task can only be cancelled when it reaches an `await`. If there is no `await`, the generator (function with `yield`) can not be cancelled properly and may keep running even after cancellation is requested.\n\nSince this small example does not need any `await` statements, we add an `await anyio.sleep(0)` to give the event loop a chance to handle cancellation.\n\nThis would be even more important with large or infinite streams.\n\n///\n\n/// tip\n\nInstead of returning a `StreamingResponse` directly, you should probably follow the style in [Stream Data](./stream-data.md), it's much more convenient and handles cancellation behind the scenes for you.\n\nIf you are streaming JSON Lines, follow the [Stream JSON Lines](../tutorial/stream-json-lines.md) tutorial.\n\n///\n\n### `FileResponse` { #fileresponse }\n\nAsynchronously streams a file as the response.\n\nTakes a different set of arguments to instantiate than the other response types:\n\n* `path` - The file path to the file to stream.\n* `headers` - Any custom headers to include, as a dictionary.\n* `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type.\n* `filename` - If set, this will be included in the response `Content-Disposition`.\n\nFile responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers.\n\n{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}\n\nYou can also use the `response_class` parameter:\n\n{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}\n\nIn this case, you can return the file path directly from your *path operation* function.", "source_type": "doc", "path": "docs/en/docs/advanced/custom-response.md", "symbol": "Available responses { #available-responses }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/custom-response.md#L94-L218", "start_line": 94, "end_line": 218} {"id": "docs/en/docs/advanced/custom-response.md::Custom response class { #custom-response-class }::L219", "text": "# Doc: docs/en/docs/advanced/custom-response.md | Page: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others } | Section: Custom response class { #custom-response-class }\n## Custom response class { #custom-response-class }\n\nYou can create your own custom response class, inheriting from `Response` and using it.\n\nFor example, let's say that you want to use [`orjson`](https://github.com/ijl/orjson) with some settings.\n\nLet's say you want it to return indented and formatted JSON, so you want to use the orjson option `orjson.OPT_INDENT_2`.\n\nYou could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`:\n\n{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}\n\nNow instead of returning:\n\n```json\n{\"message\": \"Hello World\"}\n```\n\n...this response will return:\n\n```json\n{\n \"message\": \"Hello World\"\n}\n```\n\nOf course, you will probably find much better ways to take advantage of this than formatting JSON. 😉\n\n### `orjson` or Response Model { #orjson-or-response-model }\n\nIf what you are looking for is performance, you are probably better off using a [Response Model](../tutorial/response-model.md) than an `orjson` response.\n\nWith a response model, FastAPI will use Pydantic to serialize the data to JSON, without using intermediate steps, like converting it with `jsonable_encoder`, which would happen in any other case.\n\nAnd under the hood, Pydantic uses the same underlying Rust mechanisms as `orjson` to serialize to JSON, so you will already get the best performance with a response model.", "source_type": "doc", "path": "docs/en/docs/advanced/custom-response.md", "symbol": "Custom response class { #custom-response-class }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/custom-response.md#L219-L254", "start_line": 219, "end_line": 254} {"id": "docs/en/docs/advanced/custom-response.md::Default response class { #default-response-class }::L255", "text": "# Doc: docs/en/docs/advanced/custom-response.md | Page: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others } | Section: Default response class { #default-response-class }\n## Default response class { #default-response-class }\n\nWhen creating a **FastAPI** class instance or an `APIRouter` you can specify which response class to use by default.\n\nThe parameter that defines this is `default_response_class`.\n\nIn the example below, **FastAPI** will use `HTMLResponse` by default, in all *path operations*, instead of JSON.\n\n{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}\n\n/// tip\n\nYou can still override `response_class` in *path operations* as before.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/custom-response.md", "symbol": "Default response class { #default-response-class }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/custom-response.md#L255-L270", "start_line": 255, "end_line": 270} {"id": "docs/en/docs/advanced/custom-response.md::Additional documentation { #additional-documentation }::L271", "text": "# Doc: docs/en/docs/advanced/custom-response.md | Page: Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others } | Section: Additional documentation { #additional-documentation }\n## Additional documentation { #additional-documentation }\n\nYou can also declare the media type and many other details in OpenAPI using `responses`: [Additional Responses in OpenAPI](additional-responses.md).", "source_type": "doc", "path": "docs/en/docs/advanced/custom-response.md", "symbol": "Additional documentation { #additional-documentation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/custom-response.md#L271-L273", "start_line": 271, "end_line": 273} {"id": "docs/en/docs/advanced/dataclasses.md::Using Dataclasses { #using-dataclasses }::L1", "text": "# Doc: docs/en/docs/advanced/dataclasses.md | Page: Using Dataclasses { #using-dataclasses } | Section: Using Dataclasses { #using-dataclasses }\n# Using Dataclasses { #using-dataclasses }\n\nFastAPI is built on top of **Pydantic**, and I have been showing you how to use Pydantic models to declare requests and responses.\n\nBut FastAPI also supports using [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) the same way:\n\n{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}\n\nThis is still supported thanks to **Pydantic**, as it has [internal support for `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).\n\nSo, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses.\n\nAnd of course, it supports the same:\n\n* data validation\n* data serialization\n* data documentation, etc.\n\nThis works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic.\n\n/// note\n\nKeep in mind that dataclasses can't do everything Pydantic models can do.\n\nSo, you might still need to use Pydantic models.\n\nBut if you have a bunch of dataclasses lying around, this is a nice trick to use them to power a web API using FastAPI. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/dataclasses.md", "symbol": "Using Dataclasses { #using-dataclasses }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/dataclasses.md#L1-L30", "start_line": 1, "end_line": 30} {"id": "docs/en/docs/advanced/dataclasses.md::Dataclasses in `response_model` { #dataclasses-in-response-model }::L31", "text": "# Doc: docs/en/docs/advanced/dataclasses.md | Page: Using Dataclasses { #using-dataclasses } | Section: Dataclasses in `response_model` { #dataclasses-in-response-model }\n## Dataclasses in `response_model` { #dataclasses-in-response-model }\n\nYou can also use `dataclasses` in the `response_model` parameter:\n\n{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}\n\nThe dataclass will be automatically converted to a Pydantic dataclass.\n\nThis way, its schema will show up in the API docs user interface:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/dataclasses.md", "symbol": "Dataclasses in `response_model` { #dataclasses-in-response-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/dataclasses.md#L31-L42", "start_line": 31, "end_line": 42} {"id": "docs/en/docs/advanced/dataclasses.md::Dataclasses in Nested Data Structures { #dataclasses-in-nested-data-structures }::L43", "text": "# Doc: docs/en/docs/advanced/dataclasses.md | Page: Using Dataclasses { #using-dataclasses } | Section: Dataclasses in Nested Data Structures { #dataclasses-in-nested-data-structures }\n## Dataclasses in Nested Data Structures { #dataclasses-in-nested-data-structures }\n\nYou can also combine `dataclasses` with other type annotations to make nested data structures.\n\nIn some cases, you might still have to use Pydantic's version of `dataclasses`. For example, if you have errors with the automatically generated API documentation.\n\nIn that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement:\n\n{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}\n\n1. We still import `field` from standard `dataclasses`.\n\n2. `pydantic.dataclasses` is a drop-in replacement for `dataclasses`.\n\n3. The `Author` dataclass includes a list of `Item` dataclasses.\n\n4. The `Author` dataclass is used as the `response_model` parameter.\n\n5. You can use other standard type annotations with dataclasses as the request body.\n\n In this case, it's a list of `Item` dataclasses.\n\n6. Here we are returning a dictionary that contains `items` which is a list of dataclasses.\n\n FastAPI is still capable of serializing the data to JSON.\n\n7. Here the `response_model` is using a type annotation of a list of `Author` dataclasses.\n\n Again, you can combine `dataclasses` with standard type annotations.\n\n8. Notice that this *path operation function* uses regular `def` instead of `async def`.\n\n As always, in FastAPI you can combine `def` and `async def` as needed.\n\n If you need a refresher about when to use which, check out the section _\"In a hurry?\"_ in the docs about [`async` and `await`](../async.md#in-a-hurry).\n\n9. This *path operation function* is not returning dataclasses (although it could), but a list of dictionaries with internal data.\n\n FastAPI will use the `response_model` parameter (that includes dataclasses) to convert the response.\n\nYou can combine `dataclasses` with other type annotations in many different combinations to form complex data structures.\n\nCheck the in-code annotation tips above to see more specific details.", "source_type": "doc", "path": "docs/en/docs/advanced/dataclasses.md", "symbol": "Dataclasses in Nested Data Structures { #dataclasses-in-nested-data-structures }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/dataclasses.md#L43-L86", "start_line": 43, "end_line": 86} {"id": "docs/en/docs/advanced/dataclasses.md::Learn More { #learn-more }::L87", "text": "# Doc: docs/en/docs/advanced/dataclasses.md | Page: Using Dataclasses { #using-dataclasses } | Section: Learn More { #learn-more }\n## Learn More { #learn-more }\n\nYou can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc.\n\nTo learn more, check the [Pydantic docs about dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).", "source_type": "doc", "path": "docs/en/docs/advanced/dataclasses.md", "symbol": "Learn More { #learn-more }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/dataclasses.md#L87-L92", "start_line": 87, "end_line": 92} {"id": "docs/en/docs/advanced/dataclasses.md::Version { #version }::L93", "text": "# Doc: docs/en/docs/advanced/dataclasses.md | Page: Using Dataclasses { #using-dataclasses } | Section: Version { #version }\n## Version { #version }\n\nThis is available since FastAPI version `0.67.0`. 🔖", "source_type": "doc", "path": "docs/en/docs/advanced/dataclasses.md", "symbol": "Version { #version }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/dataclasses.md#L93-L95", "start_line": 93, "end_line": 95} {"id": "docs/en/docs/advanced/events.md::Lifespan Events { #lifespan-events }::L1", "text": "# Doc: docs/en/docs/advanced/events.md | Page: Lifespan Events { #lifespan-events } | Section: Lifespan Events { #lifespan-events }\n# Lifespan Events { #lifespan-events }\n\nYou can define logic (code) that should be executed before the application **starts up**. This means that this code will be executed **once**, **before** the application **starts receiving requests**.\n\nThe same way, you can define logic (code) that should be executed when the application is **shutting down**. In this case, this code will be executed **once**, **after** having handled possibly **many requests**.\n\nBecause this code is executed before the application **starts** taking requests, and right after it **finishes** handling requests, it covers the whole application **lifespan** (the word \"lifespan\" will be important in a second 😉).\n\nThis can be very useful for setting up **resources** that you need to use for the whole app, and that are **shared** among requests, and/or that you need to **clean up** afterwards. For example, a database connection pool, or loading a shared machine learning model.", "source_type": "doc", "path": "docs/en/docs/advanced/events.md", "symbol": "Lifespan Events { #lifespan-events }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/events.md#L1-L10", "start_line": 1, "end_line": 10} {"id": "docs/en/docs/advanced/events.md::Use Case { #use-case }::L11", "text": "# Doc: docs/en/docs/advanced/events.md | Page: Lifespan Events { #lifespan-events } | Section: Use Case { #use-case }\n## Use Case { #use-case }\n\nLet's start with an example **use case** and then see how to solve it with this.\n\nLet's imagine that you have some **machine learning models** that you want to use to handle requests. 🤖\n\nThe same models are shared among requests, so, it's not one model per request, or one per user or something similar.\n\nLet's imagine that loading the model can **take quite some time**, because it has to read a lot of **data from disk**. So you don't want to do it for every request.\n\nYou could load it at the top level of the module/file, but that would also mean that it would **load the model** even if you are just running a simple automated test, then that test would be **slow** because it would have to wait for the model to load before being able to run an independent part of the code.\n\nThat's what we'll solve, let's load the model before the requests are handled, but only right before the application starts receiving requests, not while the code is being loaded.", "source_type": "doc", "path": "docs/en/docs/advanced/events.md", "symbol": "Use Case { #use-case }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/events.md#L11-L24", "start_line": 11, "end_line": 24} {"id": "docs/en/docs/advanced/events.md::Lifespan { #lifespan }::L25", "text": "# Doc: docs/en/docs/advanced/events.md | Page: Lifespan Events { #lifespan-events } | Section: Lifespan { #lifespan }\n## Lifespan { #lifespan }\n\nYou can define this *startup* and *shutdown* logic using the `lifespan` parameter of the `FastAPI` app, and a \"context manager\" (I'll show you what that is in a second).\n\nLet's start with an example and then see it in detail.\n\nWe create an async function `lifespan()` with `yield` like this:\n\n{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}\n\nHere we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*.\n\nAnd then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU.\n\n/// tip\n\nThe `shutdown` would happen when you are **stopping** the application.\n\nMaybe you need to start a new version, or you just got tired of running it. 🤷\n\n///\n\n### Lifespan function { #lifespan-function }\n\nThe first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`.\n\n{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}\n\nThe first part of the function, before the `yield`, will be executed **before** the application starts.\n\nAnd the part after the `yield` will be executed **after** the application has finished.\n\n### Async Context Manager { #async-context-manager }\n\nIf you check, the function is decorated with an `@asynccontextmanager`.\n\nThat converts the function into something called an \"**async context manager**\".\n\n{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}\n\nA **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager:\n\n```Python\nwith open(\"file.txt\") as file:\n file.read()\n```\n\nIn recent versions of Python, there's also an **async context manager**. You would use it with `async with`:\n\n```Python\nasync with lifespan(app):\n await do_stuff()\n```\n\nWhen you create a context manager or an async context manager like above, what it does is that, before entering the `with` block, it will execute the code before the `yield`, and after exiting the `with` block, it will execute the code after the `yield`.\n\nIn our code example above, we don't use it directly, but we pass it to FastAPI for it to use it.\n\nThe `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it.\n\n{* ../../docs_src/events/tutorial003_py310.py hl[22] *}", "source_type": "doc", "path": "docs/en/docs/advanced/events.md", "symbol": "Lifespan { #lifespan }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/events.md#L25-L86", "start_line": 25, "end_line": 86} {"id": "docs/en/docs/advanced/events.md::Alternative Events (deprecated) { #alternative-events-deprecated }::L87", "text": "# Doc: docs/en/docs/advanced/events.md | Page: Lifespan Events { #lifespan-events } | Section: Alternative Events (deprecated) { #alternative-events-deprecated }\n## Alternative Events (deprecated) { #alternative-events-deprecated }\n\n/// warning\n\nThe recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both.\n\nYou can probably skip this part.\n\n///\n\nThere's an alternative way to define this logic to be executed during *startup* and during *shutdown*.\n\nYou can define event handlers (functions) that need to be executed before the application starts up, or when the application is shutting down.\n\nThese functions can be declared with `async def` or normal `def`.\n\n### `startup` event { #startup-event }\n\nTo add a function that should be run before the application starts, declare it with the event `\"startup\"`:\n\n{* ../../docs_src/events/tutorial001_py310.py hl[8] *}\n\nIn this case, the `startup` event handler function will initialize the items \"database\" (just a `dict`) with some values.\n\nYou can add more than one event handler function.\n\nAnd your application won't start receiving requests until all the `startup` event handlers have completed.\n\n### `shutdown` event { #shutdown-event }\n\nTo add a function that should be run when the application is shutting down, declare it with the event `\"shutdown\"`:\n\n{* ../../docs_src/events/tutorial002_py310.py hl[6] *}\n\nHere, the `shutdown` event handler function will write a text line `\"Application shutdown\"` to a file `log.txt`.\n\n/// note\n\nIn the `open()` function, the `mode=\"a\"` means \"append\", so, the line will be added after whatever is on that file, without overwriting the previous contents.\n\n///\n\n/// tip\n\nNotice that in this case we are using a standard Python `open()` function that interacts with a file.\n\nSo, it involves I/O (input/output), that requires \"waiting\" for things to be written to disk.\n\nBut `open()` doesn't use `async` and `await`.\n\nSo, we declare the event handler function with standard `def` instead of `async def`.\n\n///\n\n### `startup` and `shutdown` together { #startup-and-shutdown-together }\n\nThere's a high chance that the logic for your *startup* and *shutdown* is connected, you might want to start something and then finish it, acquire a resource and then release it, etc.\n\nDoing that in separate functions that don't share logic or variables together is more difficult as you would need to store values in global variables or similar tricks.\n\nBecause of that, it's now recommended to instead use the `lifespan` as explained above.", "source_type": "doc", "path": "docs/en/docs/advanced/events.md", "symbol": "Alternative Events (deprecated) { #alternative-events-deprecated }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/events.md#L87-L148", "start_line": 87, "end_line": 148} {"id": "docs/en/docs/advanced/events.md::Technical Details { #technical-details }::L149", "text": "# Doc: docs/en/docs/advanced/events.md | Page: Lifespan Events { #lifespan-events } | Section: Technical Details { #technical-details }\n## Technical Details { #technical-details }\n\nJust a technical detail for the curious nerds. 🤓\n\nUnderneath, in the ASGI technical specification, this is part of the [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), and it defines events called `startup` and `shutdown`.\n\n/// note\n\nYou can read more about the Starlette `lifespan` handlers in [Starlette's Lifespan' docs](https://www.starlette.dev/lifespan/).\n\nIncluding how to handle lifespan state that can be used in other areas of your code.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/events.md", "symbol": "Technical Details { #technical-details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/events.md#L149-L162", "start_line": 149, "end_line": 162} {"id": "docs/en/docs/advanced/events.md::Sub Applications { #sub-applications }::L163", "text": "# Doc: docs/en/docs/advanced/events.md | Page: Lifespan Events { #lifespan-events } | Section: Sub Applications { #sub-applications }\n## Sub Applications { #sub-applications }\n\n🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](sub-applications.md).", "source_type": "doc", "path": "docs/en/docs/advanced/events.md", "symbol": "Sub Applications { #sub-applications }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/events.md#L163-L165", "start_line": 163, "end_line": 165} {"id": "docs/en/docs/advanced/generate-clients.md::Generating SDKs { #generating-sdks }::L1", "text": "# Doc: docs/en/docs/advanced/generate-clients.md | Page: Generating SDKs { #generating-sdks } | Section: Generating SDKs { #generating-sdks }\n# Generating SDKs { #generating-sdks }\n\nBecause **FastAPI** is based on the **OpenAPI** specification, its APIs can be described in a standard format that many tools understand.\n\nThis makes it easy to generate up-to-date **documentation**, client libraries (**SDKs**) in multiple languages, and **testing** or **automation workflows** that stay in sync with your code.\n\nIn this guide, you'll learn how to generate a **TypeScript SDK** for your FastAPI backend.", "source_type": "doc", "path": "docs/en/docs/advanced/generate-clients.md", "symbol": "Generating SDKs { #generating-sdks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/generate-clients.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/advanced/generate-clients.md::Open Source SDK Generators { #open-source-sdk-generators }::L9", "text": "# Doc: docs/en/docs/advanced/generate-clients.md | Page: Generating SDKs { #generating-sdks } | Section: Open Source SDK Generators { #open-source-sdk-generators }\n## Open Source SDK Generators { #open-source-sdk-generators }\n\nA versatile option is the [OpenAPI Generator](https://openapi-generator.tech/), which supports **many programming languages** and can generate SDKs from your OpenAPI specification.\n\nFor **TypeScript clients**, [Hey API](https://heyapi.dev/) is a purpose-built solution, providing an optimized experience for the TypeScript ecosystem.\n\nYou can discover more SDK generators on [OpenAPI.Tools](https://openapi.tools/#sdk).\n\n/// tip\n\nFastAPI automatically generates **OpenAPI 3.1** specifications, so any tool you use must support this version.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/generate-clients.md", "symbol": "Open Source SDK Generators { #open-source-sdk-generators }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/generate-clients.md#L9-L22", "start_line": 9, "end_line": 22} {"id": "docs/en/docs/advanced/generate-clients.md::Create a TypeScript SDK { #create-a-typescript-sdk }::L23", "text": "# Doc: docs/en/docs/advanced/generate-clients.md | Page: Generating SDKs { #generating-sdks } | Section: Create a TypeScript SDK { #create-a-typescript-sdk }\n## Create a TypeScript SDK { #create-a-typescript-sdk }\n\nLet's start with a simple FastAPI application:\n\n{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}\n\nNotice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.\n\n### API Docs { #api-docs }\n\nIf you go to `/docs`, you will see that it has the **schemas** for the data to be sent in requests and received in responses:\n\n\n\nYou can see those schemas because they were declared with the models in the app.\n\nThat information is available in the app's **OpenAPI schema**, and then shown in the API docs.\n\nThat same information from the models that is included in OpenAPI is what can be used to **generate the client code**.\n\n### Hey API { #hey-api }\n\nOnce we have a FastAPI app with the models, we can use Hey API to generate a TypeScript client. The fastest way to do that is via npx.\n\n```sh\nnpx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client\n```\n\nThis will generate a TypeScript SDK in `./src/client`.\n\nYou can learn how to [install `@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/get-started) and read about the [generated output](https://heyapi.dev/openapi-ts/output) on their website.\n\n### Using the SDK { #using-the-sdk }\n\nNow you can import and use the client code. It could look like this, notice that you get autocompletion for the methods:\n\n\n\nYou will also get autocompletion for the payload to send:\n\n\n\n/// tip\n\nNotice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model.\n\n///\n\nYou will have inline errors for the data that you send:\n\n\n\nThe response object will also have autocompletion:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/generate-clients.md", "symbol": "Create a TypeScript SDK { #create-a-typescript-sdk }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/generate-clients.md#L23-L78", "start_line": 23, "end_line": 78} {"id": "docs/en/docs/advanced/generate-clients.md::FastAPI App with Tags { #fastapi-app-with-tags }::L79", "text": "# Doc: docs/en/docs/advanced/generate-clients.md | Page: Generating SDKs { #generating-sdks } | Section: FastAPI App with Tags { #fastapi-app-with-tags }\n## FastAPI App with Tags { #fastapi-app-with-tags }\n\nIn many cases, your FastAPI app will be bigger, and you will probably use tags to separate different groups of *path operations*.\n\nFor example, you could have a section for **items** and another section for **users**, and they could be separated by tags:\n\n{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}\n\n### Generate a TypeScript Client with Tags { #generate-a-typescript-client-with-tags }\n\nIf you generate a client for a FastAPI app using tags, it will normally also separate the client code based on the tags.\n\nThis way, you will be able to have things ordered and grouped correctly for the client code:\n\n\n\nIn this case, you have:\n\n* `ItemsService`\n* `UsersService`\n\n### Client Method Names { #client-method-names }\n\nRight now, the generated method names like `createItemItemsPost` don't look very clean:\n\n```TypeScript\nItemsService.createItemItemsPost({name: \"Plumbus\", price: 5})\n```\n\n...that's because the client generator uses the OpenAPI internal **operation ID** for each *path operation*.\n\nOpenAPI requires that each operation ID is unique across all the *path operations*, so FastAPI uses the **function name**, the **path**, and the **HTTP method/operation** to generate that operation ID, because that way it can make sure that the operation IDs are unique.\n\nBut I'll show you how to improve that next. 🤓", "source_type": "doc", "path": "docs/en/docs/advanced/generate-clients.md", "symbol": "FastAPI App with Tags { #fastapi-app-with-tags }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/generate-clients.md#L79-L113", "start_line": 79, "end_line": 113} {"id": "docs/en/docs/advanced/generate-clients.md::Custom Operation IDs and Better Method Names { #custom-operation-ids-and-better-method-names }::L114", "text": "# Doc: docs/en/docs/advanced/generate-clients.md | Page: Generating SDKs { #generating-sdks } | Section: Custom Operation IDs and Better Method Names { #custom-operation-ids-and-better-method-names }\n## Custom Operation IDs and Better Method Names { #custom-operation-ids-and-better-method-names }\n\nYou can **modify** the way these operation IDs are **generated** to make them simpler and have **simpler method names** in the clients.\n\nIn this case, you will have to ensure that each operation ID is **unique** in some other way.\n\nFor example, you could make sure that each *path operation* has a tag, and then generate the operation ID based on the **tag** and the *path operation* **name** (the function name).\n\n### Custom Generate Unique ID Function { #custom-generate-unique-id-function }\n\nFastAPI uses a **unique ID** for each *path operation*, which is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.\n\nYou can customize that function. It takes an `APIRoute` and outputs a string.\n\nFor example, here it is using the first tag (you will probably have only one tag) and the *path operation* name (the function name).\n\nYou can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter:\n\n{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}\n\n### Generate a TypeScript Client with Custom Operation IDs { #generate-a-typescript-client-with-custom-operation-ids }\n\nNow, if you generate the client again, you will see that it has the improved method names:\n\n\n\nAs you see, the method names now have the tag and then the function name, now they don't include information from the URL path and the HTTP operation.\n\n### Preprocess the OpenAPI Specification for the Client Generator { #preprocess-the-openapi-specification-for-the-client-generator }\n\nThe generated code still has some **duplicated information**.\n\nWe already know that this method is related to the **items** because that word is in the `ItemsService` (taken from the tag), but we still have the tag name prefixed in the method name too. 😕\n\nWe will probably still want to keep it for OpenAPI in general, as that will ensure that the operation IDs are **unique**.\n\nBut for the generated client, we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.\n\nWe could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:\n\n{* ../../docs_src/generate_clients/tutorial004_py310.py *}\n\n//// tab | Node.js\n\n```Javascript\n{!> ../../docs_src/generate_clients/tutorial004.js!}\n```\n\n////\n\nWith that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.\n\n### Generate a TypeScript Client with the Preprocessed OpenAPI { #generate-a-typescript-client-with-the-preprocessed-openapi }\n\nSince the end result is now in an `openapi.json` file, you need to update your input location:\n\n```sh\nnpx @hey-api/openapi-ts -i ./openapi.json -o src/client\n```\n\nAfter generating the new client, you would now have **clean method names**, with all the **autocompletion**, **inline errors**, etc:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/generate-clients.md", "symbol": "Custom Operation IDs and Better Method Names { #custom-operation-ids-and-better-method-names }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/generate-clients.md#L114-L177", "start_line": 114, "end_line": 177} {"id": "docs/en/docs/advanced/generate-clients.md::Benefits { #benefits }::L178", "text": "# Doc: docs/en/docs/advanced/generate-clients.md | Page: Generating SDKs { #generating-sdks } | Section: Benefits { #benefits }\n## Benefits { #benefits }\n\nWhen using the automatically generated clients, you would get **autocompletion** for:\n\n* Methods.\n* Request payloads in the body, query parameters, etc.\n* Response payloads.\n\nYou would also have **inline errors** for everything.\n\nAnd whenever you update the backend code, and **regenerate** the frontend, it would have any new *path operations* available as methods, the old ones removed, and any other change would be reflected on the generated code. 🤓\n\nThis also means that if something changed, it will be **reflected** on the client code automatically. And if you **build** the client, it will error out if you have any **mismatch** in the data used.\n\nSo, you would **detect many errors** very early in the development cycle instead of having to wait for the errors to show up to your final users in production and then trying to debug where the problem is. ✨", "source_type": "doc", "path": "docs/en/docs/advanced/generate-clients.md", "symbol": "Benefits { #benefits }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/generate-clients.md#L178-L192", "start_line": 178, "end_line": 192} {"id": "docs/en/docs/advanced/index.md::Additional Features { #additional-features }::L3", "text": "# Doc: docs/en/docs/advanced/index.md | Page: Advanced User Guide { #advanced-user-guide } | Section: Additional Features { #additional-features }\n## Additional Features { #additional-features }\n\nThe main [Tutorial - User Guide](../tutorial/index.md) should be enough to give you a tour through all the main features of **FastAPI**.\n\nIn the next sections you will see other options, configurations, and additional features.\n\n/// tip\n\nThe next sections are **not necessarily \"advanced\"**.\n\nAnd it's possible that for your use case, the solution is in one of them.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/index.md", "symbol": "Additional Features { #additional-features }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/index.md#L3-L16", "start_line": 3, "end_line": 16} {"id": "docs/en/docs/advanced/index.md::Read the Tutorial first { #read-the-tutorial-first }::L17", "text": "# Doc: docs/en/docs/advanced/index.md | Page: Advanced User Guide { #advanced-user-guide } | Section: Read the Tutorial first { #read-the-tutorial-first }\n## Read the Tutorial first { #read-the-tutorial-first }\n\nYou could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md).\n\nAnd the next sections assume you already read it, and assume that you know those main ideas.", "source_type": "doc", "path": "docs/en/docs/advanced/index.md", "symbol": "Read the Tutorial first { #read-the-tutorial-first }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/index.md#L17-L21", "start_line": 17, "end_line": 21} {"id": "docs/en/docs/advanced/json-base64-bytes.md::JSON with Bytes as Base64 { #json-with-bytes-as-base64 }::L1", "text": "# Doc: docs/en/docs/advanced/json-base64-bytes.md | Page: JSON with Bytes as Base64 { #json-with-bytes-as-base64 } | Section: JSON with Bytes as Base64 { #json-with-bytes-as-base64 }\n# JSON with Bytes as Base64 { #json-with-bytes-as-base64 }\n\nIf your app needs to receive and send JSON data, but you need to include binary data in it, you can encode it as base64.", "source_type": "doc", "path": "docs/en/docs/advanced/json-base64-bytes.md", "symbol": "JSON with Bytes as Base64 { #json-with-bytes-as-base64 }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/json-base64-bytes.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/advanced/json-base64-bytes.md::Base64 vs Files { #base64-vs-files }::L5", "text": "# Doc: docs/en/docs/advanced/json-base64-bytes.md | Page: JSON with Bytes as Base64 { #json-with-bytes-as-base64 } | Section: Base64 vs Files { #base64-vs-files }\n## Base64 vs Files { #base64-vs-files }\n\nConsider first if you can use [Request Files](../tutorial/request-files.md) for uploading binary data and [Custom Response - FileResponse](./custom-response.md#fileresponse) for sending binary data, instead of encoding it in JSON.\n\nJSON can only contain UTF-8 encoded strings, so it can't contain raw bytes.\n\nBase64 can encode binary data in strings, but to do it, it needs to use more characters than the original binary data, so it would normally be less efficient than regular files.\n\nUse base64 only if you definitely need to include binary data in JSON, and you can't use files for that.", "source_type": "doc", "path": "docs/en/docs/advanced/json-base64-bytes.md", "symbol": "Base64 vs Files { #base64-vs-files }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/json-base64-bytes.md#L5-L14", "start_line": 5, "end_line": 14} {"id": "docs/en/docs/advanced/json-base64-bytes.md::Pydantic `bytes` { #pydantic-bytes }::L15", "text": "# Doc: docs/en/docs/advanced/json-base64-bytes.md | Page: JSON with Bytes as Base64 { #json-with-bytes-as-base64 } | Section: Pydantic `bytes` { #pydantic-bytes }\n## Pydantic `bytes` { #pydantic-bytes }\n\nYou can declare a Pydantic model with `bytes` fields, and then use `val_json_bytes` in the model config to tell it to use base64 to *validate* input JSON data, as part of that validation it will decode the base64 string into bytes.\n\n{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}\n\nIf you check the `/docs`, they will show that the field `data` expects base64 encoded bytes:\n\n
\n\n
\n\nYou could send a request like:\n\n```json\n{\n \"description\": \"Some data\",\n \"data\": \"aGVsbG8=\"\n}\n```\n\n/// tip\n\n`aGVsbG8=` is the base64 encoding of `hello`.\n\n///\n\nAnd then Pydantic will decode the base64 string and give you the original bytes in the `data` field of the model.\n\nYou will receive a response like:\n\n```json\n{\n \"description\": \"Some data\",\n \"content\": \"hello\"\n}\n```", "source_type": "doc", "path": "docs/en/docs/advanced/json-base64-bytes.md", "symbol": "Pydantic `bytes` { #pydantic-bytes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/json-base64-bytes.md#L15-L52", "start_line": 15, "end_line": 52} {"id": "docs/en/docs/advanced/json-base64-bytes.md::Pydantic `bytes` for Output Data { #pydantic-bytes-for-output-data }::L53", "text": "# Doc: docs/en/docs/advanced/json-base64-bytes.md | Page: JSON with Bytes as Base64 { #json-with-bytes-as-base64 } | Section: Pydantic `bytes` for Output Data { #pydantic-bytes-for-output-data }\n## Pydantic `bytes` for Output Data { #pydantic-bytes-for-output-data }\n\nYou can also use `bytes` fields with `ser_json_bytes` in the model config for output data, and Pydantic will *serialize* the bytes as base64 when generating the JSON response.\n\n{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:2,12:16,29,38:41] hl[16] *}", "source_type": "doc", "path": "docs/en/docs/advanced/json-base64-bytes.md", "symbol": "Pydantic `bytes` for Output Data { #pydantic-bytes-for-output-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/json-base64-bytes.md#L53-L58", "start_line": 53, "end_line": 58} {"id": "docs/en/docs/advanced/json-base64-bytes.md::Pydantic `bytes` for Input and Output Data { #pydantic-bytes-for-input-and-output-data }::L59", "text": "# Doc: docs/en/docs/advanced/json-base64-bytes.md | Page: JSON with Bytes as Base64 { #json-with-bytes-as-base64 } | Section: Pydantic `bytes` for Input and Output Data { #pydantic-bytes-for-input-and-output-data }\n## Pydantic `bytes` for Input and Output Data { #pydantic-bytes-for-input-and-output-data }\n\nAnd of course, you can use the same model configured to use base64 to handle both input (*validate*) with `val_json_bytes` and output (*serialize*) with `ser_json_bytes` when receiving and sending JSON data.\n\n{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:2,19:26,29,44:46] hl[23:26] *}", "source_type": "doc", "path": "docs/en/docs/advanced/json-base64-bytes.md", "symbol": "Pydantic `bytes` for Input and Output Data { #pydantic-bytes-for-input-and-output-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/json-base64-bytes.md#L59-L63", "start_line": 59, "end_line": 63} {"id": "docs/en/docs/advanced/middleware.md::Advanced Middleware { #advanced-middleware }::L1", "text": "# Doc: docs/en/docs/advanced/middleware.md | Page: Advanced Middleware { #advanced-middleware } | Section: Advanced Middleware { #advanced-middleware }\n# Advanced Middleware { #advanced-middleware }\n\nIn the main tutorial you read how to add [Custom Middleware](../tutorial/middleware.md) to your application.\n\nAnd then you also read how to handle [CORS with the `CORSMiddleware`](../tutorial/cors.md).\n\nIn this section we'll see how to use other middlewares.", "source_type": "doc", "path": "docs/en/docs/advanced/middleware.md", "symbol": "Advanced Middleware { #advanced-middleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/middleware.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/advanced/middleware.md::Adding ASGI middlewares { #adding-asgi-middlewares }::L9", "text": "# Doc: docs/en/docs/advanced/middleware.md | Page: Advanced Middleware { #advanced-middleware } | Section: Adding ASGI middlewares { #adding-asgi-middlewares }\n## Adding ASGI middlewares { #adding-asgi-middlewares }\n\nAs **FastAPI** is based on Starlette and implements the ASGI specification, you can use any ASGI middleware.\n\nA middleware doesn't have to be made for FastAPI or Starlette to work, as long as it follows the ASGI spec.\n\nIn general, ASGI middlewares are classes that expect to receive an ASGI app as the first argument.\n\nSo, in the documentation for third-party ASGI middlewares they will probably tell you to do something like:\n\n```Python\nfrom unicorn import UnicornMiddleware\n\napp = SomeASGIApp()\n\nnew_app = UnicornMiddleware(app, some_config=\"rainbow\")\n```\n\nBut FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares handle server errors and custom exception handlers work properly.\n\nFor that, you use `app.add_middleware()` (as in the example for CORS).\n\n```Python\nfrom fastapi import FastAPI\nfrom unicorn import UnicornMiddleware\n\napp = FastAPI()\n\napp.add_middleware(UnicornMiddleware, some_config=\"rainbow\")\n```\n\n`app.add_middleware()` receives a middleware class as the first argument and any additional arguments to be passed to the middleware.", "source_type": "doc", "path": "docs/en/docs/advanced/middleware.md", "symbol": "Adding ASGI middlewares { #adding-asgi-middlewares }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/middleware.md#L9-L41", "start_line": 9, "end_line": 41} {"id": "docs/en/docs/advanced/middleware.md::Integrated middlewares { #integrated-middlewares }::L42", "text": "# Doc: docs/en/docs/advanced/middleware.md | Page: Advanced Middleware { #advanced-middleware } | Section: Integrated middlewares { #integrated-middlewares }\n## Integrated middlewares { #integrated-middlewares }\n\n**FastAPI** includes several middlewares for common use cases, we'll see next how to use them.\n\n/// note | Technical Details\n\nFor the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`.\n\n**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/middleware.md", "symbol": "Integrated middlewares { #integrated-middlewares }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/middleware.md#L42-L53", "start_line": 42, "end_line": 53} {"id": "docs/en/docs/advanced/middleware.md::`HTTPSRedirectMiddleware` { #httpsredirectmiddleware }::L54", "text": "# Doc: docs/en/docs/advanced/middleware.md | Page: Advanced Middleware { #advanced-middleware } | Section: `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }\n## `HTTPSRedirectMiddleware` { #httpsredirectmiddleware }\n\nEnforces that all incoming requests must either be `https` or `wss`.\n\nAny incoming request to `http` or `ws` will be redirected to the secure scheme instead.\n\n{* ../../docs_src/advanced_middleware/tutorial001_py310.py hl[2,6] *}", "source_type": "doc", "path": "docs/en/docs/advanced/middleware.md", "symbol": "`HTTPSRedirectMiddleware` { #httpsredirectmiddleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/middleware.md#L54-L61", "start_line": 54, "end_line": 61} {"id": "docs/en/docs/advanced/middleware.md::`TrustedHostMiddleware` { #trustedhostmiddleware }::L62", "text": "# Doc: docs/en/docs/advanced/middleware.md | Page: Advanced Middleware { #advanced-middleware } | Section: `TrustedHostMiddleware` { #trustedhostmiddleware }\n## `TrustedHostMiddleware` { #trustedhostmiddleware }\n\nEnforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks.\n\n{* ../../docs_src/advanced_middleware/tutorial002_py310.py hl[2,6:8] *}\n\nThe following arguments are supported:\n\n* `allowed_hosts` - A list of domain names that should be allowed as hostnames. Wildcard domains such as `*.example.com` are supported for matching subdomains. To allow any hostname either use `allowed_hosts=[\"*\"]` or omit the middleware.\n* `www_redirect` - If set to True, requests to non-www versions of the allowed hosts will be redirected to their www counterparts. Defaults to `True`.\n\nIf an incoming request does not validate correctly then a `400` response will be sent.", "source_type": "doc", "path": "docs/en/docs/advanced/middleware.md", "symbol": "`TrustedHostMiddleware` { #trustedhostmiddleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/middleware.md#L62-L74", "start_line": 62, "end_line": 74} {"id": "docs/en/docs/advanced/middleware.md::`GZipMiddleware` { #gzipmiddleware }::L75", "text": "# Doc: docs/en/docs/advanced/middleware.md | Page: Advanced Middleware { #advanced-middleware } | Section: `GZipMiddleware` { #gzipmiddleware }\n## `GZipMiddleware` { #gzipmiddleware }\n\nHandles GZip responses for any request that includes `\"gzip\"` in the `Accept-Encoding` header.\n\nThe middleware will handle both standard and streaming responses.\n\n{* ../../docs_src/advanced_middleware/tutorial003_py310.py hl[2,6] *}\n\nThe following arguments are supported:\n\n* `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`.\n* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes.", "source_type": "doc", "path": "docs/en/docs/advanced/middleware.md", "symbol": "`GZipMiddleware` { #gzipmiddleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/middleware.md#L75-L87", "start_line": 75, "end_line": 87} {"id": "docs/en/docs/advanced/middleware.md::Other middlewares { #other-middlewares }::L88", "text": "# Doc: docs/en/docs/advanced/middleware.md | Page: Advanced Middleware { #advanced-middleware } | Section: Other middlewares { #other-middlewares }\n## Other middlewares { #other-middlewares }\n\nThere are many other ASGI middlewares.\n\nFor example:\n\n* [Uvicorn's `ProxyHeadersMiddleware`](https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py)\n* [MessagePack](https://github.com/florimondmanca/msgpack-asgi)\n\nTo see other available middlewares check [Starlette's Middleware docs](https://www.starlette.dev/middleware/) and the [ASGI Awesome List](https://github.com/florimondmanca/awesome-asgi).", "source_type": "doc", "path": "docs/en/docs/advanced/middleware.md", "symbol": "Other middlewares { #other-middlewares }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/middleware.md#L88-L97", "start_line": 88, "end_line": 97} {"id": "docs/en/docs/advanced/openapi-callbacks.md::OpenAPI Callbacks { #openapi-callbacks }::L1", "text": "# Doc: docs/en/docs/advanced/openapi-callbacks.md | Page: OpenAPI Callbacks { #openapi-callbacks } | Section: OpenAPI Callbacks { #openapi-callbacks }\n# OpenAPI Callbacks { #openapi-callbacks }\n\nYou could create an API with a *path operation* that could trigger a request to an *external API* created by someone else (probably the same developer that would be *using* your API).\n\nThe process that happens when your API app calls the *external API* is named a \"callback\". Because the software that the external developer wrote sends a request to your API and then your API *calls back*, sending a request to an *external API* (that was probably created by the same developer).\n\nIn this case, you could want to document how that external API *should* look. What *path operation* it should have, what body it should expect, what response it should return, etc.", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-callbacks.md", "symbol": "OpenAPI Callbacks { #openapi-callbacks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-callbacks.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/advanced/openapi-callbacks.md::An app with callbacks { #an-app-with-callbacks }::L9", "text": "# Doc: docs/en/docs/advanced/openapi-callbacks.md | Page: OpenAPI Callbacks { #openapi-callbacks } | Section: An app with callbacks { #an-app-with-callbacks }\n## An app with callbacks { #an-app-with-callbacks }\n\nLet's see all this with an example.\n\nImagine you develop an app that allows creating invoices.\n\nThese invoices will have an `id`, `title` (optional), `customer`, and `total`.\n\nThe user of your API (an external developer) will create an invoice in your API with a POST request.\n\nThen your API will (let's imagine):\n\n* Send the invoice to some customer of the external developer.\n* Collect the money.\n* Send a notification back to the API user (the external developer).\n * This will be done by sending a POST request (from *your API*) to some *external API* provided by that external developer (this is the \"callback\").", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-callbacks.md", "symbol": "An app with callbacks { #an-app-with-callbacks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-callbacks.md#L9-L25", "start_line": 9, "end_line": 25} {"id": "docs/en/docs/advanced/openapi-callbacks.md::The normal **FastAPI** app { #the-normal-fastapi-app }::L26", "text": "# Doc: docs/en/docs/advanced/openapi-callbacks.md | Page: OpenAPI Callbacks { #openapi-callbacks } | Section: The normal **FastAPI** app { #the-normal-fastapi-app }\n## The normal **FastAPI** app { #the-normal-fastapi-app }\n\nLet's first see how the normal API app would look before adding the callback.\n\nIt will have a *path operation* that will receive an `Invoice` body, and a query parameter `callback_url` that will contain the URL for the callback.\n\nThis part is pretty normal, most of the code is probably already familiar to you:\n\n{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}\n\n/// tip\n\nThe `callback_url` query parameter uses a Pydantic [Url](https://docs.pydantic.dev/latest/api/networks/) type.\n\n///\n\nThe only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next.", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-callbacks.md", "symbol": "The normal **FastAPI** app { #the-normal-fastapi-app }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-callbacks.md#L26-L43", "start_line": 26, "end_line": 43} {"id": "docs/en/docs/advanced/openapi-callbacks.md::Documenting the callback { #documenting-the-callback }::L44", "text": "# Doc: docs/en/docs/advanced/openapi-callbacks.md | Page: OpenAPI Callbacks { #openapi-callbacks } | Section: Documenting the callback { #documenting-the-callback }\n## Documenting the callback { #documenting-the-callback }\n\nThe actual callback code will depend heavily on your own API app.\n\nAnd it will probably vary a lot from one app to the next.\n\nIt could be just one or two lines of code, like:\n\n```Python\ncallback_url = \"https://example.com/api/v1/invoices/events/\"\nhttpx.post(callback_url, json={\"description\": \"Invoice paid\", \"paid\": True})\n```\n\nBut possibly the most important part of the callback is making sure that your API user (the external developer) implements the *external API* correctly, according to the data that *your API* is going to send in the request body of the callback, etc.\n\nSo, what we will do next is add the code to document how that *external API* should look to receive the callback from *your API*.\n\nThat documentation will show up in the Swagger UI at `/docs` in your API, and it will let external developers know how to build the *external API*.\n\nThis example doesn't implement the callback itself (that could be just a line of code), only the documentation part.\n\n/// tip\n\nThe actual callback is just an HTTP request.\n\nWhen implementing the callback yourself, you could use something like [HTTPX](https://www.python-httpx.org) or [Requests](https://requests.readthedocs.io/).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-callbacks.md", "symbol": "Documenting the callback { #documenting-the-callback }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-callbacks.md#L44-L72", "start_line": 44, "end_line": 72} {"id": "docs/en/docs/advanced/openapi-callbacks.md::Write the callback documentation code { #write-the-callback-documentation-code }::L73", "text": "# Doc: docs/en/docs/advanced/openapi-callbacks.md | Page: OpenAPI Callbacks { #openapi-callbacks } | Section: Write the callback documentation code { #write-the-callback-documentation-code }\n## Write the callback documentation code { #write-the-callback-documentation-code }\n\nThis code won't be executed in your app, we only need it to *document* how that *external API* should look.\n\nBut, you already know how to easily create automatic documentation for an API with **FastAPI**.\n\nSo we are going to use that same knowledge to document how the *external API* should look... by creating the *path operation(s)* that the external API should implement (the ones your API will call).\n\n/// tip\n\nWhen writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*.\n\nTemporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*.\n\n///\n\n### Create a callback `APIRouter` { #create-a-callback-apirouter }\n\nFirst create a new `APIRouter` that will contain one or more callbacks.\n\n{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}\n\n### Create the callback *path operation* { #create-the-callback-path-operation }\n\nTo create the callback *path operation* use the same `APIRouter` you created above.\n\nIt should look just like a normal FastAPI *path operation*:\n\n* It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`.\n* And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`.\n\n{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}\n\nThere are 2 main differences from a normal *path operation*:\n\n* It doesn't need to have any actual code, because your app will never call this code. It's only used to document the *external API*. So, the function could just have `pass`.\n* The *path* can contain an [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression) (see more below) where it can use variables with parameters and parts of the original request sent to *your API*.\n\n### The callback path expression { #the-callback-path-expression }\n\nThe callback *path* can have an [OpenAPI 3 expression](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression) that can contain parts of the original request sent to *your API*.\n\nIn this case, it's the `str`:\n\n```Python\n\"{$callback_url}/invoices/{$request.body.id}\"\n```\n\nSo, if your API user (the external developer) sends a request to *your API* to:\n\n```\nhttps://yourapi.com/invoices/?callback_url=https://www.external.org/events\n```\n\nwith a JSON body of:\n\n```JSON\n{\n \"id\": \"2expen51ve\",\n \"customer\": \"Mr. Richie Rich\",\n \"total\": \"9999\"\n}\n```\n\nthen *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*):\n\n```\nhttps://www.external.org/events/invoices/2expen51ve\n```\n\nwith a JSON body containing something like:\n\n```JSON\n{\n \"description\": \"Payment celebration\",\n \"paid\": true\n}\n```\n\nand it would expect a response from that *external API* with a JSON body like:\n\n```JSON\n{\n \"ok\": true\n}\n```\n\n/// tip\n\nNotice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`).\n\n///\n\n### Add the callback router { #add-the-callback-router }\n\nAt this point you have the *callback path operation(s)* needed (the one(s) that the *external developer* should implement in the *external API*) in the callback router you created above.\n\nNow use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` from that callback router:\n\n{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}\n\n/// tip\n\nNotice that you are not passing the router itself (`invoices_callback_router`) to `callbacks=`, but its `.routes`, as in `invoices_callback_router.routes`. FastAPI will use those routes to generate the callback OpenAPI documentation.\n\n///\n\n### Check the docs { #check-the-docs }\n\nNow you can start your app and go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see your docs including a \"Callbacks\" section for your *path operation* that shows how the *external API* should look:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-callbacks.md", "symbol": "Write the callback documentation code { #write-the-callback-documentation-code }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-callbacks.md#L73-L186", "start_line": 73, "end_line": 186} {"id": "docs/en/docs/advanced/openapi-webhooks.md::OpenAPI Webhooks { #openapi-webhooks }::L1", "text": "# Doc: docs/en/docs/advanced/openapi-webhooks.md | Page: OpenAPI Webhooks { #openapi-webhooks } | Section: OpenAPI Webhooks { #openapi-webhooks }\n# OpenAPI Webhooks { #openapi-webhooks }\n\nThere are cases where you want to tell your API **users** that your app could call *their* app (sending a request) with some data, normally to **notify** of some type of **event**.\n\nThis means that instead of the normal process of your users sending requests to your API, it's **your API** (or your app) that could **send requests to their system** (to their API, their app).\n\nThis is normally called a **webhook**.", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-webhooks.md", "symbol": "OpenAPI Webhooks { #openapi-webhooks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-webhooks.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/advanced/openapi-webhooks.md::Webhooks steps { #webhooks-steps }::L9", "text": "# Doc: docs/en/docs/advanced/openapi-webhooks.md | Page: OpenAPI Webhooks { #openapi-webhooks } | Section: Webhooks steps { #webhooks-steps }\n## Webhooks steps { #webhooks-steps }\n\nThe process normally is that **you define** in your code what is the message that you will send, the **body of the request**.\n\nYou also define in some way at which **moments** your app will send those requests or events.\n\nAnd **your users** define in some way (for example in a web dashboard somewhere) the **URL** where your app should send those requests.\n\nAll the **logic** about how to register the URLs for webhooks and the code to actually send those requests is up to you. You write it however you want to in **your own code**.", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-webhooks.md", "symbol": "Webhooks steps { #webhooks-steps }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-webhooks.md#L9-L18", "start_line": 9, "end_line": 18} {"id": "docs/en/docs/advanced/openapi-webhooks.md::Documenting webhooks with **FastAPI** and OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }::L19", "text": "# Doc: docs/en/docs/advanced/openapi-webhooks.md | Page: OpenAPI Webhooks { #openapi-webhooks } | Section: Documenting webhooks with **FastAPI** and OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }\n## Documenting webhooks with **FastAPI** and OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }\n\nWith **FastAPI**, using OpenAPI, you can define the names of these webhooks, the types of HTTP operations that your app can send (e.g. `POST`, `PUT`, etc.) and the request **bodies** that your app would send.\n\nThis can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code.\n\n/// note\n\nWebhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-webhooks.md", "symbol": "Documenting webhooks with **FastAPI** and OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-webhooks.md#L19-L30", "start_line": 19, "end_line": 30} {"id": "docs/en/docs/advanced/openapi-webhooks.md::An app with webhooks { #an-app-with-webhooks }::L31", "text": "# Doc: docs/en/docs/advanced/openapi-webhooks.md | Page: OpenAPI Webhooks { #openapi-webhooks } | Section: An app with webhooks { #an-app-with-webhooks }\n## An app with webhooks { #an-app-with-webhooks }\n\nWhen you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`.\n\n{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}\n\nThe webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**.\n\n/// note\n\nThe `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.\n\n///\n\nNotice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post(\"new-subscription\")`, the webhook name is `new-subscription`.\n\nThis is because it is expected that **your users** would define the actual **URL path** where they want to receive the webhook request in some other way (e.g. a web dashboard).\n\n### Check the docs { #check-the-docs }\n\nNow you can start your app and go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see your docs have the normal *path operations* and now also some **webhooks**:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/openapi-webhooks.md", "symbol": "An app with webhooks { #an-app-with-webhooks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/openapi-webhooks.md#L31-L55", "start_line": 31, "end_line": 55} {"id": "docs/en/docs/advanced/path-operation-advanced-configuration.md::Path Operation Advanced Configuration { #path-operation-advanced-configuration }::L1", "text": "# Doc: docs/en/docs/advanced/path-operation-advanced-configuration.md | Page: Path Operation Advanced Configuration { #path-operation-advanced-configuration } | Section: Path Operation Advanced Configuration { #path-operation-advanced-configuration }\n# Path Operation Advanced Configuration { #path-operation-advanced-configuration }", "source_type": "doc", "path": "docs/en/docs/advanced/path-operation-advanced-configuration.md", "symbol": "Path Operation Advanced Configuration { #path-operation-advanced-configuration }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/path-operation-advanced-configuration.md#L1-L2", "start_line": 1, "end_line": 2} {"id": "docs/en/docs/advanced/path-operation-advanced-configuration.md::OpenAPI operationId { #openapi-operationid }::L3", "text": "# Doc: docs/en/docs/advanced/path-operation-advanced-configuration.md | Page: Path Operation Advanced Configuration { #path-operation-advanced-configuration } | Section: OpenAPI operationId { #openapi-operationid }\n## OpenAPI operationId { #openapi-operationid }\n\n/// warning\n\nIf you are not an \"expert\" in OpenAPI, you probably don't need this.\n\n///\n\nYou can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`.\n\nYou would have to make sure that it is unique for each operation.\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}\n\n### Using the *path operation function* name as the operationId { #using-the-path-operation-function-name-as-the-operationid }\n\nIf you want to use your APIs' function names as `operationId`s, you can pass a custom `generate_unique_id_function` to `FastAPI`.\n\nThe function receives each `APIRoute` and returns the `operationId` to use for that path operation.\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2,5:6,9] *}\n\n/// warning\n\nIf you do this, you have to make sure each one of your *path operation functions* has a unique name.\n\nEven if they are in different modules (Python files).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/path-operation-advanced-configuration.md", "symbol": "OpenAPI operationId { #openapi-operationid }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/path-operation-advanced-configuration.md#L3-L32", "start_line": 3, "end_line": 32} {"id": "docs/en/docs/advanced/path-operation-advanced-configuration.md::Exclude from OpenAPI { #exclude-from-openapi }::L33", "text": "# Doc: docs/en/docs/advanced/path-operation-advanced-configuration.md | Page: Path Operation Advanced Configuration { #path-operation-advanced-configuration } | Section: Exclude from OpenAPI { #exclude-from-openapi }\n## Exclude from OpenAPI { #exclude-from-openapi }\n\nTo exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`:\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}", "source_type": "doc", "path": "docs/en/docs/advanced/path-operation-advanced-configuration.md", "symbol": "Exclude from OpenAPI { #exclude-from-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/path-operation-advanced-configuration.md#L33-L38", "start_line": 33, "end_line": 38} {"id": "docs/en/docs/advanced/path-operation-advanced-configuration.md::Advanced description from docstring { #advanced-description-from-docstring }::L39", "text": "# Doc: docs/en/docs/advanced/path-operation-advanced-configuration.md | Page: Path Operation Advanced Configuration { #path-operation-advanced-configuration } | Section: Advanced description from docstring { #advanced-description-from-docstring }\n## Advanced description from docstring { #advanced-description-from-docstring }\n\nYou can limit the lines used from the docstring of a *path operation function* for OpenAPI.\n\nAdding an `\\f` (an escaped \"form feed\" character) causes **FastAPI** to truncate the output used for OpenAPI at this point.\n\nIt won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest.\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}", "source_type": "doc", "path": "docs/en/docs/advanced/path-operation-advanced-configuration.md", "symbol": "Advanced description from docstring { #advanced-description-from-docstring }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/path-operation-advanced-configuration.md#L39-L48", "start_line": 39, "end_line": 48} {"id": "docs/en/docs/advanced/path-operation-advanced-configuration.md::Additional Responses { #additional-responses }::L49", "text": "# Doc: docs/en/docs/advanced/path-operation-advanced-configuration.md | Page: Path Operation Advanced Configuration { #path-operation-advanced-configuration } | Section: Additional Responses { #additional-responses }\n## Additional Responses { #additional-responses }\n\nYou probably have seen how to declare the `response_model` and `status_code` for a *path operation*.\n\nThat defines the metadata about the main response of a *path operation*.\n\nYou can also declare additional responses with their models, status codes, etc.\n\nThere's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md).", "source_type": "doc", "path": "docs/en/docs/advanced/path-operation-advanced-configuration.md", "symbol": "Additional Responses { #additional-responses }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/path-operation-advanced-configuration.md#L49-L58", "start_line": 49, "end_line": 58} {"id": "docs/en/docs/advanced/path-operation-advanced-configuration.md::OpenAPI Extra { #openapi-extra }::L59", "text": "# Doc: docs/en/docs/advanced/path-operation-advanced-configuration.md | Page: Path Operation Advanced Configuration { #path-operation-advanced-configuration } | Section: OpenAPI Extra { #openapi-extra }\n## OpenAPI Extra { #openapi-extra }\n\nWhen you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema.\n\n/// note | Technical details\n\nIn the OpenAPI specification it is called the [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object).\n\n///\n\nIt has all the information about the *path operation* and is used to generate the automatic documentation.\n\nIt includes the `tags`, `parameters`, `requestBody`, `responses`, etc.\n\nThis *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it.\n\n/// tip\n\nThis is a low level extension point.\n\nIf you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md).\n\n///\n\nYou can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`.\n\n### OpenAPI Extensions { #openapi-extensions }\n\nThis `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}\n\nIf you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*.\n\n\n\nAnd if you see the resulting OpenAPI (at `/openapi.json` in your API), you will see your extension as part of the specific *path operation* too:\n\n```JSON hl_lines=\"22\"\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"FastAPI\",\n \"version\": \"0.1.0\"\n },\n \"paths\": {\n \"/items/\": {\n \"get\": {\n \"summary\": \"Read Items\",\n \"operationId\": \"read_items_items__get\",\n \"responses\": {\n \"200\": {\n \"description\": \"Successful Response\",\n \"content\": {\n \"application/json\": {\n \"schema\": {}\n }\n }\n }\n },\n \"x-aperture-labs-portal\": \"blue\"\n }\n }\n }\n}\n```\n\n### Custom OpenAPI *path operation* schema { #custom-openapi-path-operation-schema }\n\nThe dictionary in `openapi_extra` will be deeply merged with the automatically generated OpenAPI schema for the *path operation*.\n\nSo, you could add additional data to the automatically generated schema.\n\nFor example, you could decide to read and validate the request with your own code, without using the automatic features of FastAPI with Pydantic, but you could still want to define the request in the OpenAPI schema.\n\nYou could do that with `openapi_extra`:\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}\n\nIn this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way.\n\nNevertheless, we can declare the expected schema for the request body.\n\n### Custom OpenAPI content type { #custom-openapi-content-type }\n\nUsing this same trick, you could use a Pydantic model to define the JSON Schema that is then included in the custom OpenAPI schema section for the *path operation*.\n\nAnd you could do this even if the data type in the request is not JSON.\n\nFor example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON:\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}\n\nNevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML.\n\nThen we use the request directly, and extract the body as `bytes`. This means that FastAPI won't even try to parse the request payload as JSON.\n\nAnd then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content:\n\n{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}\n\n/// tip\n\nHere we reuse the same Pydantic model.\n\nBut the same way, we could have validated it in some other way.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/path-operation-advanced-configuration.md", "symbol": "OpenAPI Extra { #openapi-extra }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/path-operation-advanced-configuration.md#L59-L166", "start_line": 59, "end_line": 166} {"id": "docs/en/docs/advanced/response-change-status-code.md::Response - Change Status Code { #response-change-status-code }::L1", "text": "# Doc: docs/en/docs/advanced/response-change-status-code.md | Page: Response - Change Status Code { #response-change-status-code } | Section: Response - Change Status Code { #response-change-status-code }\n# Response - Change Status Code { #response-change-status-code }\n\nYou probably read before that you can set a default [Response Status Code](../tutorial/response-status-code.md).\n\nBut in some cases you need to return a different status code than the default.", "source_type": "doc", "path": "docs/en/docs/advanced/response-change-status-code.md", "symbol": "Response - Change Status Code { #response-change-status-code }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-change-status-code.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/advanced/response-change-status-code.md::Use case { #use-case }::L7", "text": "# Doc: docs/en/docs/advanced/response-change-status-code.md | Page: Response - Change Status Code { #response-change-status-code } | Section: Use case { #use-case }\n## Use case { #use-case }\n\nFor example, imagine that you want to return an HTTP status code of \"OK\" `200` by default.\n\nBut if the data didn't exist, you want to create it, and return an HTTP status code of \"CREATED\" `201`.\n\nBut you still want to be able to filter and convert the data you return with a `response_model`.\n\nFor those cases, you can use a `Response` parameter.", "source_type": "doc", "path": "docs/en/docs/advanced/response-change-status-code.md", "symbol": "Use case { #use-case }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-change-status-code.md#L7-L16", "start_line": 7, "end_line": 16} {"id": "docs/en/docs/advanced/response-change-status-code.md::Use a `Response` parameter { #use-a-response-parameter }::L17", "text": "# Doc: docs/en/docs/advanced/response-change-status-code.md | Page: Response - Change Status Code { #response-change-status-code } | Section: Use a `Response` parameter { #use-a-response-parameter }\n## Use a `Response` parameter { #use-a-response-parameter }\n\nYou can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies and headers).\n\nAnd then you can set the `status_code` in that *temporary* response object.\n\n{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}\n\nAnd then you can return any object you need, as you normally would (a `dict`, a database model, etc).\n\nAnd if you declared a `response_model`, it will still be used to filter and convert the object you returned.\n\n**FastAPI** will use that *temporary* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`.\n\nYou can also declare the `Response` parameter in dependencies, and set the status code in them. But keep in mind that the last one to be set will win.", "source_type": "doc", "path": "docs/en/docs/advanced/response-change-status-code.md", "symbol": "Use a `Response` parameter { #use-a-response-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-change-status-code.md#L17-L31", "start_line": 17, "end_line": 31} {"id": "docs/en/docs/advanced/response-cookies.md::Use a `Response` parameter { #use-a-response-parameter }::L3", "text": "# Doc: docs/en/docs/advanced/response-cookies.md | Page: Response Cookies { #response-cookies } | Section: Use a `Response` parameter { #use-a-response-parameter }\n## Use a `Response` parameter { #use-a-response-parameter }\n\nYou can declare a parameter of type `Response` in your *path operation function*.\n\nAnd then you can set cookies in that *temporary* response object.\n\n{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}\n\nAnd then you can return any object you need, as you normally would (a `dict`, a database model, etc).\n\nAnd if you declared a `response_model`, it will still be used to filter and convert the object you returned.\n\n**FastAPI** will use that *temporary* response to extract the cookies (also headers and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.\n\nYou can also declare the `Response` parameter in dependencies, and set cookies (and headers) in them.", "source_type": "doc", "path": "docs/en/docs/advanced/response-cookies.md", "symbol": "Use a `Response` parameter { #use-a-response-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-cookies.md#L3-L18", "start_line": 3, "end_line": 18} {"id": "docs/en/docs/advanced/response-cookies.md::Return a `Response` directly { #return-a-response-directly }::L19", "text": "# Doc: docs/en/docs/advanced/response-cookies.md | Page: Response Cookies { #response-cookies } | Section: Return a `Response` directly { #return-a-response-directly }\n## Return a `Response` directly { #return-a-response-directly }\n\nYou can also create cookies when returning a `Response` directly in your code.\n\nTo do that, you can create a response as described in [Return a Response Directly](response-directly.md).\n\nThen set Cookies in it, and then return it:\n\n{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}\n\n/// tip\n\nKeep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.\n\nSo, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.\n\nAnd also that you are not sending any data that should have been filtered by a `response_model`.\n\n///\n\n### More info { #more-info }\n\n/// note | Technical Details\n\nYou could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.\n\nAnd as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.\n\n///\n\nTo see all the available parameters and options, check the [documentation in Starlette](https://www.starlette.dev/responses/#set-cookie).", "source_type": "doc", "path": "docs/en/docs/advanced/response-cookies.md", "symbol": "Return a `Response` directly { #return-a-response-directly }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-cookies.md#L19-L51", "start_line": 19, "end_line": 51} {"id": "docs/en/docs/advanced/response-directly.md::Return a Response Directly { #return-a-response-directly }::L1", "text": "# Doc: docs/en/docs/advanced/response-directly.md | Page: Return a Response Directly { #return-a-response-directly } | Section: Return a Response Directly { #return-a-response-directly }\n# Return a Response Directly { #return-a-response-directly }\n\nWhen you create a **FastAPI** *path operation* you can normally return any data from it: a `dict`, a `list`, a Pydantic model, a database model, etc.\n\nIf you declare a [Response Model](../tutorial/response-model.md) FastAPI will use it to serialize the data to JSON, using Pydantic.\n\nIf you don't declare a response model, FastAPI will use the `jsonable_encoder` explained in [JSON Compatible Encoder](../tutorial/encoder.md) and put it in a `JSONResponse`.\n\nYou could also create a `JSONResponse` directly and return it.\n\n/// tip\n\nYou will normally have much better performance using a [Response Model](../tutorial/response-model.md) than returning a `JSONResponse` directly, as that way it serializes the data using Pydantic, in Rust.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/response-directly.md", "symbol": "Return a Response Directly { #return-a-response-directly }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-directly.md#L1-L16", "start_line": 1, "end_line": 16} {"id": "docs/en/docs/advanced/response-directly.md::Return a `Response` { #return-a-response }::L17", "text": "# Doc: docs/en/docs/advanced/response-directly.md | Page: Return a Response Directly { #return-a-response-directly } | Section: Return a `Response` { #return-a-response }\n## Return a `Response` { #return-a-response }\n\nYou can return a `Response` or any sub-class of it.\n\n/// note\n\n`JSONResponse` itself is a sub-class of `Response`.\n\n///\n\nAnd when you return a `Response`, **FastAPI** will pass it directly.\n\nIt won't do any data conversion with Pydantic models, it won't convert the contents to any type, etc.\n\nThis gives you a lot of **flexibility**. You can return any data type, override any data declaration or validation, etc.\n\nIt also gives you a lot of **responsibility**. You have to make sure that the data you return is correct, in the correct format, that it can be serialized, etc.", "source_type": "doc", "path": "docs/en/docs/advanced/response-directly.md", "symbol": "Return a `Response` { #return-a-response }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-directly.md#L17-L34", "start_line": 17, "end_line": 34} {"id": "docs/en/docs/advanced/response-directly.md::Using the `jsonable_encoder` in a `Response` { #using-the-jsonable-encoder-in-a-response }::L35", "text": "# Doc: docs/en/docs/advanced/response-directly.md | Page: Return a Response Directly { #return-a-response-directly } | Section: Using the `jsonable_encoder` in a `Response` { #using-the-jsonable-encoder-in-a-response }\n## Using the `jsonable_encoder` in a `Response` { #using-the-jsonable-encoder-in-a-response }\n\nBecause **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it.\n\nFor example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types.\n\nFor those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response:\n\n{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}\n\n/// note | Technical Details\n\nYou could also use `from starlette.responses import JSONResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/response-directly.md", "symbol": "Using the `jsonable_encoder` in a `Response` { #using-the-jsonable-encoder-in-a-response }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-directly.md#L35-L52", "start_line": 35, "end_line": 52} {"id": "docs/en/docs/advanced/response-directly.md::Returning a custom `Response` { #returning-a-custom-response }::L53", "text": "# Doc: docs/en/docs/advanced/response-directly.md | Page: Return a Response Directly { #return-a-response-directly } | Section: Returning a custom `Response` { #returning-a-custom-response }\n## Returning a custom `Response` { #returning-a-custom-response }\n\nThe example above shows all the parts you need, but it's not very useful yet, as you could have just returned the `item` directly, and **FastAPI** would put it in a `JSONResponse` for you, converting it to a `dict`, etc. All that by default.\n\nNow, let's see how you could use that to return a custom response.\n\nLet's say that you want to return an [XML](https://en.wikipedia.org/wiki/XML) response.\n\nYou could put your XML content in a string, put that in a `Response`, and return it:\n\n{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}", "source_type": "doc", "path": "docs/en/docs/advanced/response-directly.md", "symbol": "Returning a custom `Response` { #returning-a-custom-response }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-directly.md#L53-L64", "start_line": 53, "end_line": 64} {"id": "docs/en/docs/advanced/response-directly.md::How a Response Model Works { #how-a-response-model-works }::L65", "text": "# Doc: docs/en/docs/advanced/response-directly.md | Page: Return a Response Directly { #return-a-response-directly } | Section: How a Response Model Works { #how-a-response-model-works }\n## How a Response Model Works { #how-a-response-model-works }\n\nWhen you declare a [Response Model - Return Type](../tutorial/response-model.md) in a path operation, **FastAPI** will use it to serialize the data to JSON, using Pydantic.\n\n{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}\n\nAs that will happen on the Rust side, the performance will be much better than if it was done with regular Python and the `JSONResponse` class.\n\nWhen using a `response_model` or return type, FastAPI won't use the `jsonable_encoder` to convert the data (which would be slower) nor the `JSONResponse` class.\n\nInstead it takes the JSON bytes generated with Pydantic using the response model (or return type) and returns a `Response` with the right media type for JSON directly (`application/json`).", "source_type": "doc", "path": "docs/en/docs/advanced/response-directly.md", "symbol": "How a Response Model Works { #how-a-response-model-works }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-directly.md#L65-L76", "start_line": 65, "end_line": 76} {"id": "docs/en/docs/advanced/response-directly.md::Notes { #notes }::L77", "text": "# Doc: docs/en/docs/advanced/response-directly.md | Page: Return a Response Directly { #return-a-response-directly } | Section: Notes { #notes }\n## Notes { #notes }\n\nWhen you return a `Response` directly its data is not validated, converted (serialized), or documented automatically.\n\nBut you can still document it as described in [Additional Responses in OpenAPI](additional-responses.md).\n\nYou can see in later sections how to use/declare these custom `Response`s while still having automatic data conversion, documentation, etc.", "source_type": "doc", "path": "docs/en/docs/advanced/response-directly.md", "symbol": "Notes { #notes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-directly.md#L77-L83", "start_line": 77, "end_line": 83} {"id": "docs/en/docs/advanced/response-headers.md::Use a `Response` parameter { #use-a-response-parameter }::L3", "text": "# Doc: docs/en/docs/advanced/response-headers.md | Page: Response Headers { #response-headers } | Section: Use a `Response` parameter { #use-a-response-parameter }\n## Use a `Response` parameter { #use-a-response-parameter }\n\nYou can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies).\n\nAnd then you can set headers in that *temporary* response object.\n\n{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}\n\nAnd then you can return any object you need, as you normally would (a `dict`, a database model, etc).\n\nAnd if you declared a `response_model`, it will still be used to filter and convert the object you returned.\n\n**FastAPI** will use that *temporary* response to extract the headers (also cookies and status code), and will put them in the final response that contains the value you returned, filtered by any `response_model`.\n\nYou can also declare the `Response` parameter in dependencies, and set headers (and cookies) in them.", "source_type": "doc", "path": "docs/en/docs/advanced/response-headers.md", "symbol": "Use a `Response` parameter { #use-a-response-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-headers.md#L3-L18", "start_line": 3, "end_line": 18} {"id": "docs/en/docs/advanced/response-headers.md::Return a `Response` directly { #return-a-response-directly }::L19", "text": "# Doc: docs/en/docs/advanced/response-headers.md | Page: Response Headers { #response-headers } | Section: Return a `Response` directly { #return-a-response-directly }\n## Return a `Response` directly { #return-a-response-directly }\n\nYou can also add headers when you return a `Response` directly.\n\nCreate a response as described in [Return a Response Directly](response-directly.md) and pass the headers as an additional parameter:\n\n{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}\n\n/// note | Technical Details\n\nYou could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.\n\nAnd as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/response-headers.md", "symbol": "Return a `Response` directly { #return-a-response-directly }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-headers.md#L19-L36", "start_line": 19, "end_line": 36} {"id": "docs/en/docs/advanced/response-headers.md::Custom Headers { #custom-headers }::L37", "text": "# Doc: docs/en/docs/advanced/response-headers.md | Page: Response Headers { #response-headers } | Section: Custom Headers { #custom-headers }\n## Custom Headers { #custom-headers }\n\nKeep in mind that custom proprietary headers can be added [using the `X-` prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).\n\nBut if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), using the parameter `expose_headers` documented in [Starlette's CORS docs](https://www.starlette.dev/middleware/#corsmiddleware).", "source_type": "doc", "path": "docs/en/docs/advanced/response-headers.md", "symbol": "Custom Headers { #custom-headers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/response-headers.md#L37-L41", "start_line": 37, "end_line": 41} {"id": "docs/en/docs/advanced/security/http-basic-auth.md::HTTP Basic Auth { #http-basic-auth }::L1", "text": "# Doc: docs/en/docs/advanced/security/http-basic-auth.md | Page: HTTP Basic Auth { #http-basic-auth } | Section: HTTP Basic Auth { #http-basic-auth }\n# HTTP Basic Auth { #http-basic-auth }\n\nFor the simplest cases, you can use HTTP Basic Auth.\n\nIn HTTP Basic Auth, the application expects a header that contains a username and a password.\n\nIf it doesn't receive it, it returns an HTTP 401 \"Unauthorized\" error.\n\nAnd returns a header `WWW-Authenticate` with a value of `Basic`, and an optional `realm` parameter.\n\nThat tells the browser to show the integrated prompt for a username and password.\n\nThen, when you type that username and password, the browser sends them in the header automatically.", "source_type": "doc", "path": "docs/en/docs/advanced/security/http-basic-auth.md", "symbol": "HTTP Basic Auth { #http-basic-auth }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/http-basic-auth.md#L1-L14", "start_line": 1, "end_line": 14} {"id": "docs/en/docs/advanced/security/http-basic-auth.md::Simple HTTP Basic Auth { #simple-http-basic-auth }::L15", "text": "# Doc: docs/en/docs/advanced/security/http-basic-auth.md | Page: HTTP Basic Auth { #http-basic-auth } | Section: Simple HTTP Basic Auth { #simple-http-basic-auth }\n## Simple HTTP Basic Auth { #simple-http-basic-auth }\n\n* Import `HTTPBasic` and `HTTPBasicCredentials`.\n* Create a \"`security` scheme\" using `HTTPBasic`.\n* Use that `security` with a dependency in your *path operation*.\n* It returns an object of type `HTTPBasicCredentials`:\n * It contains the `username` and `password` sent.\n\n{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}\n\nWhen you try to open the URL for the first time (or click the \"Execute\" button in the docs) the browser will ask you for your username and password:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/security/http-basic-auth.md", "symbol": "Simple HTTP Basic Auth { #simple-http-basic-auth }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/http-basic-auth.md#L15-L28", "start_line": 15, "end_line": 28} {"id": "docs/en/docs/advanced/security/http-basic-auth.md::Check the username { #check-the-username }::L29", "text": "# Doc: docs/en/docs/advanced/security/http-basic-auth.md | Page: HTTP Basic Auth { #http-basic-auth } | Section: Check the username { #check-the-username }\n## Check the username { #check-the-username }\n\nHere's a more complete example.\n\nUse a dependency to check if the username and password are correct.\n\nFor this, use the Python standard module [`secrets`](https://docs.python.org/3/library/secrets.html) to check the username and password.\n\n`secrets.compare_digest()` needs to take `bytes` or a `str` that only contains ASCII characters (the ones in English), this means it wouldn't work with characters like `á`, as in `Sebastián`.\n\nTo handle that, we first convert the `username` and `password` to `bytes` encoding them with UTF-8.\n\nThen we can use `secrets.compare_digest()` to ensure that `credentials.username` is `\"stanleyjobson\"`, and that `credentials.password` is `\"swordfish\"`.\n\n{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}\n\nThis would be similar to:\n\n```Python\nif not (credentials.username == \"stanleyjobson\") or not (credentials.password == \"swordfish\"):\n # Return some error\n ...\n```\n\nBut by using the `secrets.compare_digest()` it will be secure against a type of attacks called \"timing attacks\".\n\n### Timing Attacks { #timing-attacks }\n\nBut what's a \"timing attack\"?\n\nLet's imagine some attackers are trying to guess the username and password.\n\nAnd they send a request with a username `johndoe` and a password `love123`.\n\nThen the Python code in your application would be equivalent to something like:\n\n```Python\nif \"johndoe\" == \"stanleyjobson\" and \"love123\" == \"swordfish\":\n ...\n```\n\nBut right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that \"there's no need to waste more computation comparing the rest of the letters\". And your application will say \"Incorrect username or password\".\n\nBut then the attackers try with username `stanleyjobsox` and password `love123`.\n\nAnd your application code does something like:\n\n```Python\nif \"stanleyjobsox\" == \"stanleyjobson\" and \"love123\" == \"swordfish\":\n ...\n```\n\nPython will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back \"Incorrect username or password\".\n\n#### The time to answer helps the attackers { #the-time-to-answer-helps-the-attackers }\n\nAt that point, by noticing that the server took some microseconds longer to send the \"Incorrect username or password\" response, the attackers will know that they got _something_ right, some of the initial letters were right.\n\nAnd then they can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`.\n\n#### A \"professional\" attack { #a-professional-attack }\n\nOf course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time.\n\nBut doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the \"help\" of our application, just using the time taken to answer.\n\n#### Fix it with `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }\n\nBut in our code we are actually using `secrets.compare_digest()`.\n\nIn short, it will take the same time to compare `stanleyjobsox` to `stanleyjobson` than it takes to compare `johndoe` to `stanleyjobson`. And the same for the password.\n\nThat way, using `secrets.compare_digest()` in your application code, it will be safe against this whole range of security attacks.\n\n### Return the error { #return-the-error }\n\nAfter detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:\n\n{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}", "source_type": "doc", "path": "docs/en/docs/advanced/security/http-basic-auth.md", "symbol": "Check the username { #check-the-username }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/http-basic-auth.md#L29-L107", "start_line": 29, "end_line": 107} {"id": "docs/en/docs/advanced/security/index.md::Additional Features { #additional-features }::L3", "text": "# Doc: docs/en/docs/advanced/security/index.md | Page: Advanced Security { #advanced-security } | Section: Additional Features { #additional-features }\n## Additional Features { #additional-features }\n\nThere are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md).\n\n/// tip\n\nThe next sections are **not necessarily \"advanced\"**.\n\nAnd it's possible that for your use case, the solution is in one of them.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/security/index.md", "symbol": "Additional Features { #additional-features }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/index.md#L3-L14", "start_line": 3, "end_line": 14} {"id": "docs/en/docs/advanced/security/index.md::Read the Tutorial first { #read-the-tutorial-first }::L15", "text": "# Doc: docs/en/docs/advanced/security/index.md | Page: Advanced Security { #advanced-security } | Section: Read the Tutorial first { #read-the-tutorial-first }\n## Read the Tutorial first { #read-the-tutorial-first }\n\nThe next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/index.md).\n\nThey are all based on the same concepts, but allow some extra functionalities.", "source_type": "doc", "path": "docs/en/docs/advanced/security/index.md", "symbol": "Read the Tutorial first { #read-the-tutorial-first }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/index.md#L15-L19", "start_line": 15, "end_line": 19} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::OAuth2 scopes { #oauth2-scopes }::L1", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: OAuth2 scopes { #oauth2-scopes }\n# OAuth2 scopes { #oauth2-scopes }\n\nYou can use OAuth2 scopes directly with **FastAPI**, they are integrated to work seamlessly.\n\nThis would allow you to have a more fine-grained permission system, following the OAuth2 standard, integrated into your OpenAPI application (and the API docs).\n\nOAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, X (Twitter), etc. They use it to provide specific permissions to users and applications.\n\nEvery time you \"log in with\" Facebook, Google, GitHub, Microsoft, X (Twitter), that application is using OAuth2 with scopes.\n\nIn this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application.\n\n/// warning\n\nThis is a more or less advanced section. If you are just starting, you can skip it.\n\nYou don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.\n\nBut OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.\n\nNevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.\n\nIn many cases, OAuth2 with scopes can be an overkill.\n\nBut if you know you need it, or you are curious, keep reading.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "OAuth2 scopes { #oauth2-scopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L1-L28", "start_line": 1, "end_line": 28} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::OAuth2 scopes and OpenAPI { #oauth2-scopes-and-openapi }::L29", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: OAuth2 scopes and OpenAPI { #oauth2-scopes-and-openapi }\n## OAuth2 scopes and OpenAPI { #oauth2-scopes-and-openapi }\n\nThe OAuth2 specification defines \"scopes\" as a list of strings separated by spaces.\n\nThe content of each of these strings can have any format, but should not contain spaces.\n\nThese scopes represent \"permissions\".\n\nIn OpenAPI (e.g. the API docs), you can define \"security schemes\".\n\nWhen one of these security schemes uses OAuth2, you can also declare and use scopes.\n\nEach \"scope\" is just a string (without spaces).\n\nThey are normally used to declare specific security permissions, for example:\n\n* `users:read` or `users:write` are common examples.\n* `instagram_basic` is used by Facebook / Instagram.\n* `https://www.googleapis.com/auth/drive` is used by Google.\n\n/// note\n\nIn OAuth2 a \"scope\" is just a string that declares a specific permission required.\n\nIt doesn't matter if it has other characters like `:` or if it is a URL.\n\nThose details are implementation specific.\n\nFor OAuth2 they are just strings.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "OAuth2 scopes and OpenAPI { #oauth2-scopes-and-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L29-L60", "start_line": 29, "end_line": 60} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Global view { #global-view }::L61", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Global view { #global-view }\n## Global view { #global-view }\n\nFirst, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md). Now using OAuth2 scopes:\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}\n\nNow let's review those changes step by step.", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Global view { #global-view }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L61-L68", "start_line": 61, "end_line": 68} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::OAuth2 Security scheme { #oauth2-security-scheme }::L69", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: OAuth2 Security scheme { #oauth2-security-scheme }\n## OAuth2 Security scheme { #oauth2-security-scheme }\n\nThe first change is that now we are declaring the OAuth2 security scheme with two available scopes, `me` and `items`.\n\nThe `scopes` parameter receives a `dict` with each scope as a key and the description as the value:\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}\n\nBecause we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.\n\nAnd you will be able to select which scopes you want to give access to: `me` and `items`.\n\nThis is the same mechanism used when you give permissions while logging in with Facebook, Google, GitHub, etc:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "OAuth2 Security scheme { #oauth2-security-scheme }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L69-L84", "start_line": 69, "end_line": 84} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::JWT token with scopes { #jwt-token-with-scopes }::L85", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: JWT token with scopes { #jwt-token-with-scopes }\n## JWT token with scopes { #jwt-token-with-scopes }\n\nNow, modify the token *path operation* to return the scopes requested.\n\nWe are still using the same `OAuth2PasswordRequestForm`. It includes a property `scopes` with a `list` of `str`, with each scope it received in the request.\n\nAnd we return the scopes as part of the JWT token.\n\n/// danger\n\nFor simplicity, here we are just adding the scopes received directly to the token.\n\nBut in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.\n\n///\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "JWT token with scopes { #jwt-token-with-scopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L85-L102", "start_line": 85, "end_line": 102} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Declare scopes in *path operations* and dependencies { #declare-scopes-in-path-operations-and-dependencies }::L103", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Declare scopes in *path operations* and dependencies { #declare-scopes-in-path-operations-and-dependencies }\n## Declare scopes in *path operations* and dependencies { #declare-scopes-in-path-operations-and-dependencies }\n\nNow we declare that the *path operation* for `/users/me/items/` requires the scope `items`.\n\nFor this, we import and use `Security` from `fastapi`.\n\nYou can use `Security` to declare dependencies (just like `Depends`), but `Security` also receives a parameter `scopes` with a list of scopes (strings).\n\nIn this case, we pass a dependency function `get_current_active_user` to `Security` (the same way we would do with `Depends`).\n\nBut we also pass a `list` of scopes, in this case with just one scope: `items` (it could have more).\n\nAnd the dependency function `get_current_active_user` can also declare sub-dependencies, not only with `Depends` but also with `Security`. Declaring its own sub-dependency function (`get_current_user`), and more scope requirements.\n\nIn this case, it requires the scope `me` (it could require more than one scope).\n\n/// note\n\nYou don't necessarily need to add different scopes in different places.\n\nWe are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.\n\n///\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}\n\n/// note | Technical Details\n\n`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.\n\nBut by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.\n\nBut when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Declare scopes in *path operations* and dependencies { #declare-scopes-in-path-operations-and-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L103-L138", "start_line": 103, "end_line": 138} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Use `SecurityScopes` { #use-securityscopes }::L139", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Use `SecurityScopes` { #use-securityscopes }\n## Use `SecurityScopes` { #use-securityscopes }\n\nNow update the dependency `get_current_user`.\n\nThis is the one used by the dependencies above.\n\nHere's where we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`.\n\nBecause this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes.\n\nWe also declare a special parameter of type `SecurityScopes`, imported from `fastapi.security`.\n\nThis `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly).\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Use `SecurityScopes` { #use-securityscopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L139-L154", "start_line": 139, "end_line": 154} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Use the `scopes` { #use-the-scopes }::L155", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Use the `scopes` { #use-the-scopes }\n## Use the `scopes` { #use-the-scopes }\n\nThe parameter `security_scopes` will be of type `SecurityScopes`.\n\nIt will have a property `scopes` with a list containing all the scopes required by itself and all the dependencies that use this as a sub-dependency. That means, all the \"dependants\"... this might sound confusing, it is explained again later below.\n\nThe `security_scopes` object (of class `SecurityScopes`) also provides a `scope_str` attribute with a single string, containing those scopes separated by spaces (we are going to use it).\n\nWe create an `HTTPException` that we can reuse (`raise`) later at several points.\n\nIn this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec).\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Use the `scopes` { #use-the-scopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L155-L168", "start_line": 155, "end_line": 168} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Verify the `username` and data shape { #verify-the-username-and-data-shape }::L169", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Verify the `username` and data shape { #verify-the-username-and-data-shape }\n## Verify the `username` and data shape { #verify-the-username-and-data-shape }\n\nWe verify that we get a `username`, and extract the scopes.\n\nAnd then we validate that data with the Pydantic model (catching the `ValidationError` exception), and if we get an error reading the JWT token or validating the data with Pydantic, we raise the `HTTPException` we created before.\n\nFor that, we update the Pydantic model `TokenData` with a new property `scopes`.\n\nBy validating the data with Pydantic we can make sure that we have, for example, exactly a `list` of `str` with the scopes and a `str` with the `username`.\n\nInstead of, for example, a `dict`, or something else, as it could break the application at some point later, making it a security risk.\n\nWe also verify that we have a user with that username, and if not, we raise that same exception we created before.\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Verify the `username` and data shape { #verify-the-username-and-data-shape }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L169-L184", "start_line": 169, "end_line": 184} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Verify the `scopes` { #verify-the-scopes }::L185", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Verify the `scopes` { #verify-the-scopes }\n## Verify the `scopes` { #verify-the-scopes }\n\nWe now verify that all the scopes required, by this dependency and all the dependants (including *path operations*), are included in the scopes provided in the token received, otherwise raise an `HTTPException`.\n\nFor this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.\n\n{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Verify the `scopes` { #verify-the-scopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L185-L192", "start_line": 185, "end_line": 192} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Dependency tree and scopes { #dependency-tree-and-scopes }::L193", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Dependency tree and scopes { #dependency-tree-and-scopes }\n## Dependency tree and scopes { #dependency-tree-and-scopes }\n\nLet's review again this dependency tree and the scopes.\n\nAs the `get_current_active_user` dependency has `get_current_user` as a sub-dependency, the scope `\"me\"` declared at `get_current_active_user` will be included in the list of required scopes in the `security_scopes.scopes` passed to `get_current_user`.\n\nThe *path operation* itself also declares a scope, `\"items\"`, so this will also be in the list of `security_scopes.scopes` passed to `get_current_user`.\n\nHere's what the hierarchy of dependencies and scopes looks like:\n\n* The *path operation* `read_own_items` has:\n * Required scopes `[\"items\"]` with the dependency:\n * `get_current_active_user`:\n * The dependency function `get_current_active_user` has:\n * Required scopes `[\"me\"]` with the dependency:\n * `get_current_user`:\n * The dependency function `get_current_user` has:\n * No scopes required by itself.\n * A dependency using `oauth2_scheme`.\n * A `security_scopes` parameter of type `SecurityScopes`:\n * This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so:\n * `security_scopes.scopes` will contain `[\"me\", \"items\"]` for the *path operation* `read_own_items`.\n * `security_scopes.scopes` will contain `[\"me\"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`.\n * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scopes` either.\n\n/// tip\n\nThe important and \"magic\" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.\n\nAll depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Dependency tree and scopes { #dependency-tree-and-scopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L193-L225", "start_line": 193, "end_line": 225} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::More details about `SecurityScopes` { #more-details-about-securityscopes }::L226", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: More details about `SecurityScopes` { #more-details-about-securityscopes }\n## More details about `SecurityScopes` { #more-details-about-securityscopes }\n\nYou can use `SecurityScopes` at any point, and in multiple places, it doesn't have to be at the \"root\" dependency.\n\nIt will always have the security scopes declared in the current `Security` dependencies and all the dependants for **that specific** *path operation* and **that specific** dependency tree.\n\nBecause the `SecurityScopes` will have all the scopes declared by dependants, you can use it to verify that a token has the required scopes in a central dependency function, and then declare different scope requirements in different *path operations*.\n\nThey will be checked independently for each *path operation*.", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "More details about `SecurityScopes` { #more-details-about-securityscopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L226-L235", "start_line": 226, "end_line": 235} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::Check it { #check-it }::L236", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: Check it { #check-it }\n## Check it { #check-it }\n\nIf you open the API docs, you can authenticate and specify which scopes you want to authorize.\n\n\n\nIf you don't select any scope, you will be \"authenticated\", but when you try to access `/users/me/` or `/users/me/items/` you will get an error saying that you don't have enough permissions. You will still be able to access `/status/`.\n\nAnd if you select the scope `me` but not the scope `items`, you will be able to access `/users/me/` but not `/users/me/items/`.\n\nThat's what would happen to a third party application that tried to access one of these *path operations* with a token provided by a user, depending on how many permissions the user gave the application.", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "Check it { #check-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L236-L247", "start_line": 236, "end_line": 247} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::About third party integrations { #about-third-party-integrations }::L248", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: About third party integrations { #about-third-party-integrations }\n## About third party integrations { #about-third-party-integrations }\n\nIn this example we are using the OAuth2 \"password\" flow.\n\nThis is appropriate when we are logging in to our own application, probably with our own frontend.\n\nBecause we can trust it to receive the `username` and `password`, as we control it.\n\nBut if you are building an OAuth2 application that others would connect to (i.e., if you are building an authentication provider equivalent to Facebook, Google, GitHub, etc.) you should use one of the other flows.\n\nThe most common is the implicit flow.\n\nThe most secure is the code flow, but it's more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.\n\n/// note\n\nIt's common that each authentication provider names their flows in a different way, to make it part of their brand.\n\nBut in the end, they are implementing the same OAuth2 standard.\n\n///\n\n**FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`.", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "About third party integrations { #about-third-party-integrations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L248-L271", "start_line": 248, "end_line": 271} {"id": "docs/en/docs/advanced/security/oauth2-scopes.md::`Security` in decorator `dependencies` { #security-in-decorator-dependencies }::L272", "text": "# Doc: docs/en/docs/advanced/security/oauth2-scopes.md | Page: OAuth2 scopes { #oauth2-scopes } | Section: `Security` in decorator `dependencies` { #security-in-decorator-dependencies }\n## `Security` in decorator `dependencies` { #security-in-decorator-dependencies }\n\nThe same way you can define a `list` of `Depends` in the decorator's `dependencies` parameter (as explained in [Dependencies in path operation decorators](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)), you could also use `Security` with `scopes` there.", "source_type": "doc", "path": "docs/en/docs/advanced/security/oauth2-scopes.md", "symbol": "`Security` in decorator `dependencies` { #security-in-decorator-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/security/oauth2-scopes.md#L272-L274", "start_line": 272, "end_line": 274} {"id": "docs/en/docs/advanced/settings.md::Settings and Environment Variables { #settings-and-environment-variables }::L1", "text": "# Doc: docs/en/docs/advanced/settings.md | Page: Settings and Environment Variables { #settings-and-environment-variables } | Section: Settings and Environment Variables { #settings-and-environment-variables }\n# Settings and Environment Variables { #settings-and-environment-variables }\n\nIn many cases your application could need some external settings or configurations, for example secret keys, database credentials, credentials for email services, etc.\n\nMost of these settings are variable (can change), like database URLs. And many could be sensitive, like secrets.\n\nFor this reason it's common to provide them in environment variables that are read by the application.\n\n/// tip\n\nTo understand environment variables you can read [Environment Variables](../environment-variables.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/settings.md", "symbol": "Settings and Environment Variables { #settings-and-environment-variables }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/settings.md#L1-L14", "start_line": 1, "end_line": 14} {"id": "docs/en/docs/advanced/settings.md::Types and validation { #types-and-validation }::L15", "text": "# Doc: docs/en/docs/advanced/settings.md | Page: Settings and Environment Variables { #settings-and-environment-variables } | Section: Types and validation { #types-and-validation }\n## Types and validation { #types-and-validation }\n\nThese environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, such as Linux, Windows, and macOS).\n\nThat means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code.", "source_type": "doc", "path": "docs/en/docs/advanced/settings.md", "symbol": "Types and validation { #types-and-validation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/settings.md#L15-L20", "start_line": 15, "end_line": 20} {"id": "docs/en/docs/advanced/settings.md::Pydantic `Settings` { #pydantic-settings }::L21", "text": "# Doc: docs/en/docs/advanced/settings.md | Page: Settings and Environment Variables { #settings-and-environment-variables } | Section: Pydantic `Settings` { #pydantic-settings }\n## Pydantic `Settings` { #pydantic-settings }\n\nFortunately, Pydantic provides a great utility to handle these settings coming from environment variables with [Pydantic: Settings management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).\n\n### Install `pydantic-settings` { #install-pydantic-settings }\n\nFirst, make sure you create your [virtual environment](../virtual-environments.md), activate it, and then install the `pydantic-settings` package:\n\n
\n\n```console\n$ pip install pydantic-settings\n---> 100%\n```\n\n
\n\nIt also comes included when you install the `all` extras with:\n\n
\n\n```console\n$ pip install \"fastapi[all]\"\n---> 100%\n```\n\n
\n\n### Create the `Settings` object { #create-the-settings-object }\n\nImport `BaseSettings` from Pydantic and create a sub-class, very much like with a Pydantic model.\n\nThe same way as with Pydantic models, you declare class attributes with type annotations, and possibly default values.\n\nYou can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`.\n\n{* ../../docs_src/settings/tutorial001_py310.py hl[2,5:8,11] *}\n\n/// tip\n\nIf you want something quick to copy and paste, don't use this example, use the last one below.\n\n///\n\nThen, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`.\n\nNext it will convert and validate the data. So, when you use that `settings` object, you will have data of the types you declared (e.g. `items_per_user` will be an `int`).\n\n### Use the `settings` { #use-the-settings }\n\nThen you can use the new `settings` object in your application:\n\n{* ../../docs_src/settings/tutorial001_py310.py hl[18:20] *}\n\n### Run the server { #run-the-server }\n\nNext, you would run the server passing the configurations as environment variables, for example you could set an `ADMIN_EMAIL` and `APP_NAME` with:\n\n
\n\n```console\n$ ADMIN_EMAIL=\"deadpool@example.com\" APP_NAME=\"ChimichangApp\" fastapi run main.py\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\n/// tip\n\nTo set multiple env vars for a single command just separate them with a space, and put them all before the command.\n\n///\n\nAnd then the `admin_email` setting would be set to `\"deadpool@example.com\"`.\n\nThe `app_name` would be `\"ChimichangApp\"`.\n\nAnd the `items_per_user` would keep its default value of `50`.", "source_type": "doc", "path": "docs/en/docs/advanced/settings.md", "symbol": "Pydantic `Settings` { #pydantic-settings }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/settings.md#L21-L100", "start_line": 21, "end_line": 100} {"id": "docs/en/docs/advanced/settings.md::Settings in another module { #settings-in-another-module }::L101", "text": "# Doc: docs/en/docs/advanced/settings.md | Page: Settings and Environment Variables { #settings-and-environment-variables } | Section: Settings in another module { #settings-in-another-module }\n## Settings in another module { #settings-in-another-module }\n\nYou could put those settings in another module file as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md).\n\nFor example, you could have a file `config.py` with:\n\n{* ../../docs_src/settings/app01_py310/config.py *}\n\nAnd then use it in a file `main.py`:\n\n{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}\n\n/// tip\n\nYou would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/settings.md", "symbol": "Settings in another module { #settings-in-another-module }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/settings.md#L101-L118", "start_line": 101, "end_line": 118} {"id": "docs/en/docs/advanced/settings.md::Settings in a dependency { #settings-in-a-dependency }::L119", "text": "# Doc: docs/en/docs/advanced/settings.md | Page: Settings and Environment Variables { #settings-and-environment-variables } | Section: Settings in a dependency { #settings-in-a-dependency }\n## Settings in a dependency { #settings-in-a-dependency }\n\nIn some occasions it might be useful to provide the settings from a dependency, instead of having a global object with `settings` that is used everywhere.\n\nThis could be especially useful during testing, as it's very easy to override a dependency with your own custom settings.\n\n### The config file { #the-config-file }\n\nComing from the previous example, your `config.py` file could look like:\n\n{* ../../docs_src/settings/app02_an_py310/config.py hl[10] *}\n\nNotice that now we don't create a default instance `settings = Settings()`.\n\n### The main app file { #the-main-app-file }\n\nNow we create a dependency that returns a new `config.Settings()`.\n\n{* ../../docs_src/settings/app02_an_py310/main.py hl[6,12:13] *}\n\n/// tip\n\nWe'll discuss the `@lru_cache` in a bit.\n\nFor now you can assume `get_settings()` is a normal function.\n\n///\n\nAnd then we can require it from the *path operation function* as a dependency and use it anywhere we need it.\n\n{* ../../docs_src/settings/app02_an_py310/main.py hl[17,19:21] *}\n\n### Settings and testing { #settings-and-testing }\n\nThen it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`:\n\n{* ../../docs_src/settings/app02_an_py310/test_main.py hl[9:10,13,21] *}\n\nIn the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object.\n\nThen we can test that it is used.", "source_type": "doc", "path": "docs/en/docs/advanced/settings.md", "symbol": "Settings in a dependency { #settings-in-a-dependency }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/settings.md#L119-L160", "start_line": 119, "end_line": 160} {"id": "docs/en/docs/advanced/settings.md::Reading a `.env` file { #reading-a-env-file }::L161", "text": "# Doc: docs/en/docs/advanced/settings.md | Page: Settings and Environment Variables { #settings-and-environment-variables } | Section: Reading a `.env` file { #reading-a-env-file }\n## Reading a `.env` file { #reading-a-env-file }\n\nIf you have many settings that possibly change a lot, maybe in different environments, it might be useful to put them on a file and then read them from it as if they were environment variables.\n\nThis practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a \"dotenv\".\n\n/// tip\n\nA file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS.\n\nBut a dotenv file doesn't really have to have that exact filename.\n\n///\n\nPydantic has support for reading from these types of files using an external library. You can read more at [Pydantic Settings: Dotenv (.env) support](https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support).\n\n/// tip\n\nFor this to work, you need to `pip install python-dotenv`.\n\n///\n\n### The `.env` file { #the-env-file }\n\nYou could have a `.env` file with:\n\n```bash\nADMIN_EMAIL=\"deadpool@example.com\"\nAPP_NAME=\"ChimichangApp\"\n```\n\n### Read settings from `.env` { #read-settings-from-env }\n\nAnd then update your `config.py` with:\n\n{* ../../docs_src/settings/app03_an_py310/config.py hl[9] *}\n\n/// tip\n\nThe `model_config` attribute is used just for Pydantic configuration. You can read more at [Pydantic: Concepts: Configuration](https://docs.pydantic.dev/latest/concepts/config/).\n\n///\n\nHere we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.\n\n### Creating the `Settings` only once with `lru_cache` { #creating-the-settings-only-once-with-lru-cache }\n\nReading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request.\n\nBut every time we do:\n\n```Python\nSettings()\n```\n\na new `Settings` object would be created, and at creation it would read the `.env` file again.\n\nIf the dependency function was just like:\n\n```Python\ndef get_settings():\n return Settings()\n```\n\nwe would create that object for each request, and we would be reading the `.env` file for each request. ⚠️\n\nBut as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️\n\n{* ../../docs_src/settings/app03_an_py310/main.py hl[1,11] *}\n\nThen for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.\n\n#### `lru_cache` Technical Details { #lru-cache-technical-details }\n\n`@lru_cache` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time.\n\nSo, the function below it will be executed once for each combination of arguments. And then the values returned by each of those combinations of arguments will be used again and again whenever the function is called with exactly the same combination of arguments.\n\nFor example, if you have a function:\n\n```Python\n@lru_cache\ndef say_hi(name: str, salutation: str = \"Ms.\"):\n return f\"Hello {salutation} {name}\"\n```\n\nyour program could execute like this:\n\n```mermaid\nsequenceDiagram\n\nparticipant code as Code\nparticipant function as say_hi()\nparticipant execute as Execute function\n\n rect rgba(0, 255, 0, .1)\n code ->> function: say_hi(name=\"Camila\")\n function ->> execute: execute function code\n execute ->> code: return the result\n end\n\n rect rgba(0, 255, 255, .1)\n code ->> function: say_hi(name=\"Camila\")\n function ->> code: return stored result\n end\n\n rect rgba(0, 255, 0, .1)\n code ->> function: say_hi(name=\"Rick\")\n function ->> execute: execute function code\n execute ->> code: return the result\n end\n\n rect rgba(0, 255, 0, .1)\n code ->> function: say_hi(name=\"Rick\", salutation=\"Mr.\")\n function ->> execute: execute function code\n execute ->> code: return the result\n end\n\n rect rgba(0, 255, 255, .1)\n code ->> function: say_hi(name=\"Rick\")\n function ->> code: return stored result\n end\n\n rect rgba(0, 255, 255, .1)\n code ->> function: say_hi(name=\"Camila\")\n function ->> code: return stored result\n end\n```\n\nIn the case of our dependency `get_settings()`, the function doesn't even take any arguments, so it always returns the same value.\n\nThat way, it behaves almost as if it was just a global variable. But as it uses a dependency function, then we can override it easily for testing.\n\n`@lru_cache` is part of `functools` which is part of Python's standard library, you can read more about it in the [Python docs for `@lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache).", "source_type": "doc", "path": "docs/en/docs/advanced/settings.md", "symbol": "Reading a `.env` file { #reading-a-env-file }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/settings.md#L161-L295", "start_line": 161, "end_line": 295} {"id": "docs/en/docs/advanced/settings.md::Recap { #recap }::L296", "text": "# Doc: docs/en/docs/advanced/settings.md | Page: Settings and Environment Variables { #settings-and-environment-variables } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can use Pydantic Settings to handle the settings or configurations for your application, with all the power of Pydantic models.\n\n* By using a dependency you can simplify testing.\n* You can use `.env` files with it.\n* Using `@lru_cache` lets you avoid reading the dotenv file again and again for each request, while allowing you to override it during testing.", "source_type": "doc", "path": "docs/en/docs/advanced/settings.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/settings.md#L296-L302", "start_line": 296, "end_line": 302} {"id": "docs/en/docs/advanced/stream-data.md::Stream Data { #stream-data }::L1", "text": "# Doc: docs/en/docs/advanced/stream-data.md | Page: Stream Data { #stream-data } | Section: Stream Data { #stream-data }\n# Stream Data { #stream-data }\n\nIf you want to stream data that can be structured as JSON, you should [Stream JSON Lines](../tutorial/stream-json-lines.md).\n\nBut if you want to **stream pure binary data** or strings, here's how you can do it.\n\n/// note\n\nAdded in FastAPI 0.134.0.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/stream-data.md", "symbol": "Stream Data { #stream-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/stream-data.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/advanced/stream-data.md::Use Cases { #use-cases }::L13", "text": "# Doc: docs/en/docs/advanced/stream-data.md | Page: Stream Data { #stream-data } | Section: Use Cases { #use-cases }\n## Use Cases { #use-cases }\n\nYou could use this if you want to stream pure strings, for example directly from the output of an **AI LLM** service.\n\nYou could also use it to stream **large binary files**, where you stream each chunk of data as you read it, without having to read it all into memory at once.\n\nYou could also stream **video** or **audio** this way, it could even be generated as you process and send it.", "source_type": "doc", "path": "docs/en/docs/advanced/stream-data.md", "symbol": "Use Cases { #use-cases }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/stream-data.md#L13-L20", "start_line": 13, "end_line": 20} {"id": "docs/en/docs/advanced/stream-data.md::A `StreamingResponse` with `yield` { #a-streamingresponse-with-yield }::L21", "text": "# Doc: docs/en/docs/advanced/stream-data.md | Page: Stream Data { #stream-data } | Section: A `StreamingResponse` with `yield` { #a-streamingresponse-with-yield }\n## A `StreamingResponse` with `yield` { #a-streamingresponse-with-yield }\n\nIf you declare a `response_class=StreamingResponse` in your *path operation function*, you can use `yield` to send each chunk of data in turn.\n\n{* ../../docs_src/stream_data/tutorial001_py310.py ln[1:23] hl[20,23] *}\n\nFastAPI will give each chunk of data to the `StreamingResponse` as is, it won't try to convert it to JSON or anything similar.\n\n### Non-async *path operation functions* { #non-async-path-operation-functions }\n\nYou can also use regular `def` functions (without `async`), and use `yield` the same way.\n\n{* ../../docs_src/stream_data/tutorial001_py310.py ln[26:29] hl[27] *}\n\n### No Annotation { #no-annotation }\n\nYou don't really need to declare the return type annotation for streaming binary data.\n\nAs FastAPI will not try to convert the data to JSON with Pydantic or serialize it in any way, in this case, the type annotation is only for your editor and tools to use, it won't be used by FastAPI.\n\n{* ../../docs_src/stream_data/tutorial001_py310.py ln[32:35] hl[33] *}\n\nThis also means that with `StreamingResponse` you have the **freedom** and **responsibility** to produce and encode the data bytes exactly as you need them to be sent, independent of the type annotations. 🤓\n\n### Stream Bytes { #stream-bytes }\n\nOne of the main use cases would be to stream `bytes` instead of strings, you can of course do it.\n\n{* ../../docs_src/stream_data/tutorial001_py310.py ln[44:47] hl[47] *}", "source_type": "doc", "path": "docs/en/docs/advanced/stream-data.md", "symbol": "A `StreamingResponse` with `yield` { #a-streamingresponse-with-yield }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/stream-data.md#L21-L50", "start_line": 21, "end_line": 50} {"id": "docs/en/docs/advanced/stream-data.md::A Custom `PNGStreamingResponse` { #a-custom-pngstreamingresponse }::L51", "text": "# Doc: docs/en/docs/advanced/stream-data.md | Page: Stream Data { #stream-data } | Section: A Custom `PNGStreamingResponse` { #a-custom-pngstreamingresponse }\n## A Custom `PNGStreamingResponse` { #a-custom-pngstreamingresponse }\n\nIn the examples above, the data bytes were streamed, but the response didn't have a `Content-Type` header, so the client didn't know what type of data it was receiving.\n\nYou can create a custom sub-class of `StreamingResponse` that sets the `Content-Type` header to the type of data you're streaming.\n\nFor example, you can create a `PNGStreamingResponse` that sets the `Content-Type` header to `image/png` using the `media_type` attribute:\n\n{* ../../docs_src/stream_data/tutorial002_py310.py ln[6,19:20] hl[20] *}\n\nThen you can use this new class in `response_class=PNGStreamingResponse` in your *path operation function*:\n\n{* ../../docs_src/stream_data/tutorial002_py310.py ln[23:27] hl[23] *}\n\n### Simulate a File { #simulate-a-file }\n\nIn this example, we are simulating a file with `io.BytesIO`, which is a file-like object that lives only in memory, but lets us use the same interface.\n\nFor example, we can iterate over it to consume its contents, as we could with a file.\n\n{* ../../docs_src/stream_data/tutorial002_py310.py ln[1:27] hl[3,12:13,25] *}\n\n/// note | Technical Details\n\nThe other two variables, `image_base64` and `binary_image`, are an image encoded in Base64, and then converted to bytes, to then pass it to `io.BytesIO`.\n\nOnly so that it can live in the same file for this example and you can copy it and run it as is. 🥚\n\n///\n\nBy using a `with` block, we make sure that the file-like object is closed after the generator function (the function with `yield`) is done. So, after it finishes sending the response.\n\nIt wouldn't be that important in this specific example because it's a fake in-memory file (with `io.BytesIO`), but with a real file, it would be important to make sure the file is closed after the work with it is done.\n\n### Files and Async { #files-and-async }\n\nIn most cases, file-like objects are not compatible with async and await by default.\n\nFor example, they don't have an `await file.read()`, or `async for chunk in file`.\n\nAnd in many cases, reading them would be a blocking operation (that could block the event loop), because they are read from disk or from the network.\n\n/// note\n\nThe example above is actually an exception, because the `io.BytesIO` object is already in memory, so reading it won't block anything.\n\nBut in many cases reading a file or a file-like object would block.\n\n///\n\nTo avoid blocking the event loop, you can simply declare the *path operation function* with regular `def` instead of `async def`, that way FastAPI will run it on a threadpool worker, to avoid blocking the main loop.\n\n{* ../../docs_src/stream_data/tutorial002_py310.py ln[30:34] hl[31] *}\n\n/// tip\n\nIf you need to call blocking code from inside of an async function, or an async function from inside of a blocking function, you could use [Asyncer](https://asyncer.tiangolo.com), a sibling library to FastAPI.\n\n///\n\n### `yield from` { #yield-from }\n\nWhen you are iterating over something, like a file-like object, and then you are doing `yield` for each item, you could also use `yield from` to yield each item directly and skip the `for` loop.\n\nThis is not particular to FastAPI, it's just Python, but it's a nice trick to know. 😎\n\n{* ../../docs_src/stream_data/tutorial002_py310.py ln[37:40] hl[40] *}", "source_type": "doc", "path": "docs/en/docs/advanced/stream-data.md", "symbol": "A Custom `PNGStreamingResponse` { #a-custom-pngstreamingresponse }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/stream-data.md#L51-L117", "start_line": 51, "end_line": 117} {"id": "docs/en/docs/advanced/strict-content-type.md::Strict Content-Type Checking { #strict-content-type-checking }::L1", "text": "# Doc: docs/en/docs/advanced/strict-content-type.md | Page: Strict Content-Type Checking { #strict-content-type-checking } | Section: Strict Content-Type Checking { #strict-content-type-checking }\n# Strict Content-Type Checking { #strict-content-type-checking }\n\nBy default, **FastAPI** uses strict `Content-Type` header checking for JSON request bodies, this means that JSON requests **must** include a valid `Content-Type` header (e.g. `application/json`) in order for the body to be parsed as JSON.", "source_type": "doc", "path": "docs/en/docs/advanced/strict-content-type.md", "symbol": "Strict Content-Type Checking { #strict-content-type-checking }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/strict-content-type.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/advanced/strict-content-type.md::CSRF Risk { #csrf-risk }::L5", "text": "# Doc: docs/en/docs/advanced/strict-content-type.md | Page: Strict Content-Type Checking { #strict-content-type-checking } | Section: CSRF Risk { #csrf-risk }\n## CSRF Risk { #csrf-risk }\n\nThis default behavior provides protection against a class of **Cross-Site Request Forgery (CSRF)** attacks in a very specific scenario.\n\nThese attacks exploit the fact that browsers allow scripts to send requests without doing any CORS preflight check when they:\n\n* don't have a `Content-Type` header (e.g. using `fetch()` with a `Blob` body)\n* and don't send any authentication credentials.\n\nThis type of attack is mainly relevant when:\n\n* the application is running locally (e.g. on `localhost`) or in an internal network\n* and the application doesn't have any authentication, it expects that any request from the same network can be trusted.", "source_type": "doc", "path": "docs/en/docs/advanced/strict-content-type.md", "symbol": "CSRF Risk { #csrf-risk }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/strict-content-type.md#L5-L18", "start_line": 5, "end_line": 18} {"id": "docs/en/docs/advanced/strict-content-type.md::Example Attack { #example-attack }::L19", "text": "# Doc: docs/en/docs/advanced/strict-content-type.md | Page: Strict Content-Type Checking { #strict-content-type-checking } | Section: Example Attack { #example-attack }\n## Example Attack { #example-attack }\n\nImagine you build a way to run a local AI agent.\n\nIt provides an API at\n\n```\nhttp://localhost:8000/v1/agents/multivac\n```\n\nThere's also a frontend at\n\n```\nhttp://localhost:8000\n```\n\n/// tip\n\nNote that both have the same host.\n\n///\n\nThen using the frontend you can make the AI agent do things on your behalf.\n\nAs it's running **locally**, and not in the open internet, you decide to **not have any authentication** set up, just trusting the access to the local network.\n\nThen one of your users could install it and run it locally.\n\nThen they could open a malicious website, e.g. something like\n\n```\nhttps://evilhackers.example.com\n```\n\nAnd that malicious website sends requests using `fetch()` with a `Blob` body to the local API at\n\n```\nhttp://localhost:8000/v1/agents/multivac\n```\n\nEven though the host of the malicious website and the local app is different, the browser won't trigger a CORS preflight request because:\n\n* It's running without any authentication, it doesn't have to send any credentials.\n* The browser thinks it's not sending JSON (because of the missing `Content-Type` header).\n\nThen the malicious website could make the local AI agent send angry messages to the user's ex-boss... or worse. 😅", "source_type": "doc", "path": "docs/en/docs/advanced/strict-content-type.md", "symbol": "Example Attack { #example-attack }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/strict-content-type.md#L19-L65", "start_line": 19, "end_line": 65} {"id": "docs/en/docs/advanced/strict-content-type.md::Open Internet { #open-internet }::L66", "text": "# Doc: docs/en/docs/advanced/strict-content-type.md | Page: Strict Content-Type Checking { #strict-content-type-checking } | Section: Open Internet { #open-internet }\n## Open Internet { #open-internet }\n\nIf your app is in the open internet, you wouldn't \"trust the network\" and let anyone send privileged requests without authentication.\n\nAttackers could simply run a script to send requests to your API, no need for browser interaction, so you are probably already securing any privileged endpoints.\n\nIn that case **this attack / risk doesn't apply to you**.\n\nThis risk and attack is mainly relevant when the app runs on the **local network** and that is the **only assumed protection**.", "source_type": "doc", "path": "docs/en/docs/advanced/strict-content-type.md", "symbol": "Open Internet { #open-internet }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/strict-content-type.md#L66-L75", "start_line": 66, "end_line": 75} {"id": "docs/en/docs/advanced/strict-content-type.md::Allowing Requests Without Content-Type { #allowing-requests-without-content-type }::L76", "text": "# Doc: docs/en/docs/advanced/strict-content-type.md | Page: Strict Content-Type Checking { #strict-content-type-checking } | Section: Allowing Requests Without Content-Type { #allowing-requests-without-content-type }\n## Allowing Requests Without Content-Type { #allowing-requests-without-content-type }\n\nIf you need to support clients that don't send a `Content-Type` header, you can disable strict checking by setting `strict_content_type=False`:\n\n{* ../../docs_src/strict_content_type/tutorial001_py310.py hl[4] *}\n\nWith this setting, requests without a `Content-Type` header will have their body parsed as JSON, which is the same behavior as older versions of FastAPI.\n\n/// note\n\nThis behavior and configuration was added in FastAPI 0.132.0.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/strict-content-type.md", "symbol": "Allowing Requests Without Content-Type { #allowing-requests-without-content-type }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/strict-content-type.md#L76-L88", "start_line": 76, "end_line": 88} {"id": "docs/en/docs/advanced/sub-applications.md::Sub Applications - Mounts { #sub-applications-mounts }::L1", "text": "# Doc: docs/en/docs/advanced/sub-applications.md | Page: Sub Applications - Mounts { #sub-applications-mounts } | Section: Sub Applications - Mounts { #sub-applications-mounts }\n# Sub Applications - Mounts { #sub-applications-mounts }\n\nIf you need to have two independent FastAPI applications, with their own independent OpenAPI and their own docs UIs, you can have a main app and \"mount\" one (or more) sub-application(s).", "source_type": "doc", "path": "docs/en/docs/advanced/sub-applications.md", "symbol": "Sub Applications - Mounts { #sub-applications-mounts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/sub-applications.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/advanced/sub-applications.md::Mounting a **FastAPI** application { #mounting-a-fastapi-application }::L5", "text": "# Doc: docs/en/docs/advanced/sub-applications.md | Page: Sub Applications - Mounts { #sub-applications-mounts } | Section: Mounting a **FastAPI** application { #mounting-a-fastapi-application }\n## Mounting a **FastAPI** application { #mounting-a-fastapi-application }\n\n\"Mounting\" means adding a completely \"independent\" application in a specific path, that then takes care of handling everything under that path, with the _path operations_ declared in that sub-application.\n\n### Top-level application { #top-level-application }\n\nFirst, create the main, top-level, **FastAPI** application, and its *path operations*:\n\n{* ../../docs_src/sub_applications/tutorial001_py310.py hl[3, 6:8] *}\n\n### Sub-application { #sub-application }\n\nThen, create your sub-application, and its *path operations*.\n\nThis sub-application is just another standard FastAPI application, but this is the one that will be \"mounted\":\n\n{* ../../docs_src/sub_applications/tutorial001_py310.py hl[11, 14:16] *}\n\n### Mount the sub-application { #mount-the-sub-application }\n\nIn your top-level application, `app`, mount the sub-application, `subapi`.\n\nIn this case, it will be mounted at the path `/subapi`:\n\n{* ../../docs_src/sub_applications/tutorial001_py310.py hl[11, 19] *}\n\n### Check the automatic API docs { #check-the-automatic-api-docs }\n\nNow, run the `fastapi` command:\n\n
\n\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nAnd open the docs at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see the automatic API docs for the main app, including only its own _path operations_:\n\n\n\nAnd then, open the docs for the sub-application, at [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).\n\nYou will see the automatic API docs for the sub-application, including only its own _path operations_, all under the correct sub-path prefix `/subapi`:\n\n\n\nIf you try interacting with any of the two user interfaces, they will work correctly, because the browser will be able to talk to each specific app or sub-app.\n\n### Technical Details: `root_path` { #technical-details-root-path }\n\nWhen you mount a sub-application as described above, FastAPI will take care of communicating the mount path for the sub-application using a mechanism from the ASGI specification called a `root_path`.\n\nThat way, the sub-application will know to use that path prefix for the docs UI.\n\nAnd the sub-application could also have its own mounted sub-applications and everything would work correctly, because FastAPI handles all these `root_path`s automatically.\n\nYou will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](behind-a-proxy.md).", "source_type": "doc", "path": "docs/en/docs/advanced/sub-applications.md", "symbol": "Mounting a **FastAPI** application { #mounting-a-fastapi-application }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/sub-applications.md#L5-L67", "start_line": 5, "end_line": 67} {"id": "docs/en/docs/advanced/templates.md::Templates { #templates }::L1", "text": "# Doc: docs/en/docs/advanced/templates.md | Page: Templates { #templates } | Section: Templates { #templates }\n# Templates { #templates }\n\nYou can use any template engine you want with **FastAPI**.\n\nA common choice is Jinja2, the same one used by Flask and other tools.\n\nThere are utilities to configure it easily that you can use directly in your **FastAPI** application (provided by Starlette).", "source_type": "doc", "path": "docs/en/docs/advanced/templates.md", "symbol": "Templates { #templates }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/templates.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/advanced/templates.md::Install dependencies { #install-dependencies }::L9", "text": "# Doc: docs/en/docs/advanced/templates.md | Page: Templates { #templates } | Section: Install dependencies { #install-dependencies }\n## Install dependencies { #install-dependencies }\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and install `jinja2`:\n\n
\n\n```console\n$ pip install jinja2\n\n---> 100%\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/advanced/templates.md", "symbol": "Install dependencies { #install-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/templates.md#L9-L22", "start_line": 9, "end_line": 22} {"id": "docs/en/docs/advanced/templates.md::Using `Jinja2Templates` { #using-jinja2templates }::L23", "text": "# Doc: docs/en/docs/advanced/templates.md | Page: Templates { #templates } | Section: Using `Jinja2Templates` { #using-jinja2templates }\n## Using `Jinja2Templates` { #using-jinja2templates }\n\n* Import `Jinja2Templates`.\n* Create a `templates` object that you can reuse later.\n* Declare a `Request` parameter in the *path operation* that will return a template.\n* Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a \"context\" dictionary with key-value pairs to be used inside of the Jinja2 template.\n\n{* ../../docs_src/templates/tutorial001_py310.py hl[4,11,15:18] *}\n\n/// note\n\nBefore FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter.\n\nAlso, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2.\n\n///\n\n/// tip\n\nBy declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML.\n\n///\n\n/// note | Technical Details\n\nYou could also use `from starlette.templating import Jinja2Templates`.\n\n**FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/templates.md", "symbol": "Using `Jinja2Templates` { #using-jinja2templates }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/templates.md#L23-L53", "start_line": 23, "end_line": 53} {"id": "docs/en/docs/advanced/templates.md::Writing templates { #writing-templates }::L54", "text": "# Doc: docs/en/docs/advanced/templates.md | Page: Templates { #templates } | Section: Writing templates { #writing-templates }\n## Writing templates { #writing-templates }\n\nThen you can write a template at `templates/item.html` with, for example:\n\n```jinja hl_lines=\"7\"\n{!../../docs_src/templates/templates/item.html!}\n```\n\n### Template Context Values { #template-context-values }\n\nIn the HTML that contains:\n\n{% raw %}\n\n```jinja\nItem ID: {{ id }}\n```\n\n{% endraw %}\n\n...it will show the `id` taken from the \"context\" `dict` you passed:\n\n```Python\n{\"id\": id}\n```\n\nFor example, with an ID of `42`, this would render:\n\n```html\nItem ID: 42\n```\n\n### Template `url_for` Arguments { #template-url-for-arguments }\n\nYou can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*.\n\nSo, the section with:\n\n{% raw %}\n\n```jinja\n\n```\n\n{% endraw %}\n\n...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`.\n\nFor example, with an ID of `42`, this would render:\n\n```html\n\n```", "source_type": "doc", "path": "docs/en/docs/advanced/templates.md", "symbol": "Writing templates { #writing-templates }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/templates.md#L54-L107", "start_line": 54, "end_line": 107} {"id": "docs/en/docs/advanced/templates.md::Templates and static files { #templates-and-static-files }::L108", "text": "# Doc: docs/en/docs/advanced/templates.md | Page: Templates { #templates } | Section: Templates and static files { #templates-and-static-files }\n## Templates and static files { #templates-and-static-files }\n\nYou can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name=\"static\"`.\n\n```jinja hl_lines=\"4\"\n{!../../docs_src/templates/templates/item.html!}\n```\n\nIn this example, it would link to a CSS file at `static/styles.css` with:\n\n```CSS hl_lines=\"4\"\n{!../../docs_src/templates/static/styles.css!}\n```\n\nAnd because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`.", "source_type": "doc", "path": "docs/en/docs/advanced/templates.md", "symbol": "Templates and static files { #templates-and-static-files }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/templates.md#L108-L123", "start_line": 108, "end_line": 123} {"id": "docs/en/docs/advanced/templates.md::More details { #more-details }::L124", "text": "# Doc: docs/en/docs/advanced/templates.md | Page: Templates { #templates } | Section: More details { #more-details }\n## More details { #more-details }\n\nFor more details, including how to test templates, check [Starlette's docs on templates](https://www.starlette.dev/templates/).", "source_type": "doc", "path": "docs/en/docs/advanced/templates.md", "symbol": "More details { #more-details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/templates.md#L124-L126", "start_line": 124, "end_line": 126} {"id": "docs/en/docs/advanced/testing-dependencies.md::Testing Dependencies with Overrides { #testing-dependencies-with-overrides }::L1", "text": "# Doc: docs/en/docs/advanced/testing-dependencies.md | Page: Testing Dependencies with Overrides { #testing-dependencies-with-overrides } | Section: Testing Dependencies with Overrides { #testing-dependencies-with-overrides }\n# Testing Dependencies with Overrides { #testing-dependencies-with-overrides }", "source_type": "doc", "path": "docs/en/docs/advanced/testing-dependencies.md", "symbol": "Testing Dependencies with Overrides { #testing-dependencies-with-overrides }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/testing-dependencies.md#L1-L2", "start_line": 1, "end_line": 2} {"id": "docs/en/docs/advanced/testing-dependencies.md::Overriding dependencies during testing { #overriding-dependencies-during-testing }::L3", "text": "# Doc: docs/en/docs/advanced/testing-dependencies.md | Page: Testing Dependencies with Overrides { #testing-dependencies-with-overrides } | Section: Overriding dependencies during testing { #overriding-dependencies-during-testing }\n## Overriding dependencies during testing { #overriding-dependencies-during-testing }\n\nThere are some scenarios where you might want to override a dependency during testing.\n\nYou don't want the original dependency to run (nor any of the sub-dependencies it might have).\n\nInstead, you want to provide a different dependency that will be used only during tests (possibly only some specific tests), and will provide a value that can be used where the value of the original dependency was used.\n\n### Use cases: external service { #use-cases-external-service }\n\nAn example could be that you have an external authentication provider that you need to call.\n\nYou send it a token and it returns an authenticated user.\n\nThis provider might be charging you per request, and calling it might take some extra time than if you had a fixed mock user for tests.\n\nYou probably want to test the external provider once, but not necessarily call it for every test that runs.\n\nIn this case, you can override the dependency that calls that provider, and use a custom dependency that returns a mock user, only for your tests.\n\n### Use the `app.dependency_overrides` attribute { #use-the-app-dependency-overrides-attribute }\n\nFor these cases, your **FastAPI** application has an attribute `app.dependency_overrides`, it is a simple `dict`.\n\nTo override a dependency for testing, you put as a key the original dependency (a function), and as the value, your dependency override (another function).\n\nAnd then **FastAPI** will call that override instead of the original dependency.\n\n{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *}\n\n/// tip\n\nYou can set a dependency override for a dependency used anywhere in your **FastAPI** application.\n\nThe original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc.\n\nFastAPI will still be able to override it.\n\n///\n\nThen you can reset your overrides (remove them) by setting `app.dependency_overrides` to be an empty `dict`:\n\n```Python\napp.dependency_overrides = {}\n```\n\n/// tip\n\nIf you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/testing-dependencies.md", "symbol": "Overriding dependencies during testing { #overriding-dependencies-during-testing }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/testing-dependencies.md#L3-L53", "start_line": 3, "end_line": 53} {"id": "docs/en/docs/advanced/testing-events.md::Testing Events: lifespan and startup - shutdown { #testing-events-lifespan-and-startup-shutdown }::L1", "text": "# Doc: docs/en/docs/advanced/testing-events.md | Page: Testing Events: lifespan and startup - shutdown { #testing-events-lifespan-and-startup-shutdown } | Section: Testing Events: lifespan and startup - shutdown { #testing-events-lifespan-and-startup-shutdown }\n# Testing Events: lifespan and startup - shutdown { #testing-events-lifespan-and-startup-shutdown }\n\nWhen you need `lifespan` to run in your tests, you can use the `TestClient` with a `with` statement:\n\n{* ../../docs_src/app_testing/tutorial004_py310.py hl[9:15,18,27:28,30:32,41:43] *}\n\n\nYou can read more details about the [\"Running lifespan in tests in the official Starlette documentation site.\"](https://www.starlette.dev/lifespan/#running-lifespan-in-tests)\n\nFor the deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:\n\n{* ../../docs_src/app_testing/tutorial003_py310.py hl[9:12,20:24] *}", "source_type": "doc", "path": "docs/en/docs/advanced/testing-events.md", "symbol": "Testing Events: lifespan and startup - shutdown { #testing-events-lifespan-and-startup-shutdown }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/testing-events.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/advanced/testing-websockets.md::Testing WebSockets { #testing-websockets }::L1", "text": "# Doc: docs/en/docs/advanced/testing-websockets.md | Page: Testing WebSockets { #testing-websockets } | Section: Testing WebSockets { #testing-websockets }\n# Testing WebSockets { #testing-websockets }\n\nYou can use the same `TestClient` to test WebSockets.\n\nFor this, you use the `TestClient` in a `with` statement, connecting to the WebSocket:\n\n{* ../../docs_src/app_testing/tutorial002_py310.py hl[27:31] *}\n\n/// note\n\nFor more details, check Starlette's documentation for [testing WebSockets](https://www.starlette.dev/testclient/#testing-websocket-sessions).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/testing-websockets.md", "symbol": "Testing WebSockets { #testing-websockets }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/testing-websockets.md#L1-L13", "start_line": 1, "end_line": 13} {"id": "docs/en/docs/advanced/using-request-directly.md::Using the Request Directly { #using-the-request-directly }::L1", "text": "# Doc: docs/en/docs/advanced/using-request-directly.md | Page: Using the Request Directly { #using-the-request-directly } | Section: Using the Request Directly { #using-the-request-directly }\n# Using the Request Directly { #using-the-request-directly }\n\nUp to now, you have been declaring the parts of the request that you need with their types.\n\nTaking data from:\n\n* The path as parameters.\n* Headers.\n* Cookies.\n* etc.\n\nAnd by doing so, **FastAPI** is validating that data, converting it and generating documentation for your API automatically.\n\nBut there are situations where you might need to access the `Request` object directly.", "source_type": "doc", "path": "docs/en/docs/advanced/using-request-directly.md", "symbol": "Using the Request Directly { #using-the-request-directly }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/using-request-directly.md#L1-L15", "start_line": 1, "end_line": 15} {"id": "docs/en/docs/advanced/using-request-directly.md::Details about the `Request` object { #details-about-the-request-object }::L16", "text": "# Doc: docs/en/docs/advanced/using-request-directly.md | Page: Using the Request Directly { #using-the-request-directly } | Section: Details about the `Request` object { #details-about-the-request-object }\n## Details about the `Request` object { #details-about-the-request-object }\n\nAs **FastAPI** is actually **Starlette** underneath, with a layer of several tools on top, you can use Starlette's [`Request`](https://www.starlette.dev/requests/) object directly when you need to.\n\nIt would also mean that if you get data from the `Request` object directly (for example, read the body) it won't be validated, converted or documented (with OpenAPI, for the automatic API user interface) by FastAPI.\n\nAlthough any other parameter declared normally (for example, the body with a Pydantic model) would still be validated, converted, annotated, etc.\n\nBut there are specific cases where it's useful to get the `Request` object.", "source_type": "doc", "path": "docs/en/docs/advanced/using-request-directly.md", "symbol": "Details about the `Request` object { #details-about-the-request-object }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/using-request-directly.md#L16-L25", "start_line": 16, "end_line": 25} {"id": "docs/en/docs/advanced/using-request-directly.md::Use the `Request` object directly { #use-the-request-object-directly }::L26", "text": "# Doc: docs/en/docs/advanced/using-request-directly.md | Page: Using the Request Directly { #using-the-request-directly } | Section: Use the `Request` object directly { #use-the-request-object-directly }\n## Use the `Request` object directly { #use-the-request-object-directly }\n\nLet's imagine you want to get the client's IP address/host inside of your *path operation function*.\n\nFor that you need to access the request directly.\n\n{* ../../docs_src/using_request_directly/tutorial001_py310.py hl[1,7:8] *}\n\nBy declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter.\n\n/// tip\n\nNote that in this case, we are declaring a path parameter beside the request parameter.\n\nSo, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI.\n\nThe same way, you can declare any other parameter as normally, and additionally, get the `Request` too.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/using-request-directly.md", "symbol": "Use the `Request` object directly { #use-the-request-object-directly }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/using-request-directly.md#L26-L45", "start_line": 26, "end_line": 45} {"id": "docs/en/docs/advanced/using-request-directly.md::`Request` documentation { #request-documentation }::L46", "text": "# Doc: docs/en/docs/advanced/using-request-directly.md | Page: Using the Request Directly { #using-the-request-directly } | Section: `Request` documentation { #request-documentation }\n## `Request` documentation { #request-documentation }\n\nYou can read more details about the [`Request` object in the official Starlette documentation site](https://www.starlette.dev/requests/).\n\n/// note | Technical Details\n\nYou could also use `from starlette.requests import Request`.\n\n**FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/using-request-directly.md", "symbol": "`Request` documentation { #request-documentation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/using-request-directly.md#L46-L56", "start_line": 46, "end_line": 56} {"id": "docs/en/docs/advanced/websockets.md::WebSockets { #websockets }::L1", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: WebSockets { #websockets }\n# WebSockets { #websockets }\n\nYou can use [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) with **FastAPI**.", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "WebSockets { #websockets }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/advanced/websockets.md::Install `websockets` { #install-websockets }::L5", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: Install `websockets` { #install-websockets }\n## Install `websockets` { #install-websockets }\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and install `websockets` (a Python library that makes it easy to use the \"WebSocket\" protocol):\n\n
\n\n```console\n$ pip install websockets\n\n---> 100%\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "Install `websockets` { #install-websockets }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L5-L18", "start_line": 5, "end_line": 18} {"id": "docs/en/docs/advanced/websockets.md::WebSockets client { #websockets-client }::L19", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: WebSockets client { #websockets-client }\n## WebSockets client { #websockets-client }\n\n### In production { #in-production }\n\nIn your production system, you probably have a frontend created with a modern framework like React, Vue.js or Angular.\n\nAnd to communicate using WebSockets with your backend you would probably use your frontend's utilities.\n\nOr you might have a native mobile application that communicates with your WebSocket backend directly, in native code.\n\nOr you might have any other way to communicate with the WebSocket endpoint.\n\n---\n\nBut for this example, we'll use a very simple HTML document with some JavaScript, all inside a long string.\n\nThis, of course, is not optimal and you wouldn't use it for production.\n\nIn production you would have one of the options above.\n\nBut it's the simplest way to focus on the server-side of WebSockets and have a working example:\n\n{* ../../docs_src/websockets_/tutorial001_py310.py hl[2,6:38,41:43] *}", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "WebSockets client { #websockets-client }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L19-L42", "start_line": 19, "end_line": 42} {"id": "docs/en/docs/advanced/websockets.md::Create a `websocket` { #create-a-websocket }::L43", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: Create a `websocket` { #create-a-websocket }\n## Create a `websocket` { #create-a-websocket }\n\nIn your **FastAPI** application, create a `websocket`:\n\n{* ../../docs_src/websockets_/tutorial001_py310.py hl[1,46:47] *}\n\n/// note | Technical Details\n\nYou could also use `from starlette.websockets import WebSocket`.\n\n**FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "Create a `websocket` { #create-a-websocket }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L43-L56", "start_line": 43, "end_line": 56} {"id": "docs/en/docs/advanced/websockets.md::Await for messages and send messages { #await-for-messages-and-send-messages }::L57", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: Await for messages and send messages { #await-for-messages-and-send-messages }\n## Await for messages and send messages { #await-for-messages-and-send-messages }\n\nIn your WebSocket route you can `await` for messages and send messages.\n\n{* ../../docs_src/websockets_/tutorial001_py310.py hl[48:52] *}\n\nYou can receive and send binary, text, and JSON data.", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "Await for messages and send messages { #await-for-messages-and-send-messages }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L57-L64", "start_line": 57, "end_line": 64} {"id": "docs/en/docs/advanced/websockets.md::Try it { #try-it }::L65", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: Try it { #try-it }\n## Try it { #try-it }\n\nPut your code in a file `main.py` and then run your application:\n\n
\n\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nOpen your browser at [http://127.0.0.1:8000](http://127.0.0.1:8000).\n\nYou will see a simple page like:\n\n\n\nYou can type messages in the input box, and send them:\n\n\n\nAnd your **FastAPI** application with WebSockets will respond back:\n\n\n\nYou can send (and receive) many messages:\n\n\n\nAnd all of them will use the same WebSocket connection.", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "Try it { #try-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L65-L98", "start_line": 65, "end_line": 98} {"id": "docs/en/docs/advanced/websockets.md::Using `Depends` and others { #using-depends-and-others }::L99", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: Using `Depends` and others { #using-depends-and-others }\n## Using `Depends` and others { #using-depends-and-others }\n\nIn WebSocket endpoints you can import from `fastapi` and use:\n\n* `Depends`\n* `Security`\n* `Cookie`\n* `Header`\n* `Path`\n* `Query`\n\nThey work the same way as for other FastAPI endpoints/*path operations*:\n\n{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}\n\n/// note\n\nAs this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`.\n\nYou can use a closing code from the [valid codes defined in the specification](https://tools.ietf.org/html/rfc6455#section-7.4.1).\n\n///\n\n### Try the WebSockets with dependencies { #try-the-websockets-with-dependencies }\n\nRun your application:\n\n
\n\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nOpen your browser at [http://127.0.0.1:8000](http://127.0.0.1:8000).\n\nThere you can set:\n\n* The \"Item ID\", used in the path.\n* The \"Token\" used as a query parameter.\n\n/// tip\n\nNotice that the query `token` will be handled by a dependency.\n\n///\n\nWith that you can connect the WebSocket and then send and receive messages:\n\n", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "Using `Depends` and others { #using-depends-and-others }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L99-L152", "start_line": 99, "end_line": 152} {"id": "docs/en/docs/advanced/websockets.md::Handling disconnections and multiple clients { #handling-disconnections-and-multiple-clients }::L153", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: Handling disconnections and multiple clients { #handling-disconnections-and-multiple-clients }\n## Handling disconnections and multiple clients { #handling-disconnections-and-multiple-clients }\n\nWhen a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example.\n\n{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}\n\nTo try it out:\n\n* Open the app with several browser tabs.\n* Write messages from them.\n* Then close one of the tabs.\n\nThat will raise the `WebSocketDisconnect` exception, and all the other clients will receive a message like:\n\n```\nClient #1596980209979 left the chat\n```\n\n/// tip\n\nThe app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.\n\nBut keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.\n\nIf you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check [encode/broadcaster](https://github.com/encode/broadcaster).\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "Handling disconnections and multiple clients { #handling-disconnections-and-multiple-clients }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L153-L180", "start_line": 153, "end_line": 180} {"id": "docs/en/docs/advanced/websockets.md::More info { #more-info }::L181", "text": "# Doc: docs/en/docs/advanced/websockets.md | Page: WebSockets { #websockets } | Section: More info { #more-info }\n## More info { #more-info }\n\nTo learn more about the options, check Starlette's documentation for:\n\n* [The `WebSocket` class](https://www.starlette.dev/websockets/).\n* [Class-based WebSocket handling](https://www.starlette.dev/endpoints/#websocketendpoint).", "source_type": "doc", "path": "docs/en/docs/advanced/websockets.md", "symbol": "More info { #more-info }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/websockets.md#L181-L186", "start_line": 181, "end_line": 186} {"id": "docs/en/docs/advanced/wsgi.md::Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others }::L1", "text": "# Doc: docs/en/docs/advanced/wsgi.md | Page: Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others } | Section: Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others }\n# Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others }\n\nYou can mount WSGI applications as you saw with [Sub Applications - Mounts](sub-applications.md), [Behind a Proxy](behind-a-proxy.md).\n\nFor that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc.", "source_type": "doc", "path": "docs/en/docs/advanced/wsgi.md", "symbol": "Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/wsgi.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/advanced/wsgi.md::Using `WSGIMiddleware` { #using-wsgimiddleware }::L7", "text": "# Doc: docs/en/docs/advanced/wsgi.md | Page: Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others } | Section: Using `WSGIMiddleware` { #using-wsgimiddleware }\n## Using `WSGIMiddleware` { #using-wsgimiddleware }\n\n/// note\n\nThis requires installing `a2wsgi` for example with `pip install a2wsgi`.\n\n///\n\nYou need to import `WSGIMiddleware` from `a2wsgi`.\n\nThen wrap the WSGI (e.g. Flask) app with the middleware.\n\nAnd then mount that under a path.\n\n{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}\n\n/// note\n\nPreviously, it was recommended to use `WSGIMiddleware` from `fastapi.middleware.wsgi`, but it is now deprecated.\n\nIt's advised to use the `a2wsgi` package instead. The usage remains the same.\n\nJust ensure that you have the `a2wsgi` package installed and import `WSGIMiddleware` correctly from `a2wsgi`.\n\n///", "source_type": "doc", "path": "docs/en/docs/advanced/wsgi.md", "symbol": "Using `WSGIMiddleware` { #using-wsgimiddleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/wsgi.md#L7-L32", "start_line": 7, "end_line": 32} {"id": "docs/en/docs/advanced/wsgi.md::Check it { #check-it }::L33", "text": "# Doc: docs/en/docs/advanced/wsgi.md | Page: Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others } | Section: Check it { #check-it }\n## Check it { #check-it }\n\nNow, every request under the path `/v1/` will be handled by the Flask application.\n\nAnd the rest will be handled by **FastAPI**.\n\nIf you run it and go to [http://localhost:8000/v1/](http://localhost:8000/v1/) you will see the response from Flask:\n\n```txt\nHello, World from Flask!\n```\n\nAnd if you go to [http://localhost:8000/v2](http://localhost:8000/v2) you will see the response from FastAPI:\n\n```JSON\n{\n \"message\": \"Hello World\"\n}\n```", "source_type": "doc", "path": "docs/en/docs/advanced/wsgi.md", "symbol": "Check it { #check-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/advanced/wsgi.md#L33-L51", "start_line": 33, "end_line": 51} {"id": "docs/en/docs/alternatives.md::Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons }::L1", "text": "# Doc: docs/en/docs/alternatives.md | Page: Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons } | Section: Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons }\n# Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons }\n\nWhat inspired **FastAPI**, how it compares to alternatives and what it learned from them.", "source_type": "doc", "path": "docs/en/docs/alternatives.md", "symbol": "Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/alternatives.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/alternatives.md::Intro { #intro }::L5", "text": "# Doc: docs/en/docs/alternatives.md | Page: Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons } | Section: Intro { #intro }\n## Intro { #intro }\n\n**FastAPI** wouldn't exist if not for the previous work of others.\n\nThere have been many tools created before that have helped inspire its creation.\n\nI have been avoiding the creation of a new framework for several years. First I tried to solve all the features covered by **FastAPI** using many different frameworks, plug-ins, and tools.\n\nBut at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).", "source_type": "doc", "path": "docs/en/docs/alternatives.md", "symbol": "Intro { #intro }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/alternatives.md#L5-L14", "start_line": 5, "end_line": 14} {"id": "docs/en/docs/alternatives.md::Previous tools { #previous-tools }::L15", "text": "# Doc: docs/en/docs/alternatives.md | Page: Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons } | Section: Previous tools { #previous-tools }\n## Previous tools { #previous-tools }\n\n### [Django](https://www.djangoproject.com/) { #django }\n\nIt's the most popular Python framework and is widely trusted. It is used to build systems like Instagram.\n\nIt's relatively tightly coupled with relational databases (like MySQL or PostgreSQL), so, having a NoSQL database (like Couchbase, MongoDB, Cassandra, etc) as the main store engine is not very easy.\n\nIt was created to generate the HTML in the backend, not to create APIs used by a modern frontend (like React, Vue.js and Angular) or by other systems (like IoT devices) communicating with it.\n\n### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }\n\nDjango REST Framework was created to be a flexible toolkit for building Web APIs using Django underneath, to improve its API capabilities.\n\nIt is used by many companies including Mozilla, Red Hat and Eventbrite.\n\nIt was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired \"the search for\" **FastAPI**.\n\n/// note\n\nDjango REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.\n\n///\n\n/// tip | Inspired **FastAPI** to\n\nHave an automatic API documentation web user interface.\n\n///\n\n### [Flask](https://flask.palletsprojects.com) { #flask }\n\nFlask is a \"microframework\", it doesn't include database integrations nor many of the things that come by default in Django.\n\nThis simplicity and flexibility allow doing things like using NoSQL databases as the main data storage system.\n\nAs it is very simple, it's relatively intuitive to learn, although the documentation gets somewhat technical at some points.\n\nIt is also commonly used for other applications that don't necessarily need a database, user management, or any of the many features that come pre-built in Django. Although many of these features can be added with plug-ins.\n\nThis decoupling of parts, and being a \"microframework\" that could be extended to cover exactly what is needed was a key feature that I wanted to keep.\n\nGiven the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a \"Django REST Framework\" for Flask.\n\n/// tip | Inspired **FastAPI** to\n\nBe a micro-framework. Making it easy to mix and match the tools and parts needed.\n\nHave a simple and easy to use routing system.\n\n///\n\n### [Requests](https://requests.readthedocs.io) { #requests }\n\n**FastAPI** is not actually an alternative to **Requests**. Their scope is very different.\n\nIt would actually be common to use Requests *inside* of a FastAPI application.\n\nBut still, FastAPI got quite some inspiration from Requests.\n\n**Requests** is a library to *interact* with APIs (as a client), while **FastAPI** is a library to *build* APIs (as a server).\n\nThey are, more or less, at opposite ends, complementing each other.\n\nRequests has a very simple and intuitive design, it's very easy to use, with sensible defaults. But at the same time, it's very powerful and customizable.\n\nThat's why, as said in the official website:\n\n> Requests is one of the most downloaded Python packages of all time\n\nThe way you use it is very simple. For example, to do a `GET` request, you would write:\n\n```Python\nresponse = requests.get(\"http://example.com/some/url\")\n```\n\nThe FastAPI counterpart API *path operation* could look like:\n\n```Python hl_lines=\"1\"\n@app.get(\"/some/url\")\ndef read_url():\n return {\"message\": \"Hello World\"}\n```\n\nSee the similarities in `requests.get(...)` and `@app.get(...)`.\n\n/// tip | Inspired **FastAPI** to\n\n* Have a simple and intuitive API.\n* Use HTTP method names (operations) directly, in a straightforward and intuitive way.\n* Have sensible defaults, but powerful customizations.\n\n///\n\n### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }\n\nThe main feature I wanted from Django REST Framework was the automatic API documentation.\n\nThen I found that there was a standard to document APIs, using JSON (or YAML, an extension of JSON) called Swagger.\n\nAnd there was a web user interface for Swagger APIs already created. So, being able to generate Swagger documentation for an API would allow using this web user interface automatically.\n\nAt some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI.\n\nThat's why when talking about version 2.0 it's common to say \"Swagger\", and for version 3+ \"OpenAPI\".\n\n/// tip | Inspired **FastAPI** to\n\nAdopt and use an open standard for API specifications, instead of a custom schema.\n\nAnd integrate standards-based user interface tools:\n\n* [Swagger UI](https://github.com/swagger-api/swagger-ui)\n* [ReDoc](https://github.com/Rebilly/ReDoc)\n\nThese two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**).\n\n///\n\n### Flask REST frameworks { #flask-rest-frameworks }\n\nThere are several Flask REST frameworks, but after investing the time and work into investigating them, I found that many are discontinued or abandoned, with several standing issues that made them unfit.\n\n### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }\n\nOne of the main features needed by API systems is data \"serialization\" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.\n\nAnother big feature needed by APIs is data validation, making sure that the data is valid, given certain parameters. For example, that some field is an `int`, and not some random string. This is especially useful for incoming data.\n\nWithout a data validation system, you would have to do all the checks by hand, in code.\n\nThese features are what Marshmallow was built to provide. It is a great library, and I have used it a lot before.\n\nBut it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow.\n\n/// tip | Inspired **FastAPI** to\n\nUse code to define \"schemas\" that provide data types and validation, automatically.\n\n///\n\n### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }\n\nAnother big feature required by APIs is parsing data from incoming requests.\n\nWebargs is a tool that was made to provide that on top of several frameworks, including Flask.\n\nIt uses Marshmallow underneath to do the data validation. And it was created by the same developers.\n\nIt's a great tool and I have used it a lot too, before having **FastAPI**.\n\n/// note\n\nWebargs was created by the same Marshmallow developers.\n\n///\n\n/// tip | Inspired **FastAPI** to\n\nHave automatic validation of incoming request data.\n\n///\n\n### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }\n\nMarshmallow and Webargs provide validation, parsing and serialization as plug-ins.\n\nBut documentation is still missing. Then APISpec was created.\n\nIt is a plug-in for many frameworks (and there's a plug-in for Starlette too).\n\nThe way it works is that you write the definition of the schema using YAML format inside the docstring of each function handling a route.\n\nAnd it generates OpenAPI schemas.\n\nThat's how it works in Flask, Starlette, Responder, etc.\n\nBut then, we have again the problem of having a micro-syntax, inside of a Python string (a big YAML).\n\nThe editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete.\n\n/// note\n\nAPISpec was created by the same Marshmallow developers.\n\n///\n\n/// tip | Inspired **FastAPI** to\n\nSupport the open standard for APIs, OpenAPI.\n\n///\n\n### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }\n\nIt's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec.\n\nIt uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec.\n\nIt's a great tool, very underrated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract.\n\nThis solved having to write YAML (another syntax) inside of Python docstrings.\n\nThis combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**.\n\nUsing it led to the creation of several Flask full-stack generators. These are the main stacks I (and several external teams) have been using up to now:\n\n* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)\n* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)\n* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)\n\nAnd these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md).\n\n/// note\n\nFlask-apispec was created by the same Marshmallow developers.\n\n///\n\n/// tip | Inspired **FastAPI** to\n\nGenerate the OpenAPI schema automatically, from the same code that defines serialization and validation.\n\n///\n\n### [NestJS](https://nestjs.com/) (and [Angular](https://angular.io/)) { #nestjs-and-angular }\n\nThis isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework inspired by Angular.\n\nIt achieves something somewhat similar to what can be done with Flask-apispec.\n\nIt has an integrated dependency injection system, inspired by Angular 2. It requires pre-registering the \"injectables\" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition.\n\nAs the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good.\n\nBut as TypeScript data is not preserved after compilation to JavaScript, it cannot rely on the types to define validation, serialization and documentation at the same time. Due to this and some design decisions, to get validation, serialization and automatic schema generation, it's needed to add decorators in many places. So, it becomes quite verbose.\n\nIt can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated.\n\n/// tip | Inspired **FastAPI** to\n\nUse Python types to have great editor support.\n\nHave a powerful dependency injection system. Find a way to minimize code repetition.\n\n///\n\n### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }\n\nIt was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask.\n\n/// note | Technical Details\n\nIt used [`uvloop`](https://github.com/MagicStack/uvloop) instead of the default Python `asyncio` loop. That's what made it so fast.\n\nIt clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.\n\n///\n\n/// tip | Inspired **FastAPI** to\n\nFind a way to have a crazy performance.\n\nThat's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).\n\n///\n\n### [Falcon](https://falconframework.org/) { #falcon }\n\nFalcon is another high performance Python framework, it is designed to be minimal, and work as the foundation of other frameworks like Hug.\n\nIt is designed to have functions that receive two parameters, one \"request\" and one \"response\". Then you \"read\" parts from the request, and \"write\" parts to the response. Because of this design, it is not possible to declare request parameters and bodies with standard Python type hints as function parameters.\n\nSo, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters.\n\n/// tip | Inspired **FastAPI** to\n\nFind ways to get great performance.\n\nAlong with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.\n\nAlthough in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.\n\n///\n\n### [Molten](https://moltenframework.com/) { #molten }\n\nI discovered Molten in the first stages of building **FastAPI**. And it has quite similar ideas:\n\n* Based on Python type hints.\n* Validation and documentation from these types.\n* Dependency Injection system.\n\nIt doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily.\n\nIt requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high performance provided by tools like Uvicorn, Starlette and Sanic.\n\nThe dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one \"component\" that provides a certain type.\n\nRoutes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled.\n\n/// tip | Inspired **FastAPI** to\n\nDefine extra validations for data types using the \"default\" value of model attributes. This improves editor support, and it was not available in Pydantic before.\n\nThis actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).\n\n///\n\n### [Hug](https://github.com/hugapi/hug) { #hug }\n\nHug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same.\n\nIt used custom types in its declarations instead of standard Python types, but it was still a huge step forward.\n\nIt also was one of the first frameworks to generate a custom schema declaring the whole API in JSON.\n\nIt was not based on a standard like OpenAPI and JSON Schema. So it wouldn't be straightforward to integrate it with other tools, like Swagger UI. But again, it was a very innovative idea.\n\nIt has an interesting, uncommon feature: using the same framework, it's possible to create APIs and also CLIs.\n\nAs it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too.\n\n/// note\n\nHug was created by Timothy Crosley, the same creator of [`isort`](https://github.com/timothycrosley/isort), a great tool to automatically sort imports in Python files.\n\n///\n\n/// tip | Ideas inspiring **FastAPI**\n\nHug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.\n\nHug helped inspire **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.\n\nHug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.\n\n///\n\n### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }\n\nRight before deciding to build **FastAPI** I found **APIStar** server. It had almost everything I was looking for and had a great design.\n\nIt was one of the first implementations of a framework using Python type hints to declare parameters and requests that I ever saw (before NestJS and Molten). I found it more or less at the same time as Hug. But APIStar used the OpenAPI standard.\n\nIt had automatic data validation, data serialization and OpenAPI schema generation based on the same type hints in several places.\n\nBody schema definitions didn't use the same Python type hints like Pydantic, it was a bit more similar to Marshmallow, so, editor support wouldn't be as good, but still, APIStar was the best available option.\n\nIt had the best performance benchmarks at the time (only surpassed by Starlette).\n\nAt first, it didn't have an automatic API documentation web UI, but I knew I could add Swagger UI to it.\n\nIt had a dependency injection system. It required pre-registration of components, as other tools discussed above. But still, it was a great feature.\n\nI was never able to use it in a full project, as it didn't have security integration, so, I couldn't replace all the features I was having with the full-stack generators based on Flask-apispec. I had in my backlog of projects to create a pull request adding that functionality.\n\nBut then, the project's focus shifted.\n\nIt was no longer an API web framework, as the creator needed to focus on Starlette.\n\nNow APIStar is a set of tools to validate OpenAPI specifications, not a web framework.\n\n/// note\n\nAPIStar was created by Tom Christie. The same guy that created:\n\n* Django REST Framework\n* Starlette (on which **FastAPI** is based)\n* Uvicorn (used by Starlette and **FastAPI**)\n\n///\n\n/// tip | Inspired **FastAPI** to\n\nExist.\n\nThe idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.\n\nAnd after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.\n\nThen APIStar stopped existing as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.\n\nI consider **FastAPI** a \"spiritual successor\" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.\n\n///", "source_type": "doc", "path": "docs/en/docs/alternatives.md", "symbol": "Previous tools { #previous-tools }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/alternatives.md#L15-L401", "start_line": 15, "end_line": 401} {"id": "docs/en/docs/alternatives.md::Used by **FastAPI** { #used-by-fastapi }::L402", "text": "# Doc: docs/en/docs/alternatives.md | Page: Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons } | Section: Used by **FastAPI** { #used-by-fastapi }\n## Used by **FastAPI** { #used-by-fastapi }\n\n### [Pydantic](https://docs.pydantic.dev/) { #pydantic }\n\nPydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints.\n\nThat makes it extremely intuitive.\n\nIt is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great.\n\n/// tip | **FastAPI** uses it to\n\nHandle all the data validation, data serialization and automatic model documentation (based on JSON Schema).\n\n**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.\n\n///\n\n### [Starlette](https://www.starlette.dev/) { #starlette }\n\nStarlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services.\n\nIt is very simple and intuitive. It's designed to be easily extensible, and have modular components.\n\nIt has:\n\n* Seriously impressive performance.\n* WebSocket support.\n* In-process background tasks.\n* Startup and shutdown events.\n* Test client built on HTTPX.\n* CORS, GZip, Static Files, Streaming responses.\n* Session and Cookie support.\n* 100% test coverage.\n* 100% type annotated codebase.\n* Few hard dependencies.\n\nStarlette is currently the fastest Python framework tested. Only surpassed by Uvicorn, which is not a framework, but a server.\n\nStarlette provides all the basic web microframework functionality.\n\nBut it doesn't provide automatic data validation, serialization or documentation.\n\nThat's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc.\n\n/// note | Technical Details\n\nASGI is a new \"standard\" being developed by Django core team members. It is still not a \"Python standard\" (a PEP), although they are in the process of doing that.\n\nNevertheless, it is already being used as a \"standard\" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.\n\n///\n\n/// tip | **FastAPI** uses it to\n\nHandle all the core web parts. Adding features on top.\n\nThe class `FastAPI` itself inherits directly from the class `Starlette`.\n\nSo, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.\n\n///\n\n### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }\n\nUvicorn is a lightning-fast ASGI server, built on uvloop and httptools.\n\nIt is not a web framework, but a server. For example, it doesn't provide tools for routing by paths. That's something that a framework like Starlette (or **FastAPI**) would provide on top.\n\nIt is the recommended server for Starlette and **FastAPI**.\n\n/// tip | **FastAPI** recommends it as\n\nThe main web server to run **FastAPI** applications.\n\nYou can also use the `--workers` command line option to have an asynchronous multi-process server.\n\nCheck more details in the [Deployment](deployment/index.md) section.\n\n///", "source_type": "doc", "path": "docs/en/docs/alternatives.md", "symbol": "Used by **FastAPI** { #used-by-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/alternatives.md#L402-L482", "start_line": 402, "end_line": 482} {"id": "docs/en/docs/alternatives.md::Benchmarks and speed { #benchmarks-and-speed }::L483", "text": "# Doc: docs/en/docs/alternatives.md | Page: Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons } | Section: Benchmarks and speed { #benchmarks-and-speed }\n## Benchmarks and speed { #benchmarks-and-speed }\n\nTo understand, compare, and see the difference between Uvicorn, Starlette and FastAPI, check the section about [Benchmarks](benchmarks.md).", "source_type": "doc", "path": "docs/en/docs/alternatives.md", "symbol": "Benchmarks and speed { #benchmarks-and-speed }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/alternatives.md#L483-L485", "start_line": 483, "end_line": 485} {"id": "docs/en/docs/async.md::Concurrency and async / await { #concurrency-and-async-await }::L1", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: Concurrency and async / await { #concurrency-and-async-await }\n# Concurrency and async / await { #concurrency-and-async-await }\n\nDetails about the `async def` syntax for *path operation functions* and some background about asynchronous code, concurrency, and parallelism.", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "Concurrency and async / await { #concurrency-and-async-await }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/async.md::In a hurry? { #in-a-hurry }::L5", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: In a hurry? { #in-a-hurry }\n## In a hurry? { #in-a-hurry }\n\nTL;DR:\n\nIf you are using third party libraries that tell you to call them with `await`, like:\n\n```Python\nresults = await some_library()\n```\n\nThen, declare your *path operation functions* with `async def` like:\n\n```Python hl_lines=\"2\"\n@app.get('/')\nasync def read_results():\n results = await some_library()\n return results\n```\n\n/// note\n\nYou can only use `await` inside of functions created with `async def`.\n\n///\n\n---\n\nIf you are using a third party library that communicates with something (a database, an API, the file system, etc.) and doesn't have support for using `await`, (this is currently the case for most database libraries), then declare your *path operation functions* as normally, with just `def`, like:\n\n```Python hl_lines=\"2\"\n@app.get('/')\ndef results():\n results = some_library()\n return results\n```\n\n---\n\nIf your application (somehow) doesn't have to communicate with anything else and wait for it to respond, use `async def`, even if you don't need to use `await` inside.\n\n---\n\nIf you just don't know, use normal `def`.\n\n---\n\n**Note**: You can mix `def` and `async def` in your *path operation functions* as much as you need and define each one using the best option for you. FastAPI will do the right thing with them.\n\nAnyway, in any of the cases above, FastAPI will still work asynchronously and be extremely fast.\n\nBut by following the steps above, it will be able to do some performance optimizations.", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "In a hurry? { #in-a-hurry }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L5-L56", "start_line": 5, "end_line": 56} {"id": "docs/en/docs/async.md::Technical Details { #technical-details }::L57", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: Technical Details { #technical-details }\n## Technical Details { #technical-details }\n\nModern versions of Python have support for **\"asynchronous code\"** using something called **\"coroutines\"**, with **`async` and `await`** syntax.\n\nLet's see that phrase by parts in the sections below:\n\n* **Asynchronous Code**\n* **`async` and `await`**\n* **Coroutines**", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "Technical Details { #technical-details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L57-L66", "start_line": 57, "end_line": 66} {"id": "docs/en/docs/async.md::Asynchronous Code { #asynchronous-code }::L67", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: Asynchronous Code { #asynchronous-code }\n## Asynchronous Code { #asynchronous-code }\n\nAsynchronous code just means that the language 💬 has a way to tell the computer / program 🤖 that at some point in the code, it 🤖 will have to wait for *something else* to finish somewhere else. Let's say that *something else* is called \"slow-file\" 📝.\n\nSo, during that time, the computer can go and do some other work, while \"slow-file\" 📝 finishes.\n\nThen the computer / program 🤖 will come back every time it has a chance because it's waiting again, or whenever it 🤖 finishes all the work it had at that point. And it 🤖 will see if any of the tasks it was waiting for have already finished, doing whatever it had to do.\n\nNext, it 🤖 takes the first task to finish (let's say, our \"slow-file\" 📝) and continues whatever it had to do with it.\n\nThat \"wait for something else\" normally refers to I/O operations that are relatively \"slow\" (compared to the speed of the processor and the RAM memory), like waiting for:\n\n* the data from the client to be sent through the network\n* the data sent by your program to be received by the client through the network\n* the contents of a file on the disk to be read by the system and given to your program\n* the contents your program gave to the system to be written to disk\n* a remote API operation\n* a database operation to finish\n* a database query to return the results\n* etc.\n\nAs the execution time is consumed mostly by waiting for I/O operations, they call them \"I/O bound\" operations.\n\nIt's called \"asynchronous\" because the computer / program doesn't have to be \"synchronized\" with the slow task, waiting for the exact moment that the task finishes, while doing nothing, to be able to take the task result and continue the work.\n\nInstead of that, by being an \"asynchronous\" system, once finished, the task can wait in line a little bit (some microseconds) for the computer / program to finish whatever it went to do, and then come back to take the results and continue working with them.\n\nFor \"synchronous\" (contrary to \"asynchronous\") they commonly also use the term \"sequential\", because the computer / program follows all the steps in sequence before switching to a different task, even if those steps involve waiting.\n\n### Concurrency and Burgers { #concurrency-and-burgers }\n\nThis idea of **asynchronous** code described above is also sometimes called **\"concurrency\"**. It is different from **\"parallelism\"**.\n\n**Concurrency** and **parallelism** both relate to \"different things happening more or less at the same time\".\n\nBut the details between *concurrency* and *parallelism* are quite different.\n\nTo see the difference, imagine the following story about burgers:\n\n### Concurrent Burgers { #concurrent-burgers }\n\nYou go with your crush to get fast food, you stand in line while the cashier takes the orders from the people in front of you. 😍\n\n\n\nThen it's your turn, you place your order of 2 very fancy burgers for your crush and you. 🍔🍔\n\n\n\nThe cashier says something to the cook in the kitchen so they know they have to prepare your burgers (even though they are currently preparing the ones for the previous clients).\n\n\n\nYou pay. 💸\n\nThe cashier gives you the number of your turn.\n\n\n\nWhile you are waiting, you go with your crush and pick a table, you sit and talk with your crush for a long time (as your burgers are very fancy and take some time to prepare).\n\nAs you are sitting at the table with your crush, while you wait for the burgers, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨.\n\n\n\nWhile waiting and talking to your crush, from time to time, you check the number displayed on the counter to see if it's your turn already.\n\nThen at some point, it finally is your turn. You go to the counter, get your burgers and come back to the table.\n\n\n\nYou and your crush eat the burgers and have a nice time. ✨\n\n\n\n/// note\n\nBeautiful illustrations by [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨\n\n///\n\n---\n\nImagine you are the computer / program 🤖 in that story.\n\nWhile you are at the line, you are just idle 😴, waiting for your turn, not doing anything very \"productive\". But the line is fast because the cashier is only taking the orders (not preparing them), so that's fine.\n\nThen, when it's your turn, you do actual \"productive\" work, you process the menu, decide what you want, get your crush's choice, pay, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.\n\nBut then, even though you still don't have your burgers, your work with the cashier is \"on pause\" ⏸, because you have to wait 🕙 for your burgers to be ready.\n\nBut as you go away from the counter and sit at the table with a number for your turn, you can switch 🔀 your attention to your crush, and \"work\" ⏯ 🤓 on that. Then you are again doing something very \"productive\" as is flirting with your crush 😍.\n\nThen the cashier 💁 says \"I'm finished with doing the burgers\" by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers because you have the number of your turn, and they have theirs.\n\nSo you wait for your crush to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸.\n\nThen you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of \"eating burgers\" 🔀 ⏯, but the previous one of \"getting burgers\" is finished ⏹.\n\n### Parallel Burgers { #parallel-burgers }\n\nNow let's imagine these aren't \"Concurrent Burgers\", but \"Parallel Burgers\".\n\nYou go with your crush to get parallel fast food.\n\nYou stand in line while several (let's say 8) cashiers that at the same time are cooks take the orders from the people in front of you.\n\nEveryone before you is waiting for their burgers to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.\n\n\n\nThen it's finally your turn, you place your order of 2 very fancy burgers for your crush and you.\n\nYou pay 💸.\n\n\n\nThe cashier goes to the kitchen.\n\nYou wait, standing in front of the counter 🕙, so that no one else takes your burgers before you do, as there are no numbers for turns.\n\n\n\nAs you and your crush are busy not letting anyone get in front of you and take your burgers whenever they arrive, you cannot pay attention to your crush. 😞\n\nThis is \"synchronous\" work, you are \"synchronized\" with the cashier/cook 👨‍🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨‍🍳 finishes the burgers and gives them to you, or otherwise, someone else might take them.\n\n\n\nThen your cashier/cook 👨‍🍳 finally comes back with your burgers, after a long time waiting 🕙 there in front of the counter.\n\n\n\nYou take your burgers and go to the table with your crush.\n\nYou just eat them, and you are done. ⏹\n\n\n\nThere was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞\n\n/// note\n\nBeautiful illustrations by [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨\n\n///\n\n---\n\nIn this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush), both waiting 🕙 and dedicating their attention ⏯ to be \"waiting on the counter\" 🕙 for a long time.\n\nThe fast food store has 8 processors (cashiers/cooks). While the concurrent burgers store might have had only 2 (one cashier and one cook).\n\nBut still, the final experience is not the best. 😞\n\n---\n\nThis would be the parallel equivalent story for burgers. 🍔\n\nFor a more \"real life\" example of this, imagine a bank.\n\nUp to recently, most of the banks had multiple cashiers 👨‍💼👨‍💼👨‍💼👨‍💼 and a big line 🕙🕙🕙🕙🕙🕙🕙🕙.\n\nAll of the cashiers doing all the work with one client after the other 👨‍💼⏯.\n\nAnd you have to wait 🕙 in the line for a long time or you lose your turn.\n\nYou probably wouldn't want to take your crush 😍 with you to run errands at the bank 🏦.\n\n### Burger Conclusion { #burger-conclusion }\n\nIn this scenario of \"fast food burgers with your crush\", as there is a lot of waiting 🕙, it makes a lot more sense to have a concurrent system ⏸🔀⏯.\n\nThis is the case for most of the web applications.\n\nMany, many users, but your server is waiting 🕙 for their not-so-good connection to send their requests.\n\nAnd then waiting 🕙 again for the responses to come back.\n\nThis \"waiting\" 🕙 is measured in microseconds, but still, summing it all, it's a lot of waiting in the end.\n\nThat's why it makes a lot of sense to use asynchronous ⏸🔀⏯ code for web APIs.\n\nThis kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language.\n\nAnd that's the same level of performance you get with **FastAPI**.\n\nAnd as you can have parallelism and asynchronicity at the same time, you get higher performance than most of the tested NodeJS frameworks and on par with Go, which is a compiled language closer to C [(all thanks to Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).\n\n### Is concurrency better than parallelism? { #is-concurrency-better-than-parallelism }\n\nNope! That's not the moral of the story.\n\nConcurrency is different than parallelism. And it is better in **specific** scenarios that involve a lot of waiting. Because of that, it generally is a lot better than parallelism for web application development. But not for everything.\n\nSo, to balance that out, imagine the following short story:\n\n> You have to clean a big, dirty house.\n\n*Yep, that's the whole story*.\n\n---\n\nThere's no waiting 🕙 anywhere, just a lot of work to be done, in multiple places of the house.\n\nYou could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting 🕙 for anything, just cleaning and cleaning, the turns wouldn't affect anything.\n\nIt would take the same amount of time to finish with or without turns (concurrency) and you would have done the same amount of work.\n\nBut in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.\n\nIn this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job.\n\nAnd as most of the execution time is taken by actual work (instead of waiting), and the work in a computer is done by a CPU, they call these problems \"CPU bound\".\n\n---\n\nCommon examples of CPU bound operations are things that require complex math processing.\n\nFor example:\n\n* **Audio** or **image processing**.\n* **Computer vision**: an image is composed of millions of pixels, each pixel has 3 values / colors, processing that normally requires computing something on those pixels, all at the same time.\n* **Machine Learning**: it normally requires lots of \"matrix\" and \"vector\" multiplications. Think of a huge spreadsheet with numbers and multiplying all of them together at the same time.\n* **Deep Learning**: this is a sub-field of Machine Learning, so, the same applies. It's just that there is not a single spreadsheet of numbers to multiply, but a huge set of them, and in many cases, you use a special processor to build and / or use those models.\n\n### Concurrency + Parallelism: Web + Machine Learning { #concurrency-parallelism-web-machine-learning }\n\nWith **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS).\n\nBut you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems.\n\nThat, plus the simple fact that Python is the main language for **Data Science**, Machine Learning and especially Deep Learning, makes FastAPI a very good match for Data Science / Machine Learning web APIs and applications (among many others).\n\nTo see how to achieve this parallelism in production see the section about [Deployment](deployment/index.md).", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "Asynchronous Code { #asynchronous-code }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L67-L302", "start_line": 67, "end_line": 302} {"id": "docs/en/docs/async.md::`async` and `await` { #async-and-await }::L303", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: `async` and `await` { #async-and-await }\n## `async` and `await` { #async-and-await }\n\nModern versions of Python have a very intuitive way to define asynchronous code. This makes it look just like normal \"sequential\" code and do the \"awaiting\" for you at the right moments.\n\nWhen there is an operation that will require waiting before giving the results and has support for these new Python features, you can code it like:\n\n```Python\nburgers = await get_burgers(2)\n```\n\nThe key here is the `await`. It tells Python that it has to wait ⏸ for `get_burgers(2)` to finish doing its thing 🕙 before storing the results in `burgers`. With that, Python will know that it can go and do something else 🔀 ⏯ in the meanwhile (like receiving another request).\n\nFor `await` to work, it has to be inside a function that supports this asynchronicity. To do that, you just declare it with `async def`:\n\n```Python hl_lines=\"1\"\nasync def get_burgers(number: int):\n # Do some asynchronous stuff to create the burgers\n return burgers\n```\n\n...instead of `def`:\n\n```Python hl_lines=\"2\"\n# This is not asynchronous\ndef get_sequential_burgers(number: int):\n # Do some sequential stuff to create the burgers\n return burgers\n```\n\nWith `async def`, Python knows that, inside that function, it has to be aware of `await` expressions, and that it can \"pause\" ⏸ the execution of that function and go do something else 🔀 before coming back.\n\nWhen you want to call an `async def` function, you have to \"await\" it. So, this won't work:\n\n```Python\n# This won't work, because get_burgers was defined with: async def\nburgers = get_burgers(2)\n```\n\n---\n\nSo, if you are using a library that tells you that you can call it with `await`, you need to create the *path operation functions* that use it with `async def`, like in:\n\n```Python hl_lines=\"2-3\"\n@app.get('/burgers')\nasync def read_burgers():\n burgers = await get_burgers(2)\n return burgers\n```\n\n### More technical details { #more-technical-details }\n\nYou might have noticed that `await` can only be used inside of functions defined with `async def`.\n\nBut at the same time, functions defined with `async def` have to be \"awaited\". So, functions with `async def` can only be called inside of functions defined with `async def` too.\n\nSo, about the egg and the chicken, how do you call the first `async` function?\n\nIf you are working with **FastAPI** you don't have to worry about that, because that \"first\" function will be your *path operation function*, and FastAPI will know how to do the right thing.\n\nBut if you want to use `async` / `await` without FastAPI, you can do it as well.\n\n### Write your own async code { #write-your-own-async-code }\n\nStarlette (and **FastAPI**) are based on [AnyIO](https://anyio.readthedocs.io/en/stable/), which makes it compatible with both Python's standard library [asyncio](https://docs.python.org/3/library/asyncio-task.html) and [Trio](https://trio.readthedocs.io/en/stable/).\n\nIn particular, you can directly use [AnyIO](https://anyio.readthedocs.io/en/stable/) for your advanced concurrency use cases that require more advanced patterns in your own code.\n\nAnd even if you were not using FastAPI, you could also write your own async applications with [AnyIO](https://anyio.readthedocs.io/en/stable/) to be highly compatible and get its benefits (e.g. *structured concurrency*).\n\nI created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: [Asyncer](https://asyncer.tiangolo.com/). It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code.\n\n### Other forms of asynchronous code { #other-forms-of-asynchronous-code }\n\nThis style of using `async` and `await` is relatively new in the language.\n\nBut it makes working with asynchronous code a lot easier.\n\nThis same syntax (or almost identical) was also included recently in modern versions of JavaScript (in Browser and NodeJS).\n\nBut before that, handling asynchronous code was quite more complex and difficult.\n\nIn previous versions of Python, you could have used threads or [Gevent](https://www.gevent.org/). But the code is way more complex to understand, debug, and think about.\n\nIn previous versions of NodeJS / Browser JavaScript, you would have used \"callbacks\". Which leads to \"callback hell\".", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "`async` and `await` { #async-and-await }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L303-L387", "start_line": 303, "end_line": 387} {"id": "docs/en/docs/async.md::Coroutines { #coroutines }::L388", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: Coroutines { #coroutines }\n## Coroutines { #coroutines }\n\n**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it.\n\nBut all this functionality of using asynchronous code with `async` and `await` is many times summarized as using \"coroutines\". It is comparable to the main key feature of Go, the \"Goroutines\".", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "Coroutines { #coroutines }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L388-L393", "start_line": 388, "end_line": 393} {"id": "docs/en/docs/async.md::Conclusion { #conclusion }::L394", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: Conclusion { #conclusion }\n## Conclusion { #conclusion }\n\nLet's see the same phrase from above:\n\n> Modern versions of Python have support for **\"asynchronous code\"** using something called **\"coroutines\"**, with **`async` and `await`** syntax.\n\nThat should make more sense now. ✨\n\nAll that is what powers FastAPI (through Starlette) and what makes it have such an impressive performance.", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "Conclusion { #conclusion }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L394-L403", "start_line": 394, "end_line": 403} {"id": "docs/en/docs/async.md::Very Technical Details { #very-technical-details }::L404", "text": "# Doc: docs/en/docs/async.md | Page: Concurrency and async / await { #concurrency-and-async-await } | Section: Very Technical Details { #very-technical-details }\n## Very Technical Details { #very-technical-details }\n\n/// warning\n\nYou can probably skip this.\n\nThese are very technical details of how **FastAPI** works underneath.\n\nIf you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.\n\n///\n\n### Path operation functions { #path-operation-functions }\n\nWhen you declare a *path operation function* with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server).\n\nIf you are coming from another async framework that does not work in the way described above and you are used to defining trivial compute-only *path operation functions* with plain `def` for a tiny performance gain (about 100 nanoseconds), please note that in **FastAPI** the effect would be quite opposite. In these cases, it's better to use `async def` unless your *path operation functions* use code that performs blocking I/O.\n\nStill, in both situations, chances are that **FastAPI** will [still be faster](index.md#performance) than (or at least comparable to) your previous framework.\n\n### Dependencies { #dependencies }\n\nThe same applies for [dependencies](tutorial/dependencies/index.md). If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.\n\n### Sub-dependencies { #sub-dependencies }\n\nYou can have multiple dependencies and [sub-dependencies](tutorial/dependencies/sub-dependencies.md) requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being \"awaited\".\n\n### Other utility functions { #other-utility-functions }\n\nAny other utility function that you call directly can be created with normal `def` or `async def` and FastAPI won't affect the way you call it.\n\nThis is in contrast to the functions that FastAPI calls for you: *path operation functions* and dependencies.\n\nIf your utility function is a normal function with `def`, it will be called directly (as you write it in your code), not in a threadpool, if the function is created with `async def` then you should `await` that function when you call it in your code.\n\n---\n\nAgain, these are very technical details that would probably be useful if you came searching for them.\n\nOtherwise, you should be good with the guidelines from the section above:
In a hurry?.", "source_type": "doc", "path": "docs/en/docs/async.md", "symbol": "Very Technical Details { #very-technical-details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/async.md#L404-L444", "start_line": 404, "end_line": 444} {"id": "docs/en/docs/benchmarks.md::Benchmarks { #benchmarks }::L1", "text": "# Doc: docs/en/docs/benchmarks.md | Page: Benchmarks { #benchmarks } | Section: Benchmarks { #benchmarks }\n# Benchmarks { #benchmarks }\n\nIndependent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as [one of the fastest Python frameworks available](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), only below Starlette and Uvicorn themselves (used internally by FastAPI).\n\nBut when checking benchmarks and comparisons you should keep the following in mind.", "source_type": "doc", "path": "docs/en/docs/benchmarks.md", "symbol": "Benchmarks { #benchmarks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/benchmarks.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/benchmarks.md::Benchmarks and speed { #benchmarks-and-speed }::L7", "text": "# Doc: docs/en/docs/benchmarks.md | Page: Benchmarks { #benchmarks } | Section: Benchmarks and speed { #benchmarks-and-speed }\n## Benchmarks and speed { #benchmarks-and-speed }\n\nWhen you check the benchmarks, it is common to see several tools of different types compared as equivalent.\n\nSpecifically, to see Uvicorn, Starlette and FastAPI compared together (among many other tools).\n\nThe simpler the problem solved by the tool, the better performance it will get. And most of the benchmarks don't test the additional features provided by the tool.\n\nThe hierarchy is like:\n\n* **Uvicorn**: an ASGI server\n * **Starlette**: (uses Uvicorn) a web microframework\n * **FastAPI**: (uses Starlette) an API microframework with several additional features for building APIs, with data validation, etc.\n\n* **Uvicorn**:\n * Will have the best performance, as it doesn't have much extra code apart from the server itself.\n * You wouldn't write an application in Uvicorn directly. That would mean that your code would have to include more or less, at least, all the code provided by Starlette (or **FastAPI**). And if you did that, your final application would have the same overhead as having used a framework and minimizing your app code and bugs.\n * If you are comparing Uvicorn, compare it against Daphne, Hypercorn, uWSGI, etc. Application servers.\n* **Starlette**:\n * Will have the next best performance, after Uvicorn. In fact, Starlette uses Uvicorn to run. So, it probably can only get \"slower\" than Uvicorn by having to execute more code.\n * But it provides you the tools to build simple web applications, with routing based on paths, etc.\n * If you are comparing Starlette, compare it against Sanic, Flask, Django, etc. Web frameworks (or microframeworks).\n* **FastAPI**:\n * The same way that Starlette uses Uvicorn and cannot be faster than it, **FastAPI** uses Starlette, so it cannot be faster than it.\n * FastAPI provides more features on top of Starlette. Features that you almost always need when building APIs, like data validation and serialization. And by using it, you get automatic documentation for free (the automatic documentation doesn't even add overhead to running applications, it is generated on startup).\n * If you didn't use FastAPI and used Starlette directly (or another tool, like Sanic, Flask, Responder, etc) you would have to implement all the data validation and serialization yourself. So, your final application would still have the same overhead as if it was built using FastAPI. And in many cases, this data validation and serialization is the biggest amount of code written in applications.\n * So, by using FastAPI you are saving development time, bugs, lines of code, and you would probably get the same performance (or better) you would if you didn't use it (as you would have to implement it all in your code).\n * If you are comparing FastAPI, compare it against a web application framework (or set of tools) that provides data validation, serialization and documentation, like Flask-apispec, NestJS, Molten, etc. Frameworks with integrated automatic data validation, serialization and documentation.", "source_type": "doc", "path": "docs/en/docs/benchmarks.md", "symbol": "Benchmarks and speed { #benchmarks-and-speed }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/benchmarks.md#L7-L34", "start_line": 7, "end_line": 34} {"id": "docs/en/docs/contributing.md::Contributing::L1", "text": "# Doc: docs/en/docs/contributing.md | Page: Contributing | Section: Contributing\n# Contributing\n\nFirst, you might want to see the basic ways to [help FastAPI and get help](help-fastapi.md).", "source_type": "doc", "path": "docs/en/docs/contributing.md", "symbol": "Contributing", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/contributing.md::Developing::L5", "text": "# Doc: docs/en/docs/contributing.md | Page: Contributing | Section: Developing\n## Developing\n\nTo contribute code to the project, please follow the guidelines in [tiangolo.com - Contributing](https://tiangolo.com/open-source/contributing/).", "source_type": "doc", "path": "docs/en/docs/contributing.md", "symbol": "Developing", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md#L5-L7", "start_line": 5, "end_line": 7} {"id": "docs/en/docs/deployment/cloud.md::Deploy FastAPI on Cloud Providers { #deploy-fastapi-on-cloud-providers }::L1", "text": "# Doc: docs/en/docs/deployment/cloud.md | Page: Deploy FastAPI on Cloud Providers { #deploy-fastapi-on-cloud-providers } | Section: Deploy FastAPI on Cloud Providers { #deploy-fastapi-on-cloud-providers }\n# Deploy FastAPI on Cloud Providers { #deploy-fastapi-on-cloud-providers }\n\nYou can use virtually **any cloud provider** to deploy your FastAPI application.\n\nIn most of the cases, the main cloud providers have guides to deploy FastAPI with them.", "source_type": "doc", "path": "docs/en/docs/deployment/cloud.md", "symbol": "Deploy FastAPI on Cloud Providers { #deploy-fastapi-on-cloud-providers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/cloud.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/deployment/cloud.md::FastAPI Cloud { #fastapi-cloud }::L7", "text": "# Doc: docs/en/docs/deployment/cloud.md | Page: Deploy FastAPI on Cloud Providers { #deploy-fastapi-on-cloud-providers } | Section: FastAPI Cloud { #fastapi-cloud }\n## FastAPI Cloud { #fastapi-cloud }\n\n**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**.\n\nIt streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort.\n\nIt brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉\n\nFastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨", "source_type": "doc", "path": "docs/en/docs/deployment/cloud.md", "symbol": "FastAPI Cloud { #fastapi-cloud }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/cloud.md#L7-L16", "start_line": 7, "end_line": 16} {"id": "docs/en/docs/deployment/cloud.md::Cloud Providers - Sponsors { #cloud-providers-sponsors }::L17", "text": "# Doc: docs/en/docs/deployment/cloud.md | Page: Deploy FastAPI on Cloud Providers { #deploy-fastapi-on-cloud-providers } | Section: Cloud Providers - Sponsors { #cloud-providers-sponsors }\n## Cloud Providers - Sponsors { #cloud-providers-sponsors }\n\nSome other cloud providers ✨ [**sponsor FastAPI**](https://github.com/sponsors/tiangolo) ✨ too. 🙇\n\nYou might also want to consider them to follow their guides and try their services:\n\n* [Render](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi)\n* [Railway](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi)", "source_type": "doc", "path": "docs/en/docs/deployment/cloud.md", "symbol": "Cloud Providers - Sponsors { #cloud-providers-sponsors }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/cloud.md#L17-L24", "start_line": 17, "end_line": 24} {"id": "docs/en/docs/deployment/concepts.md::Deployments Concepts { #deployments-concepts }::L1", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Deployments Concepts { #deployments-concepts }\n# Deployments Concepts { #deployments-concepts }\n\nWhen deploying a **FastAPI** application, or actually, any type of web API, there are several concepts that you probably care about, and using them you can find the **most appropriate** way to **deploy your application**.\n\nSome of the important concepts are:\n\n* Security - HTTPS\n* Running on startup\n* Restarts\n* Replication (the number of processes running)\n* Memory\n* Previous steps before starting\n\nWe'll see how they would affect **deployments**.\n\nIn the end, the ultimate objective is to be able to **serve your API clients** in a way that is **secure**, to **avoid disruptions**, and to use the **compute resources** (for example remote servers/virtual machines) as efficiently as possible. 🚀\n\nI'll tell you a bit more about these **concepts** here, and that would hopefully give you the **intuition** you would need to decide how to deploy your API in very different environments, possibly even in **future** ones that don't exist yet.\n\nBy considering these concepts, you will be able to **evaluate and design** the best way to deploy **your own APIs**.\n\nIn the next chapters, I'll give you more **concrete recipes** to deploy FastAPI applications.\n\nBut for now, let's check these important **conceptual ideas**. These concepts also apply to any other type of web API. 💡", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Deployments Concepts { #deployments-concepts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L1-L25", "start_line": 1, "end_line": 25} {"id": "docs/en/docs/deployment/concepts.md::Security - HTTPS { #security-https }::L26", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Security - HTTPS { #security-https }\n## Security - HTTPS { #security-https }\n\nIn the [previous chapter about HTTPS](https.md) we learned about how HTTPS provides encryption for your API.\n\nWe also saw that HTTPS is normally provided by a component **external** to your application server, a **TLS Termination Proxy**.\n\nAnd there has to be something in charge of **renewing the HTTPS certificates**, it could be the same component or it could be something different.\n\n### Example Tools for HTTPS { #example-tools-for-https }\n\nSome of the tools you could use as a TLS Termination Proxy are:\n\n* Traefik\n * Automatically handles certificate renewals ✨\n* Caddy\n * Automatically handles certificate renewals ✨\n* Nginx\n * With an external component like Certbot for certificate renewals\n* HAProxy\n * With an external component like Certbot for certificate renewals\n* Kubernetes with an Ingress Controller like Nginx\n * With an external component like cert-manager for certificate renewals\n* Handled internally by a cloud provider as part of their services (read below 👇)\n\nAnother option is that you could use a **cloud service** that does more of the work including setting up HTTPS. It could have some restrictions or charge you more, etc. But in that case, you wouldn't have to set up a TLS Termination Proxy yourself.\n\nI'll show you some concrete examples in the next chapters.\n\n---\n\nThen the next concepts to consider are all about the program running your actual API (e.g. Uvicorn).", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Security - HTTPS { #security-https }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L26-L57", "start_line": 26, "end_line": 57} {"id": "docs/en/docs/deployment/concepts.md::Program and Process { #program-and-process }::L58", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Program and Process { #program-and-process }\n## Program and Process { #program-and-process }\n\nWe will talk a lot about the running \"**process**\", so it's useful to have clarity about what it means, and what's the difference with the word \"**program**\".\n\n### What is a Program { #what-is-a-program }\n\nThe word **program** is commonly used to describe many things:\n\n* The **code** that you write, the **Python files**.\n* The **file** that can be **executed** by the operating system, for example: `python`, `python.exe` or `uvicorn`.\n* A particular program while it is **running** on the operating system, using the CPU, and storing things in memory. This is also called a **process**.\n\n### What is a Process { #what-is-a-process }\n\nThe word **process** is normally used in a more specific way, only referring to the thing that is running in the operating system (like in the last point above):\n\n* A particular program while it is **running** on the operating system.\n * This doesn't refer to the file, nor to the code, it refers **specifically** to the thing that is being **executed** and managed by the operating system.\n* Any program, any code, **can only do things** when it is being **executed**. So, when there's a **process running**.\n* The process can be **terminated** (or \"killed\") by you, or by the operating system. At that point, it stops running/being executed, and it can **no longer do things**.\n* Each application that you have running on your computer has some process behind it, each running program, each window, etc. And there are normally many processes running **at the same time** while a computer is on.\n* There can be **multiple processes** of the **same program** running at the same time.\n\nIf you check out the \"task manager\" or \"system monitor\" (or similar tools) in your operating system, you will be able to see many of those processes running.\n\nAnd, for example, you will probably see that there are multiple processes running the same browser program (Firefox, Chrome, Edge, etc). They normally run one process per tab, plus some other extra processes.\n\n\n\n---\n\nNow that we know the difference between the terms **process** and **program**, let's continue talking about deployments.", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Program and Process { #program-and-process }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L58-L90", "start_line": 58, "end_line": 90} {"id": "docs/en/docs/deployment/concepts.md::Running on Startup { #running-on-startup }::L91", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Running on Startup { #running-on-startup }\n## Running on Startup { #running-on-startup }\n\nIn most cases, when you create a web API, you want it to be **always running**, uninterrupted, so that your clients can always access it. This is of course, unless you have a specific reason why you want it to run only in certain situations, but most of the time you want it constantly running and **available**.\n\n### In a Remote Server { #in-a-remote-server }\n\nWhen you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally.\n\nAnd it will work and will be useful **during development**.\n\nBut if your connection to the server is lost, the **running process** will probably die.\n\nAnd if the server is restarted (for example after updates, or migrations from the cloud provider) you probably **won't notice it**. And because of that, you won't even know that you have to restart the process manually. So, your API will just stay dead. 😱\n\n### Run Automatically on Startup { #run-automatically-on-startup }\n\nIn general, you will probably want the server program (e.g. Uvicorn) to be started automatically on server startup, and without needing any **human intervention**, to have a process always running with your API (e.g. Uvicorn running your FastAPI app).\n\n### Separate Program { #separate-program }\n\nTo achieve this, you will normally have a **separate program** that would make sure your application is run on startup. And in many cases, it would also make sure other components or applications are also run, for example, a database.\n\n### Example Tools to Run at Startup { #example-tools-to-run-at-startup }\n\nSome examples of the tools that can do this job are:\n\n* Docker\n* Kubernetes\n* Docker Compose\n* Docker in Swarm Mode\n* Systemd\n* Supervisor\n* Handled internally by a cloud provider as part of their services\n* Others...\n\nI'll give you more concrete examples in the next chapters.", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Running on Startup { #running-on-startup }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L91-L127", "start_line": 91, "end_line": 127} {"id": "docs/en/docs/deployment/concepts.md::Restarts { #restarts }::L128", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Restarts { #restarts }\n## Restarts { #restarts }\n\nSimilar to making sure your application is run on startup, you probably also want to make sure it is **restarted** after failures.\n\n### We Make Mistakes { #we-make-mistakes }\n\nWe, as humans, make **mistakes**, all the time. Software almost *always* has **bugs** hidden in different places. 🐛\n\nAnd we as developers keep improving the code as we find those bugs and as we implement new features (possibly adding new bugs too 😅).\n\n### Small Errors Automatically Handled { #small-errors-automatically-handled }\n\nWhen building web APIs with FastAPI, if there's an error in our code, FastAPI will normally contain it to the single request that triggered the error. 🛡\n\nThe client will get a **500 Internal Server Error** for that request, but the application will continue working for the next requests instead of just crashing completely.\n\n### Bigger Errors - Crashes { #bigger-errors-crashes }\n\nNevertheless, there might be cases where we write some code that **crashes the entire application** making Uvicorn and Python crash. 💥\n\nAnd still, you would probably not want the application to stay dead because there was an error in one place, you probably want it to **continue running** at least for the *path operations* that are not broken.\n\n### Restart After Crash { #restart-after-crash }\n\nBut in those cases with really bad errors that crash the running **process**, you would want an external component that is in charge of **restarting** the process, at least a couple of times...\n\n/// tip\n\n...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment.\n\nSo let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it.\n\n///\n\nYou would probably want to have the thing in charge of restarting your application as an **external component**, because by that point, the same application with Uvicorn and Python already crashed, so there's nothing in the same code of the same app that could do anything about it.\n\n### Example Tools to Restart Automatically { #example-tools-to-restart-automatically }\n\nIn most cases, the same tool that is used to **run the program on startup** is also used to handle automatic **restarts**.\n\nFor example, this could be handled by:\n\n* Docker\n* Kubernetes\n* Docker Compose\n* Docker in Swarm Mode\n* Systemd\n* Supervisor\n* Handled internally by a cloud provider as part of their services\n* Others...", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Restarts { #restarts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L128-L178", "start_line": 128, "end_line": 178} {"id": "docs/en/docs/deployment/concepts.md::Replication - Processes and Memory { #replication-processes-and-memory }::L179", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Replication - Processes and Memory { #replication-processes-and-memory }\n## Replication - Processes and Memory { #replication-processes-and-memory }\n\nWith a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently.\n\nBut in many cases, you will want to run several worker processes at the same time.\n\n### Multiple Processes - Workers { #multiple-processes-workers }\n\nIf you have more clients than what a single process can handle (for example if the virtual machine is not too big) and you have **multiple cores** in the server's CPU, then you could have **multiple processes** running with the same application at the same time, and distribute all the requests among them.\n\nWhen you run **multiple processes** of the same API program, they are commonly called **workers**.\n\n### Worker Processes and Ports { #worker-processes-and-ports }\n\nRemember from the docs [About HTTPS](https.md) that only one process can be listening on one combination of port and IP address in a server?\n\nThis is still true.\n\nSo, to be able to have **multiple processes** at the same time, there has to be a **single process listening on a port** that then transmits the communication to each worker process in some way.\n\n### Memory per Process { #memory-per-process }\n\nNow, when the program loads things in memory, for example, a machine learning model in a variable, or the contents of a large file in a variable, all that **consumes a bit of the memory (RAM)** of the server.\n\nAnd multiple processes normally **don't share any memory**. This means that each running process has its own things, variables, and memory. And if you are consuming a large amount of memory in your code, **each process** will consume an equivalent amount of memory.\n\n### Server Memory { #server-memory }\n\nFor example, if your code loads a Machine Learning model with **1 GB in size**, when you run one process with your API, it will consume at least 1 GB of RAM. And if you start **4 processes** (4 workers), each will consume 1 GB of RAM. So in total, your API will consume **4 GB of RAM**.\n\nAnd if your remote server or virtual machine only has 3 GB of RAM, trying to load more than 4 GB of RAM will cause problems. 🚨\n\n### Multiple Processes - An Example { #multiple-processes-an-example }\n\nIn this example, there's a **Manager Process** that starts and controls two **Worker Processes**.\n\nThis Manager Process would probably be the one listening on the **port** in the IP. And it would transmit all the communication to the worker processes.\n\nThose worker processes would be the ones running your application, they would perform the main computations to receive a **request** and return a **response**, and they would load anything you put in variables in RAM.\n\n\n\nAnd of course, the same machine would probably have **other processes** running as well, apart from your application.\n\nAn interesting detail is that the percentage of the **CPU used** by each process can **vary** a lot over time, but the **memory (RAM)** normally stays more or less **stable**.\n\nIf you have an API that does a comparable amount of computations every time and you have a lot of clients, then the **CPU utilization** will probably *also be stable* (instead of constantly going up and down quickly).\n\n### Examples of Replication Tools and Strategies { #examples-of-replication-tools-and-strategies }\n\nThere can be several approaches to achieve this, and I'll tell you more about specific strategies in the next chapters, for example when talking about Docker and containers.\n\nThe main constraint to consider is that there has to be a **single** component handling the **port** in the **public IP**. And then it has to have a way to **transmit** the communication to the replicated **processes/workers**.\n\nHere are some possible combinations and strategies:\n\n* **Uvicorn** with `--workers`\n * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**.\n* **Kubernetes** and other distributed **container systems**\n * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running.\n* **Cloud services** that handle this for you\n * The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it.\n\n/// tip\n\nDon't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet.\n\nI'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Replication - Processes and Memory { #replication-processes-and-memory }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L179-L249", "start_line": 179, "end_line": 249} {"id": "docs/en/docs/deployment/concepts.md::Previous Steps Before Starting { #previous-steps-before-starting }::L250", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Previous Steps Before Starting { #previous-steps-before-starting }\n## Previous Steps Before Starting { #previous-steps-before-starting }\n\nThere are many cases where you want to perform some steps **before starting** your application.\n\nFor example, you might want to run **database migrations**.\n\nBut in most cases, you will want to perform these steps only **once**.\n\nSo, you will want to have a **single process** to perform those **previous steps**, before starting the application.\n\nAnd you will have to make sure that it's a single process running those previous steps *even* if afterwards, you start **multiple processes** (multiple workers) for the application itself. If those steps were run by **multiple processes**, they would **duplicate** the work by running it in **parallel**, and if the steps were something delicate like a database migration, they could cause conflicts with each other.\n\nOf course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle.\n\n/// tip\n\nAlso, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application.\n\nIn that case, you wouldn't have to worry about any of this. 🤷\n\n///\n\n### Examples of Previous Steps Strategies { #examples-of-previous-steps-strategies }\n\nThis will **depend heavily** on the way you **deploy your system**, and it would probably be connected to the way you start programs, handling restarts, etc.\n\nHere are some possible ideas:\n\n* An \"Init Container\" in Kubernetes that runs before your app container\n* A bash script that runs the previous steps and then starts your application\n * You would still need a way to start/restart *that* bash script, detect errors, etc.\n\n/// tip\n\nI'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Previous Steps Before Starting { #previous-steps-before-starting }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L250-L287", "start_line": 250, "end_line": 287} {"id": "docs/en/docs/deployment/concepts.md::Resource Utilization { #resource-utilization }::L288", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Resource Utilization { #resource-utilization }\n## Resource Utilization { #resource-utilization }\n\nYour server(s) is (are) a **resource**, you can consume or **utilize**, with your programs, the computation time on the CPUs, and the RAM memory available.\n\nHow much of the system resources do you want to be consuming/utilizing? It might be easy to think \"not much\", but in reality, you will probably want to consume **as much as possible without crashing**.\n\nIf you are paying for 3 servers but you are using only a little bit of their RAM and CPU, you are probably **wasting money** 💸, and probably **wasting server electric power** 🌎, etc.\n\nIn that case, it could be better to have only 2 servers and use a higher percentage of their resources (CPU, memory, disk, network bandwidth, etc).\n\nOn the other hand, if you have 2 servers and you are using **100% of their CPU and RAM**, at some point one process will ask for more memory, and the server will have to use the disk as \"memory\" (which can be thousands of times slower), or even **crash**. Or one process might need to do some computation and would have to wait until the CPU is free again.\n\nIn this case, it would be better to get **one extra server** and run some processes on it so that they all have **enough RAM and CPU time**.\n\nThere's also the chance that for some reason you have a **spike** of usage of your API. Maybe it went viral, or maybe some other services or bots start using it. And you might want to have extra resources to be safe in those cases.\n\nYou could put an **arbitrary number** to target, for example, something **between 50% to 90%** of resource utilization. The point is that those are probably the main things you will want to measure and use to tweak your deployments.\n\nYou can use simple tools like `htop` to see the CPU and RAM used in your server or the amount used by each process. Or you can use more complex monitoring tools, which may be distributed across servers, etc.", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Resource Utilization { #resource-utilization }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L288-L307", "start_line": 288, "end_line": 307} {"id": "docs/en/docs/deployment/concepts.md::Recap { #recap }::L308", "text": "# Doc: docs/en/docs/deployment/concepts.md | Page: Deployments Concepts { #deployments-concepts } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application:\n\n* Security - HTTPS\n* Running on startup\n* Restarts\n* Replication (the number of processes running)\n* Memory\n* Previous steps before starting\n\nUnderstanding these ideas and how to apply them should give you the intuition necessary to take any decisions when configuring and tweaking your deployments. 🤓\n\nIn the next sections, I'll give you more concrete examples of possible strategies you can follow. 🚀", "source_type": "doc", "path": "docs/en/docs/deployment/concepts.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/concepts.md#L308-L321", "start_line": 308, "end_line": 321} {"id": "docs/en/docs/deployment/docker.md::FastAPI in Containers - Docker { #fastapi-in-containers-docker }::L1", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: FastAPI in Containers - Docker { #fastapi-in-containers-docker }\n# FastAPI in Containers - Docker { #fastapi-in-containers-docker }\n\nWhen deploying FastAPI applications a common approach is to build a **Linux container image**. It's normally done using [**Docker**](https://www.docker.com/). You can then deploy that container image in one of a few possible ways.\n\nUsing Linux containers has several advantages including **security**, **replicability**, **simplicity**, and others.\n\n/// tip\n\nIn a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi).\n\n///\n\n
\nDockerfile Preview 👀\n\n```Dockerfile\nFROM python:3.14\n\nWORKDIR /code\n\nCOPY ./requirements.txt /code/requirements.txt\n\nRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt\n\nCOPY ./app /code/app\n\nCMD [\"fastapi\", \"run\", \"app/main.py\", \"--port\", \"80\"]\n\n# If running behind a proxy like Nginx or Traefik add --proxy-headers\n# CMD [\"fastapi\", \"run\", \"app/main.py\", \"--port\", \"80\", \"--proxy-headers\"]\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "FastAPI in Containers - Docker { #fastapi-in-containers-docker }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L1-L34", "start_line": 1, "end_line": 34} {"id": "docs/en/docs/deployment/docker.md::What is a Container { #what-is-a-container }::L35", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: What is a Container { #what-is-a-container }\n## What is a Container { #what-is-a-container }\n\nContainers (mainly Linux containers) are a very **lightweight** way to package applications including all their dependencies and necessary files while keeping them isolated from other containers (other applications or components) in the same system.\n\nLinux containers run using the same Linux kernel of the host (machine, virtual machine, cloud server, etc). This just means that they are very lightweight (compared to full virtual machines emulating an entire operating system).\n\nThis way, containers consume **little resources**, an amount comparable to running the processes directly (a virtual machine would consume much more).\n\nContainers also have their own **isolated** running processes (commonly just one process), file system, and network, simplifying deployment, security, development, etc.", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "What is a Container { #what-is-a-container }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L35-L44", "start_line": 35, "end_line": 44} {"id": "docs/en/docs/deployment/docker.md::What is a Container Image { #what-is-a-container-image }::L45", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: What is a Container Image { #what-is-a-container-image }\n## What is a Container Image { #what-is-a-container-image }\n\nA **container** is run from a **container image**.\n\nA container image is a **static** version of all the files, environment variables, and the default command/program that should be present in a container. **Static** here means that the container **image** is not running, it's not being executed, it's only the packaged files and metadata.\n\nIn contrast to a \"**container image**\" that is the stored static contents, a \"**container**\" normally refers to the running instance, the thing that is being **executed**.\n\nWhen the **container** is started and running (started from a **container image**) it could create or change files, environment variables, etc. Those changes will exist only in that container, but would not persist in the underlying container image (would not be saved to disk).\n\nA container image is comparable to the **program** file and contents, e.g. `python` and some file `main.py`.\n\nAnd the **container** itself (in contrast to the **container image**) is the actual running instance of the image, comparable to a **process**. In fact, a container is running only when it has a **process running** (and normally it's only a single process). The container stops when there's no process running in it.", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "What is a Container Image { #what-is-a-container-image }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L45-L58", "start_line": 45, "end_line": 58} {"id": "docs/en/docs/deployment/docker.md::Container Images { #container-images }::L59", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Container Images { #container-images }\n## Container Images { #container-images }\n\nDocker has been one of the main tools to create and manage **container images** and **containers**.\n\nAnd there's a public [Docker Hub](https://hub.docker.com/) with pre-made **official container images** for many tools, environments, databases, and applications.\n\nFor example, there's an official [Python Image](https://hub.docker.com/_/python).\n\nAnd there are many other images for different things like databases, for example for:\n\n* [PostgreSQL](https://hub.docker.com/_/postgres)\n* [MySQL](https://hub.docker.com/_/mysql)\n* [MongoDB](https://hub.docker.com/_/mongo)\n* [Redis](https://hub.docker.com/_/redis), etc.\n\nBy using a pre-made container image it's very easy to **combine** and use different tools. For example, to try out a new database. In most cases, you can use the **official images**, and just configure them with environment variables.\n\nThat way, in many cases you can learn about containers and Docker and reuse that knowledge with many different tools and components.\n\nSo, you would run **multiple containers** with different things, like a database, a Python application, a web server with a React frontend application, and connect them together via their internal network.\n\nAll the container management systems (like Docker or Kubernetes) have these networking features integrated into them.", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Container Images { #container-images }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L59-L81", "start_line": 59, "end_line": 81} {"id": "docs/en/docs/deployment/docker.md::Containers and Processes { #containers-and-processes }::L82", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Containers and Processes { #containers-and-processes }\n## Containers and Processes { #containers-and-processes }\n\nA **container image** normally includes in its metadata the default program or command that should be run when the **container** is started and the parameters to be passed to that program. Very similar to what would be if it was in the command line.\n\nWhen a **container** is started, it will run that command/program (although you can override it and make it run a different command/program).\n\nA container is running as long as the **main process** (command or program) is running.\n\nA container normally has a **single process**, but it's also possible to start subprocesses from the main process, and that way you will have **multiple processes** in the same container.\n\nBut it's not possible to have a running container without **at least one running process**. If the main process stops, the container stops.", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Containers and Processes { #containers-and-processes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L82-L93", "start_line": 82, "end_line": 93} {"id": "docs/en/docs/deployment/docker.md::Build a Docker Image for FastAPI { #build-a-docker-image-for-fastapi }::L94", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Build a Docker Image for FastAPI { #build-a-docker-image-for-fastapi }\n## Build a Docker Image for FastAPI { #build-a-docker-image-for-fastapi }\n\nOkay, let's build something now! 🚀\n\nI'll show you how to build a **Docker image** for FastAPI **from scratch**, based on the **official Python** image.\n\nThis is what you would want to do in **most cases**, for example:\n\n* Using **Kubernetes** or similar tools\n* When running on a **Raspberry Pi**\n* Using a cloud service that would run a container image for you, etc.\n\n### Package Requirements { #package-requirements }\n\nYou would normally have the **package requirements** for your application in some file.\n\nIt would depend mainly on the tool you use to **install** those requirements.\n\nThe most common way to do it is to have a file `requirements.txt` with the package names and their versions, one per line.\n\nYou would of course use the same ideas you read in [About FastAPI versions](versions.md) to set the ranges of versions.\n\nFor example, your `requirements.txt` could look like:\n\n```\nfastapi[standard]>=0.113.0,<0.114.0\npydantic>=2.7.0,<3.0.0\n```\n\nAnd you would normally install those package dependencies with `pip`, for example:\n\n
\n\n```console\n$ pip install -r requirements.txt\n---> 100%\nSuccessfully installed fastapi pydantic\n```\n\n
\n\n/// note\n\nThere are other formats and tools to define and install package dependencies.\n\n///\n\n### Create the **FastAPI** Code { #create-the-fastapi-code }\n\n* Create an `app` directory and enter it.\n* Create an empty file `__init__.py`.\n* Create a `main.py` file with:\n\n```Python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/items/{item_id}\")\ndef read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n```\n\n### Dockerfile { #dockerfile }\n\nNow in the same project directory create a file `Dockerfile` with:\n\n```{ .dockerfile .annotate }\n# (1)!\nFROM python:3.14\n\n# (2)!\nWORKDIR /code\n\n# (3)!\nCOPY ./requirements.txt /code/requirements.txt\n\n# (4)!\nRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt\n\n# (5)!\nCOPY ./app /code/app\n\n# (6)!\nCMD [\"fastapi\", \"run\", \"app/main.py\", \"--port\", \"80\"]\n```\n\n1. Start from the official Python base image.\n\n2. Set the current working directory to `/code`.\n\n This is where we'll put the `requirements.txt` file and the `app` directory.\n\n3. Copy the file with the requirements to the `/code` directory.\n\n Copy **only** the file with the requirements first, not the rest of the code.\n\n As this file **doesn't change often**, Docker will detect it and use the **cache** for this step, enabling the cache for the next step too.\n\n4. Install the package dependencies in the requirements file.\n\n The `--no-cache-dir` option tells `pip` to not save the downloaded packages locally, as that is only if `pip` was going to be run again to install the same packages, but that's not the case when working with containers.\n\n /// note\n\n The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers.\n\n ///\n\n The `--upgrade` option tells `pip` to upgrade the packages if they are already installed.\n\n Because the previous step copying the file could be detected by the **Docker cache**, this step will also **use the Docker cache** when available.\n\n Using the cache in this step will **save** you a lot of **time** when building the image again and again during development, instead of **downloading and installing** all the dependencies **every time**.\n\n5. Copy the `./app` directory inside the `/code` directory.\n\n As this has all the code which is what **changes most frequently** the Docker **cache** won't be used for this or any **following steps** easily.\n\n So, it's important to put this **near the end** of the `Dockerfile`, to optimize the container image build times.\n\n6. Set the **command** to use `fastapi run`, which uses Uvicorn underneath.\n\n `CMD` takes a list of strings, each of these strings is what you would type in the command line separated by spaces.\n\n This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`.\n\n/// tip\n\nReview what each line does by clicking each number bubble in the code. 👆\n\n///\n\n/// warning\n\nMake sure to **always** use the **exec form** of the `CMD` instruction, as explained below.\n\n///\n\n#### Use `CMD` - Exec Form { #use-cmd-exec-form }\n\nThe [`CMD`](https://docs.docker.com/reference/dockerfile/#cmd) Docker instruction can be written using two forms:\n\n✅ **Exec** form:\n\n```Dockerfile\n# ✅ Do this\nCMD [\"fastapi\", \"run\", \"app/main.py\", \"--port\", \"80\"]\n```\n\n⛔️ **Shell** form:\n\n```Dockerfile\n# ⛔️ Don't do this\nCMD fastapi run app/main.py --port 80\n```\n\nMake sure to always use the **exec** form to ensure that FastAPI can shutdown gracefully and [lifespan events](../advanced/events.md) are triggered.\n\nYou can read more about it in the [Docker docs for shell and exec form](https://docs.docker.com/reference/dockerfile/#shell-and-exec-form).\n\nThis can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: [Why do my services take 10 seconds to recreate or stop?](https://docs.docker.com/compose/faq/#why-do-my-services-take-10-seconds-to-recreate-or-stop).\n\n#### Directory Structure { #directory-structure }\n\nYou should now have a directory structure like:\n\n```\n.\n├── app\n│   ├── __init__.py\n│ └── main.py\n├── Dockerfile\n└── requirements.txt\n```\n\n#### Behind a TLS Termination Proxy { #behind-a-tls-termination-proxy }\n\nIf you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn (through the FastAPI CLI) to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc.\n\n```Dockerfile\nCMD [\"fastapi\", \"run\", \"app/main.py\", \"--proxy-headers\", \"--port\", \"80\"]\n```\n\n#### Docker Cache { #docker-cache }\n\nThere's an important trick in this `Dockerfile`, we first copy the **file with the dependencies alone**, not the rest of the code. Let me tell you why that is.\n\n```Dockerfile\nCOPY ./requirements.txt /code/requirements.txt\n```\n\nDocker and other tools **build** these container images **incrementally**, adding **one layer on top of the other**, starting from the top of the `Dockerfile` and adding any files created by each of the instructions of the `Dockerfile`.\n\nDocker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **reuse the same layer** created the last time, instead of copying the file again and creating a new layer from scratch.\n\nJust avoiding the copy of files doesn't necessarily improve things too much, but because it used the cache for that step, it can **use the cache for the next step**. For example, it could use the cache for the instruction that installs dependencies with:\n\n```Dockerfile\nRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt\n```\n\nThe file with the package requirements **won't change frequently**. So, by copying only that file, Docker will be able to **use the cache** for that step.\n\nAnd then, Docker will be able to **use the cache for the next step** that downloads and installs those dependencies. And here's where we **save a lot of time**. ✨ ...and avoid boredom waiting. 😪😆\n\nDownloading and installing the package dependencies **could take minutes**, but using the **cache** would **take seconds** at most.\n\nAnd as you would be building the container image again and again during development to check that your code changes are working, there's a lot of accumulated time this would save.\n\nThen, near the end of the `Dockerfile`, we copy all the code. As this is what **changes most frequently**, we put it near the end, because almost always, anything after this step will not be able to use the cache.\n\n```Dockerfile\nCOPY ./app /code/app\n```\n\n### Build the Docker Image { #build-the-docker-image }\n\nNow that all the files are in place, let's build the container image.\n\n* Go to the project directory (in where your `Dockerfile` is, containing your `app` directory).\n* Build your FastAPI image:\n\n
\n\n```console\n$ docker build -t myimage .\n\n---> 100%\n```\n\n
\n\n/// tip\n\nNotice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image.\n\nIn this case, it's the same current directory (`.`).\n\n///\n\n### Start the Docker Container { #start-the-docker-container }\n\n* Run a container based on your image:\n\n
\n\n```console\n$ docker run -d --name mycontainer -p 80:80 myimage\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Build a Docker Image for FastAPI { #build-a-docker-image-for-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L94-L352", "start_line": 94, "end_line": 352} {"id": "docs/en/docs/deployment/docker.md::Check it { #check-it }::L353", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Check it { #check-it }\n## Check it { #check-it }\n\nYou should be able to check it in your Docker container's URL, for example: [http://192.168.99.100/items/5?q=somequery](http://192.168.99.100/items/5?q=somequery) or [http://127.0.0.1/items/5?q=somequery](http://127.0.0.1/items/5?q=somequery) (or equivalent, using your Docker host).\n\nYou will see something like:\n\n```JSON\n{\"item_id\": 5, \"q\": \"somequery\"}\n```", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Check it { #check-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L353-L362", "start_line": 353, "end_line": 362} {"id": "docs/en/docs/deployment/docker.md::Interactive API docs { #interactive-api-docs }::L363", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Interactive API docs { #interactive-api-docs }\n## Interactive API docs { #interactive-api-docs }\n\nNow you can go to [http://192.168.99.100/docs](http://192.168.99.100/docs) or [http://127.0.0.1/docs](http://127.0.0.1/docs) (or equivalent, using your Docker host).\n\nYou will see the automatic interactive API documentation (provided by [Swagger UI](https://github.com/swagger-api/swagger-ui)):\n\n![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Interactive API docs { #interactive-api-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L363-L370", "start_line": 363, "end_line": 370} {"id": "docs/en/docs/deployment/docker.md::Alternative API docs { #alternative-api-docs }::L371", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Alternative API docs { #alternative-api-docs }\n## Alternative API docs { #alternative-api-docs }\n\nAnd you can also go to [http://192.168.99.100/redoc](http://192.168.99.100/redoc) or [http://127.0.0.1/redoc](http://127.0.0.1/redoc) (or equivalent, using your Docker host).\n\nYou will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):\n\n![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Alternative API docs { #alternative-api-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L371-L378", "start_line": 371, "end_line": 378} {"id": "docs/en/docs/deployment/docker.md::Build a Docker Image with a Single-File FastAPI { #build-a-docker-image-with-a-single-file-fastapi }::L379", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Build a Docker Image with a Single-File FastAPI { #build-a-docker-image-with-a-single-file-fastapi }\n## Build a Docker Image with a Single-File FastAPI { #build-a-docker-image-with-a-single-file-fastapi }\n\nIf your FastAPI is a single file, for example, `main.py` without an `./app` directory, your file structure could look like this:\n\n```\n.\n├── Dockerfile\n├── main.py\n└── requirements.txt\n```\n\nThen you would just have to change the corresponding paths to copy the file inside the `Dockerfile`:\n\n```{ .dockerfile .annotate hl_lines=\"10 13\" }\nFROM python:3.14\n\nWORKDIR /code\n\nCOPY ./requirements.txt /code/requirements.txt\n\nRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt\n\n# (1)!\nCOPY ./main.py /code/\n\n# (2)!\nCMD [\"fastapi\", \"run\", \"main.py\", \"--port\", \"80\"]\n```\n\n1. Copy the `main.py` file to the `/code` directory directly (without any `./app` directory).\n\n2. Use `fastapi run` to serve your application in the single file `main.py`.\n\nWhen you pass the file to `fastapi run` it will detect automatically that it is a single file and not part of a package and will know how to import it and serve your FastAPI app. 😎", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Build a Docker Image with a Single-File FastAPI { #build-a-docker-image-with-a-single-file-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L379-L413", "start_line": 379, "end_line": 413} {"id": "docs/en/docs/deployment/docker.md::Deployment Concepts { #deployment-concepts }::L414", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Deployment Concepts { #deployment-concepts }\n## Deployment Concepts { #deployment-concepts }\n\nLet's talk again about some of the same [Deployment Concepts](concepts.md) in terms of containers.\n\nContainers are mainly a tool to simplify the process of **building and deploying** an application, but they don't enforce a particular approach to handle these **deployment concepts**, and there are several possible strategies.\n\nThe **good news** is that with each different strategy there's a way to cover all of the deployment concepts. 🎉\n\nLet's review these **deployment concepts** in terms of containers:\n\n* HTTPS\n* Running on startup\n* Restarts\n* Replication (the number of processes running)\n* Memory\n* Previous steps before starting", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Deployment Concepts { #deployment-concepts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L414-L430", "start_line": 414, "end_line": 430} {"id": "docs/en/docs/deployment/docker.md::HTTPS { #https }::L431", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: HTTPS { #https }\n## HTTPS { #https }\n\nIf we focus just on the **container image** for a FastAPI application (and later the running **container**), HTTPS normally would be handled **externally** by another tool.\n\nIt could be another container, for example with [Traefik](https://traefik.io/), handling **HTTPS** and **automatic** acquisition of **certificates**.\n\n/// tip\n\nTraefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it.\n\n///\n\nAlternatively, HTTPS could be handled by a cloud provider as one of their services (while still running the application in a container).", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "HTTPS { #https }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L431-L444", "start_line": 431, "end_line": 444} {"id": "docs/en/docs/deployment/docker.md::Running on Startup and Restarts { #running-on-startup-and-restarts }::L445", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Running on Startup and Restarts { #running-on-startup-and-restarts }\n## Running on Startup and Restarts { #running-on-startup-and-restarts }\n\nThere is normally another tool in charge of **starting and running** your container.\n\nIt could be **Docker** directly, **Docker Compose**, **Kubernetes**, a **cloud service**, etc.\n\nIn most (or all) cases, there's a simple option to enable running the container on startup and enabling restarts on failures. For example, in Docker, it's the command line option `--restart`.\n\nWithout using containers, making applications run on startup and with restarts can be cumbersome and difficult. But when **working with containers** in most cases that functionality is included by default. ✨", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Running on Startup and Restarts { #running-on-startup-and-restarts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L445-L454", "start_line": 445, "end_line": 454} {"id": "docs/en/docs/deployment/docker.md::Replication - Number of Processes { #replication-number-of-processes }::L455", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Replication - Number of Processes { #replication-number-of-processes }\n## Replication - Number of Processes { #replication-number-of-processes }\n\nIf you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container.\n\nOne of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**.\n\nIn those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers.\n\n### Load Balancer { #load-balancer }\n\nWhen using containers, you would normally have some component **listening on the main port**. It could possibly be another container that is also a **TLS Termination Proxy** to handle **HTTPS** or some similar tool.\n\nAs this component would take the **load** of requests and distribute that among the workers in a (hopefully) **balanced** way, it is also commonly called a **Load Balancer**.\n\n/// tip\n\nThe same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**.\n\n///\n\nAnd when working with containers, the same system you use to start and manage them would already have internal tools to transmit the **network communication** (e.g. HTTP requests) from that **load balancer** (that could also be a **TLS Termination Proxy**) to the container(s) with your app.\n\n### One Load Balancer - Multiple Worker Containers { #one-load-balancer-multiple-worker-containers }\n\nWhen working with **Kubernetes** or similar distributed container management systems, using their internal networking mechanisms would allow the single **load balancer** that is listening on the main **port** to transmit communication (requests) to possibly **multiple containers** running your app.\n\nEach of these containers running your app would normally have **just one process** (e.g. a Uvicorn process running your FastAPI application). They would all be **identical containers**, running the same thing, but each with its own process, memory, etc. That way you would take advantage of **parallelization** in **different cores** of the CPU, or even in **different machines**.\n\nAnd the distributed container system with the **load balancer** would **distribute the requests** to each one of the containers with your app **in turns**. So, each request could be handled by one of the multiple **replicated containers** running your app.\n\nAnd normally this **load balancer** would be able to handle requests that go to *other* apps in your cluster (e.g. to a different domain, or under a different URL path prefix), and would transmit that communication to the right containers for *that other* application running in your cluster.\n\n### One Process per Container { #one-process-per-container }\n\nIn this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level.\n\nSo, in this case, you **would not** want to have multiple workers in the container, for example with the `--workers` command line option. You would want to have just a **single Uvicorn process** per container (but probably multiple containers).\n\nHaving another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system.\n\n### Containers with Multiple Processes and Special Cases { #containers-with-multiple-processes-and-special-cases }\n\nOf course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside.\n\nIn those cases, you can use the `--workers` command line option to set the number of workers that you want to run:\n\n```{ .dockerfile .annotate }\nFROM python:3.14\n\nWORKDIR /code\n\nCOPY ./requirements.txt /code/requirements.txt\n\nRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt\n\nCOPY ./app /code/app\n\n# (1)!\nCMD [\"fastapi\", \"run\", \"app/main.py\", \"--port\", \"80\", \"--workers\", \"4\"]\n```\n\n1. Here we use the `--workers` command line option to set the number of workers to 4.\n\nHere are some examples of when that could make sense:\n\n#### A Simple App { #a-simple-app }\n\nYou could want a process manager in the container if your application is **simple enough** that you can run it on a **single server**, not a cluster.\n\n#### Docker Compose { #docker-compose }\n\nYou could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**.\n\nThen you could want to have **a single container** with a **process manager** starting **several worker processes** inside.\n\n---\n\nThe main point is, **none** of these are **rules written in stone** that you have to blindly follow. You can use these ideas to **evaluate your own use case** and decide what is the best approach for your system, checking out how to manage the concepts of:\n\n* Security - HTTPS\n* Running on startup\n* Restarts\n* Replication (the number of processes running)\n* Memory\n* Previous steps before starting", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Replication - Number of Processes { #replication-number-of-processes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L455-L540", "start_line": 455, "end_line": 540} {"id": "docs/en/docs/deployment/docker.md::Memory { #memory }::L541", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Memory { #memory }\n## Memory { #memory }\n\nIf you run **a single process per container** you will have a more or less well-defined, stable, and limited amount of memory consumed by each of those containers (more than one if they are replicated).\n\nAnd then you can set those same memory limits and requirements in your configurations for your container management system (for example in **Kubernetes**). That way it will be able to **replicate the containers** in the **available machines** taking into account the amount of memory needed by them, and the amount available in the machines in the cluster.\n\nIf your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that run on **each machine** (and maybe add more machines to your cluster).\n\nIf you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available.", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Memory { #memory }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L541-L550", "start_line": 541, "end_line": 550} {"id": "docs/en/docs/deployment/docker.md::Previous Steps Before Starting and Containers { #previous-steps-before-starting-and-containers }::L551", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Previous Steps Before Starting and Containers { #previous-steps-before-starting-and-containers }\n## Previous Steps Before Starting and Containers { #previous-steps-before-starting-and-containers }\n\nIf you are using containers (e.g. Docker, Kubernetes), then there are two main approaches you can use.\n\n### Multiple Containers { #multiple-containers }\n\nIf you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers.\n\n/// note\n\nIf you are using Kubernetes, this would probably be an [Init Container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/).\n\n///\n\nIf in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process.\n\n### Single Container { #single-container }\n\nIf you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app.\n\n### Base Docker Image { #base-docker-image }\n\nThere used to be an official FastAPI Docker image: [tiangolo/uvicorn-gunicorn-fastapi](https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker). But it is now deprecated. ⛔️\n\nYou should probably **not** use this base Docker image (or any other similar one).\n\nIf you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi).\n\nAnd if you need to have multiple workers, you can simply use the `--workers` command line option.\n\n/// note | Technical Details\n\nThe Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn, which added quite some complexity, just to have Gunicorn manage and restart the Uvicorn worker processes.\n\nBut now that Uvicorn (and the `fastapi` command) support using `--workers`, there's no reason to use a base Docker image instead of building your own (it's pretty much the same amount of code 😅).\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Previous Steps Before Starting and Containers { #previous-steps-before-starting-and-containers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L551-L588", "start_line": 551, "end_line": 588} {"id": "docs/en/docs/deployment/docker.md::Deploy the Container Image { #deploy-the-container-image }::L589", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Deploy the Container Image { #deploy-the-container-image }\n## Deploy the Container Image { #deploy-the-container-image }\n\nAfter having a Container (Docker) Image there are several ways to deploy it.\n\nFor example:\n\n* With **Docker Compose** in a single server\n* With a **Kubernetes** cluster\n* With a Docker Swarm Mode cluster\n* With another tool like Nomad\n* With a cloud service that takes your container image and deploys it", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Deploy the Container Image { #deploy-the-container-image }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L589-L600", "start_line": 589, "end_line": 600} {"id": "docs/en/docs/deployment/docker.md::Docker Image with `uv` { #docker-image-with-uv }::L601", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Docker Image with `uv` { #docker-image-with-uv }\n## Docker Image with `uv` { #docker-image-with-uv }\n\nIf you are using [uv](https://github.com/astral-sh/uv) to install and manage your project, you can follow their [uv Docker guide](https://docs.astral.sh/uv/guides/integration/docker/).", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Docker Image with `uv` { #docker-image-with-uv }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L601-L604", "start_line": 601, "end_line": 604} {"id": "docs/en/docs/deployment/docker.md::Recap { #recap }::L605", "text": "# Doc: docs/en/docs/deployment/docker.md | Page: FastAPI in Containers - Docker { #fastapi-in-containers-docker } | Section: Recap { #recap }\n## Recap { #recap }\n\nUsing container systems (e.g. with **Docker** and **Kubernetes**) it becomes fairly straightforward to handle all the **deployment concepts**:\n\n* HTTPS\n* Running on startup\n* Restarts\n* Replication (the number of processes running)\n* Memory\n* Previous steps before starting\n\nIn most cases, you probably won't want to use any base image, and instead **build a container image from scratch** based on the official Python Docker image.\n\nTaking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎", "source_type": "doc", "path": "docs/en/docs/deployment/docker.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/docker.md#L605-L618", "start_line": 605, "end_line": 618} {"id": "docs/en/docs/deployment/fastapicloud.md::FastAPI Cloud { #fastapi-cloud }::L1", "text": "# Doc: docs/en/docs/deployment/fastapicloud.md | Page: FastAPI Cloud { #fastapi-cloud } | Section: FastAPI Cloud { #fastapi-cloud }\n# FastAPI Cloud { #fastapi-cloud }\n\nYou can deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with just **one command**. 🚀\n\n
\n\n```console\n$ fastapi deploy\n\nDeploying to FastAPI Cloud...\n\n✅ Deployment successful!\n\n🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev\n```\n\n
\n\nThe CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.\n\nThat's it! Now you can access your app at that URL. ✨", "source_type": "doc", "path": "docs/en/docs/deployment/fastapicloud.md", "symbol": "FastAPI Cloud { #fastapi-cloud }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/fastapicloud.md#L1-L22", "start_line": 1, "end_line": 22} {"id": "docs/en/docs/deployment/fastapicloud.md::About FastAPI Cloud { #about-fastapi-cloud }::L23", "text": "# Doc: docs/en/docs/deployment/fastapicloud.md | Page: FastAPI Cloud { #fastapi-cloud } | Section: About FastAPI Cloud { #about-fastapi-cloud }\n## About FastAPI Cloud { #about-fastapi-cloud }\n\n**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**.\n\nIt streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort.\n\nIt brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉\n\nIt will also take care of most of the things you would need when deploying an app, like:\n\n* HTTPS\n* Replication, with autoscaling based on requests\n* etc.\n\nFastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨", "source_type": "doc", "path": "docs/en/docs/deployment/fastapicloud.md", "symbol": "About FastAPI Cloud { #about-fastapi-cloud }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/fastapicloud.md#L23-L38", "start_line": 23, "end_line": 38} {"id": "docs/en/docs/deployment/fastapicloud.md::Deploy to other cloud providers { #deploy-to-other-cloud-providers }::L39", "text": "# Doc: docs/en/docs/deployment/fastapicloud.md | Page: FastAPI Cloud { #fastapi-cloud } | Section: Deploy to other cloud providers { #deploy-to-other-cloud-providers }\n## Deploy to other cloud providers { #deploy-to-other-cloud-providers }\n\nFastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.\n\nFollow your cloud provider's guides to deploy FastAPI apps with them. 🤓", "source_type": "doc", "path": "docs/en/docs/deployment/fastapicloud.md", "symbol": "Deploy to other cloud providers { #deploy-to-other-cloud-providers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/fastapicloud.md#L39-L44", "start_line": 39, "end_line": 44} {"id": "docs/en/docs/deployment/fastapicloud.md::Deploy your own server { #deploy-your-own-server }::L45", "text": "# Doc: docs/en/docs/deployment/fastapicloud.md | Page: FastAPI Cloud { #fastapi-cloud } | Section: Deploy your own server { #deploy-your-own-server }\n## Deploy your own server { #deploy-your-own-server }\n\nI will also teach you later in this **Deployment** guide all the details, so you can understand what is going on, what needs to happen, or how to deploy FastAPI apps on your own, also with your own servers. 🤓", "source_type": "doc", "path": "docs/en/docs/deployment/fastapicloud.md", "symbol": "Deploy your own server { #deploy-your-own-server }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/fastapicloud.md#L45-L47", "start_line": 45, "end_line": 47} {"id": "docs/en/docs/deployment/https.md::About HTTPS { #about-https }::L1", "text": "# Doc: docs/en/docs/deployment/https.md | Page: About HTTPS { #about-https } | Section: About HTTPS { #about-https }\n# About HTTPS { #about-https }\n\nIt is easy to assume that HTTPS is something that is just \"enabled\" or not.\n\nBut it is way more complex than that.\n\n/// tip\n\nIf you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques.\n\n///\n\nTo **learn the basics of HTTPS**, from a consumer perspective, check [https://howhttps.works/](https://howhttps.works/).\n\nNow, from a **developer's perspective**, here are several things to keep in mind while thinking about HTTPS:\n\n* For HTTPS, **the server** needs to **have \"certificates\"** generated by a **third party**.\n * Those certificates are actually **acquired** from the third party, not \"generated\".\n* Certificates have a **lifetime**.\n * They **expire**.\n * And then they need to be **renewed**, **acquired again** from the third party.\n* The encryption of the connection happens at the **TCP level**.\n * That's one layer **below HTTP**.\n * So, the **certificate and encryption** handling is done **before HTTP**.\n* **TCP doesn't know about \"domains\"**. Only about IP addresses.\n * The information about the **specific domain** requested goes in the **HTTP data**.\n* The **HTTPS certificates** \"certify\" a **certain domain**, but the protocol and encryption happen at the TCP level, **before knowing** which domain is being dealt with.\n* **By default**, that would mean that you can only have **one HTTPS certificate per IP address**.\n * No matter how big your server is or how small each application you have on it might be.\n * There is a **solution** to this, however.\n* There's an **extension** to the **TLS** protocol (the one handling the encryption at the TCP level, before HTTP) called **[SNI](https://en.wikipedia.org/wiki/Server_Name_Indication)**.\n * This SNI extension allows one single server (with a **single IP address**) to have **several HTTPS certificates** and serve **multiple HTTPS domains/applications**.\n * For this to work, a **single** component (program) running on the server, listening on the **public IP address**, must have **all the HTTPS certificates** in the server.\n* **After** obtaining a secure connection, the communication protocol is **still HTTP**.\n * The contents are **encrypted**, even though they are being sent with the **HTTP protocol**.\n\nIt is a common practice to have **one program/HTTP server** running on the server (the machine, host, etc.) and **managing all the HTTPS parts**: receiving the **encrypted HTTPS requests**, sending the **decrypted HTTP requests** to the actual HTTP application running in the same server (the **FastAPI** application, in this case), take the **HTTP response** from the application, **encrypt it** using the appropriate **HTTPS certificate** and sending it back to the client using **HTTPS**. This server is often called a **[TLS Termination Proxy](https://en.wikipedia.org/wiki/TLS_termination_proxy)**.\n\nSome of the options you could use as a TLS Termination Proxy are:\n\n* Traefik (that can also handle certificate renewals)\n* Caddy (that can also handle certificate renewals)\n* Nginx\n* HAProxy", "source_type": "doc", "path": "docs/en/docs/deployment/https.md", "symbol": "About HTTPS { #about-https }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/https.md#L1-L45", "start_line": 1, "end_line": 45} {"id": "docs/en/docs/deployment/https.md::Let's Encrypt { #lets-encrypt }::L46", "text": "# Doc: docs/en/docs/deployment/https.md | Page: About HTTPS { #about-https } | Section: Let's Encrypt { #lets-encrypt }\n## Let's Encrypt { #lets-encrypt }\n\nBefore Let's Encrypt, these **HTTPS certificates** were sold by trusted third parties.\n\nThe process to acquire one of these certificates used to be cumbersome, require quite some paperwork and the certificates were quite expensive.\n\nBut then **[Let's Encrypt](https://letsencrypt.org/)** was created.\n\nIt is a project from the Linux Foundation. It provides **HTTPS certificates for free**, in an automated way. These certificates use all the standard cryptographic security, and are short-lived (about 3 months), so the **security is actually better** because of their reduced lifespan.\n\nThe domains are securely verified and the certificates are generated automatically. This also allows automating the renewal of these certificates.\n\nThe idea is to automate the acquisition and renewal of these certificates so that you can have **secure HTTPS, for free, forever**.", "source_type": "doc", "path": "docs/en/docs/deployment/https.md", "symbol": "Let's Encrypt { #lets-encrypt }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/https.md#L46-L59", "start_line": 46, "end_line": 59} {"id": "docs/en/docs/deployment/https.md::HTTPS for Developers { #https-for-developers }::L60", "text": "# Doc: docs/en/docs/deployment/https.md | Page: About HTTPS { #about-https } | Section: HTTPS for Developers { #https-for-developers }\n## HTTPS for Developers { #https-for-developers }\n\nHere's an example of how an HTTPS API could look, step by step, paying attention mainly to the ideas important for developers.\n\n### Domain Name { #domain-name }\n\nIt would probably all start by you **acquiring** some **domain name**. Then, you would configure it in a DNS server (possibly your same cloud provider).\n\nYou would probably get a cloud server (a virtual machine) or something similar, and it would have a fixed **public IP address**.\n\nIn the DNS server(s) you would configure a record (an \"`A record`\") to point **your domain** to the public **IP address of your server**.\n\nYou would probably do this just once, the first time, when setting everything up.\n\n/// tip\n\nThis Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here.\n\n///\n\n### DNS { #dns }\n\nNow let's focus on all the actual HTTPS parts.\n\nFirst, the browser would check with the **DNS servers** what is the **IP for the domain**, in this case, `someapp.example.com`.\n\nThe DNS servers would tell the browser to use some specific **IP address**. That would be the public IP address used by your server, that you configured in the DNS servers.\n\n\n\n### TLS Handshake Start { #tls-handshake-start }\n\nThe browser would then communicate with that IP address on **port 443** (the HTTPS port).\n\nThe first part of the communication is just to establish the connection between the client and the server and to decide the cryptographic keys they will use, etc.\n\n\n\nThis interaction between the client and the server to establish the TLS connection is called the **TLS handshake**.\n\n### TLS with SNI Extension { #tls-with-sni-extension }\n\n**Only one process** in the server can be listening on a specific **port** in a specific **IP address**. There could be other processes listening on other ports in the same IP address, but only one for each combination of IP address and port.\n\nTLS (HTTPS) uses the specific port `443` by default. So that's the port we would need.\n\nAs only one process can be listening on this port, the process that would do it would be the **TLS Termination Proxy**.\n\nThe TLS Termination Proxy would have access to one or more **TLS certificates** (HTTPS certificates).\n\nUsing the **SNI extension** discussed above, the TLS Termination Proxy would check which of the TLS (HTTPS) certificates available it should use for this connection, using the one that matches the domain expected by the client.\n\nIn this case, it would use the certificate for `someapp.example.com`.\n\n\n\nThe client already **trusts** the entity that generated that TLS certificate (in this case Let's Encrypt, but we'll see about that later), so it can **verify** that the certificate is valid.\n\nThen, using the certificate, the client and the TLS Termination Proxy **decide how to encrypt** the rest of the **TCP communication**. This completes the **TLS Handshake** part.\n\nAfter this, the client and the server have an **encrypted TCP connection**, this is what TLS provides. And then they can use that connection to start the actual **HTTP communication**.\n\nAnd that's what **HTTPS** is, it's just plain **HTTP** inside a **secure TLS connection** instead of a pure (unencrypted) TCP connection.\n\n/// tip\n\nNotice that the encryption of the communication happens at the **TCP level**, not at the HTTP level.\n\n///\n\n### HTTPS Request { #https-request }\n\nNow that the client and server (specifically the browser and the TLS Termination Proxy) have an **encrypted TCP connection**, they can start the **HTTP communication**.\n\nSo, the client sends an **HTTPS request**. This is just an HTTP request through an encrypted TLS connection.\n\n\n\n### Decrypt the Request { #decrypt-the-request }\n\nThe TLS Termination Proxy would use the encryption agreed to **decrypt the request**, and would transmit the **plain (decrypted) HTTP request** to the process running the application (for example a process with Uvicorn running the FastAPI application).\n\n\n\n### HTTP Response { #http-response }\n\nThe application would process the request and send a **plain (unencrypted) HTTP response** to the TLS Termination Proxy.\n\n\n\n### HTTPS Response { #https-response }\n\nThe TLS Termination Proxy would then **encrypt the response** using the cryptography agreed before (that started with the certificate for `someapp.example.com`), and send it back to the browser.\n\nNext, the browser would verify that the response is valid and encrypted with the right cryptographic key, etc. It would then **decrypt the response** and process it.\n\n\n\nThe client (browser) will know that the response comes from the correct server because it is using the cryptography they agreed using the **HTTPS certificate** before.\n\n### Multiple Applications { #multiple-applications }\n\nIn the same server (or servers), there could be **multiple applications**, for example, other API programs or a database.\n\nOnly one process can be handling the specific IP and port (the TLS Termination Proxy in our example) but the other applications/processes can be running on the server(s) too, as long as they don't try to use the same **combination of public IP and port**.\n\n\n\nThat way, the TLS Termination Proxy could handle HTTPS and certificates for **multiple domains**, for multiple applications, and then transmit the requests to the right application in each case.\n\n### Certificate Renewal { #certificate-renewal }\n\nAt some point in the future, each certificate would **expire** (about 3 months after acquiring it).\n\nAnd then, there would be another program (in some cases it's another program, in some cases it could be the same TLS Termination Proxy) that would talk to Let's Encrypt, and renew the certificate(s).\n\n\n\nThe **TLS certificates** are **associated with a domain name**, not with an IP address.\n\nSo, to renew the certificates, the renewal program needs to **prove** to the authority (Let's Encrypt) that it indeed **\"owns\" and controls that domain**.\n\nTo do that, and to accommodate different application needs, there are several ways it can do it. Some popular ways are:\n\n* **Modify some DNS records**.\n * For this, the renewal program needs to support the APIs of the DNS provider, so, depending on the DNS provider you are using, this might or might not be an option.\n* **Run as a server** (at least during the certificate acquisition process) on the public IP address associated with the domain.\n * As we said above, only one process can be listening on a specific IP and port.\n * This is one of the reasons why it's very useful when the same TLS Termination Proxy also takes care of the certificate renewal process.\n * Otherwise, you might have to stop the TLS Termination Proxy momentarily, start the renewal program to acquire the certificates, then configure them with the TLS Termination Proxy, and then restart the TLS Termination Proxy. This is not ideal, as your app(s) will not be available during the time that the TLS Termination Proxy is off.\n\nAll this renewal process, while still serving the app, is one of the main reasons why you would want to have a **separate system to handle HTTPS** with a TLS Termination Proxy instead of just using the TLS certificates with the application server directly (e.g. Uvicorn).", "source_type": "doc", "path": "docs/en/docs/deployment/https.md", "symbol": "HTTPS for Developers { #https-for-developers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/https.md#L60-L192", "start_line": 60, "end_line": 192} {"id": "docs/en/docs/deployment/https.md::Proxy Forwarded Headers { #proxy-forwarded-headers }::L193", "text": "# Doc: docs/en/docs/deployment/https.md | Page: About HTTPS { #about-https } | Section: Proxy Forwarded Headers { #proxy-forwarded-headers }\n## Proxy Forwarded Headers { #proxy-forwarded-headers }\n\nWhen using a proxy to handle HTTPS, your **application server** (for example Uvicorn via FastAPI CLI) doesn't know anything about the HTTPS process, it communicates with plain HTTP with the **TLS Termination Proxy**.\n\nThis **proxy** would normally set some HTTP headers on the fly before transmitting the request to the **application server**, to let the application server know that the request is being **forwarded** by the proxy.\n\n/// note | Technical Details\n\nThe proxy headers are:\n\n* [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For)\n* [X-Forwarded-Proto](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Proto)\n* [X-Forwarded-Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Host)\n\n///\n\nNevertheless, as the **application server** doesn't know it is behind a trusted **proxy**, by default, it wouldn't trust those headers.\n\nBut you can configure the **application server** to trust the *forwarded* headers sent by the **proxy**. If you are using FastAPI CLI, you can use the *CLI Option* `--forwarded-allow-ips` to tell it from which IPs it should trust those *forwarded* headers.\n\nFor example, if the **application server** is only receiving communication from the trusted **proxy**, you can set it to `--forwarded-allow-ips=\"*\"` to make it trust all incoming IPs, as it will only receive requests from whatever is the IP used by the **proxy**.\n\nThis way the application would be able to know what is its own public URL, if it is using HTTPS, the domain, etc.\n\nThis would be useful for example to properly handle redirects.\n\n/// tip\n\nYou can learn more about this in the documentation for [Behind a Proxy - Enable Proxy Forwarded Headers](../advanced/behind-a-proxy.md#enable-proxy-forwarded-headers)\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/https.md", "symbol": "Proxy Forwarded Headers { #proxy-forwarded-headers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/https.md#L193-L224", "start_line": 193, "end_line": 224} {"id": "docs/en/docs/deployment/https.md::Recap { #recap }::L225", "text": "# Doc: docs/en/docs/deployment/https.md | Page: About HTTPS { #about-https } | Section: Recap { #recap }\n## Recap { #recap }\n\nHaving **HTTPS** is very important, and quite **critical** in most cases. Most of the effort you as a developer have to put around HTTPS is just about **understanding these concepts** and how they work.\n\nBut once you know the basic information of **HTTPS for developers** you can easily combine and configure different tools to help you manage everything in a simple way.\n\nIn some of the next chapters, I'll show you several concrete examples of how to set up **HTTPS** for **FastAPI** applications. 🔒", "source_type": "doc", "path": "docs/en/docs/deployment/https.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/https.md#L225-L231", "start_line": 225, "end_line": 231} {"id": "docs/en/docs/deployment/index.md::Deployment { #deployment }::L1", "text": "# Doc: docs/en/docs/deployment/index.md | Page: Deployment { #deployment } | Section: Deployment { #deployment }\n# Deployment { #deployment }\n\nDeploying a **FastAPI** application is relatively easy.", "source_type": "doc", "path": "docs/en/docs/deployment/index.md", "symbol": "Deployment { #deployment }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/index.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/deployment/index.md::What Does Deployment Mean { #what-does-deployment-mean }::L5", "text": "# Doc: docs/en/docs/deployment/index.md | Page: Deployment { #deployment } | Section: What Does Deployment Mean { #what-does-deployment-mean }\n## What Does Deployment Mean { #what-does-deployment-mean }\n\nTo **deploy** an application means to perform the necessary steps to make it **available to the users**.\n\nFor a **web API**, it normally involves putting it in a **remote machine**, with a **server program** that provides good performance, stability, etc, so that your **users** can **access** the application efficiently and without interruptions or problems.\n\nThis is in contrast to the **development** stages, where you are constantly changing the code, breaking it and fixing it, stopping and restarting the development server, etc.", "source_type": "doc", "path": "docs/en/docs/deployment/index.md", "symbol": "What Does Deployment Mean { #what-does-deployment-mean }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/index.md#L5-L12", "start_line": 5, "end_line": 12} {"id": "docs/en/docs/deployment/index.md::Deployment Strategies { #deployment-strategies }::L13", "text": "# Doc: docs/en/docs/deployment/index.md | Page: Deployment { #deployment } | Section: Deployment Strategies { #deployment-strategies }\n## Deployment Strategies { #deployment-strategies }\n\nThere are several ways to do it depending on your specific use case and the tools that you use.\n\nYou could **deploy a server** yourself using a combination of tools, you could use a **cloud service** that does part of the work for you, or other possible options.\n\nFor example, we, the team behind FastAPI, built [**FastAPI Cloud**](https://fastapicloud.com), to make deploying FastAPI apps to the cloud as streamlined as possible, with the same developer experience of working with FastAPI.\n\nI will show you some of the main concepts you should probably keep in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application).\n\nYou will see more details to keep in mind and some of the techniques to do it in the next sections. ✨", "source_type": "doc", "path": "docs/en/docs/deployment/index.md", "symbol": "Deployment Strategies { #deployment-strategies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/index.md#L13-L23", "start_line": 13, "end_line": 23} {"id": "docs/en/docs/deployment/manually.md::Run a Server Manually { #run-a-server-manually }::L1", "text": "# Doc: docs/en/docs/deployment/manually.md | Page: Run a Server Manually { #run-a-server-manually } | Section: Run a Server Manually { #run-a-server-manually }\n# Run a Server Manually { #run-a-server-manually }", "source_type": "doc", "path": "docs/en/docs/deployment/manually.md", "symbol": "Run a Server Manually { #run-a-server-manually }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/manually.md#L1-L2", "start_line": 1, "end_line": 2} {"id": "docs/en/docs/deployment/manually.md::Use the `fastapi run` Command { #use-the-fastapi-run-command }::L3", "text": "# Doc: docs/en/docs/deployment/manually.md | Page: Run a Server Manually { #run-a-server-manually } | Section: Use the `fastapi run` Command { #use-the-fastapi-run-command }\n## Use the `fastapi run` Command { #use-the-fastapi-run-command }\n\nIn short, use `fastapi run` to serve your FastAPI application:\n\n
\n\n```console\n$ fastapi run main.py\n\n FastAPI Starting production server 🚀\n\n Searching for package file structure from directories\n with __init__.py files\n Importing from /home/user/code/awesomeapp\n\n module 🐍 main.py\n\n code Importing the FastAPI app object from the module with\n the following code:\n\n from main import app\n\n app Using import string: main:app\n\n server Server started at http://0.0.0.0:8000\n server Documentation at http://0.0.0.0:8000/docs\n\n Logs:\n\n INFO Started server process [2306215]\n INFO Waiting for application startup.\n INFO Application startup complete.\n INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C\n to quit)\n```\n\n
\n\nThat would work for most of the cases. 😎\n\nYou could use that command for example to start your **FastAPI** app in a container, in a server, etc.", "source_type": "doc", "path": "docs/en/docs/deployment/manually.md", "symbol": "Use the `fastapi run` Command { #use-the-fastapi-run-command }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/manually.md#L3-L44", "start_line": 3, "end_line": 44} {"id": "docs/en/docs/deployment/manually.md::ASGI Servers { #asgi-servers }::L45", "text": "# Doc: docs/en/docs/deployment/manually.md | Page: Run a Server Manually { #run-a-server-manually } | Section: ASGI Servers { #asgi-servers }\n## ASGI Servers { #asgi-servers }\n\nLet's go a little deeper into the details.\n\nFastAPI uses a standard for building Python web frameworks and servers called ASGI. FastAPI is an ASGI web framework.\n\nThe main thing you need to run a **FastAPI** application (or any other ASGI application) in a remote server machine is an ASGI server program like **Uvicorn**, this is the one that comes by default in the `fastapi` command.\n\nThere are several alternatives, including:\n\n* [Uvicorn](https://www.uvicorn.dev/): a high performance ASGI server.\n* [Hypercorn](https://hypercorn.readthedocs.io/): an ASGI server compatible with HTTP/2 and Trio among other features.\n* [Daphne](https://github.com/django/daphne): the ASGI server built for Django Channels.\n* [Granian](https://github.com/emmett-framework/granian): A Rust HTTP server for Python applications.", "source_type": "doc", "path": "docs/en/docs/deployment/manually.md", "symbol": "ASGI Servers { #asgi-servers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/manually.md#L45-L59", "start_line": 45, "end_line": 59} {"id": "docs/en/docs/deployment/manually.md::Server Machine and Server Program { #server-machine-and-server-program }::L60", "text": "# Doc: docs/en/docs/deployment/manually.md | Page: Run a Server Manually { #run-a-server-manually } | Section: Server Machine and Server Program { #server-machine-and-server-program }\n## Server Machine and Server Program { #server-machine-and-server-program }\n\nThere's a small detail about names to keep in mind. 💡\n\nThe word \"**server**\" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn).\n\nJust keep in mind that when you read \"server\" in general, it could refer to one of those two things.\n\nWhen referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs.", "source_type": "doc", "path": "docs/en/docs/deployment/manually.md", "symbol": "Server Machine and Server Program { #server-machine-and-server-program }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/manually.md#L60-L69", "start_line": 60, "end_line": 69} {"id": "docs/en/docs/deployment/manually.md::Install the Server Program { #install-the-server-program }::L70", "text": "# Doc: docs/en/docs/deployment/manually.md | Page: Run a Server Manually { #run-a-server-manually } | Section: Install the Server Program { #install-the-server-program }\n## Install the Server Program { #install-the-server-program }\n\nWhen you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command.\n\nBut you can also install an ASGI server manually.\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then you can install the server application.\n\nFor example, to install Uvicorn:\n\n
\n\n```console\n$ pip install \"uvicorn[standard]\"\n\n---> 100%\n```\n\n
\n\nA similar process would apply to any other ASGI server program.\n\n/// tip\n\nBy adding the `standard`, Uvicorn will install and use some recommended extra dependencies.\n\nThat includes `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.\n\nWhen you install FastAPI with something like `pip install \"fastapi[standard]\"` you already get `uvicorn[standard]` as well.\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/manually.md", "symbol": "Install the Server Program { #install-the-server-program }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/manually.md#L70-L101", "start_line": 70, "end_line": 101} {"id": "docs/en/docs/deployment/manually.md::Run the Server Program { #run-the-server-program }::L102", "text": "# Doc: docs/en/docs/deployment/manually.md | Page: Run a Server Manually { #run-a-server-manually } | Section: Run the Server Program { #run-the-server-program }\n## Run the Server Program { #run-the-server-program }\n\nIf you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application:\n\n
\n\n```console\n$ uvicorn main:app --host 0.0.0.0 --port 80\n\nINFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)\n```\n\n
\n\n/// note\n\nThe command `uvicorn main:app` refers to:\n\n* `main`: the file `main.py` (the Python \"module\").\n* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.\n\nIt is equivalent to:\n\n```Python\nfrom main import app\n```\n\n///\n\nEach alternative ASGI server program would have a similar command, you can read more in their respective documentation.\n\n/// warning\n\nUvicorn and other servers support a `--reload` option that is useful during development.\n\nThe `--reload` option consumes much more resources, is more unstable, etc.\n\nIt helps a lot during **development**, but you **shouldn't** use it in **production**.\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/manually.md", "symbol": "Run the Server Program { #run-the-server-program }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/manually.md#L102-L142", "start_line": 102, "end_line": 142} {"id": "docs/en/docs/deployment/manually.md::Deployment Concepts { #deployment-concepts }::L143", "text": "# Doc: docs/en/docs/deployment/manually.md | Page: Run a Server Manually { #run-a-server-manually } | Section: Deployment Concepts { #deployment-concepts }\n## Deployment Concepts { #deployment-concepts }\n\nThese examples run the server program (e.g Uvicorn), starting **a single process**, listening on all the IPs (`0.0.0.0`) on a predefined port (e.g. `80`).\n\nThis is the basic idea. But you will probably want to take care of some additional things, like:\n\n* Security - HTTPS\n* Running on startup\n* Restarts\n* Replication (the number of processes running)\n* Memory\n* Previous steps before starting\n\nI'll tell you more about each of these concepts, how to think about them, and some concrete examples with strategies to handle them in the next chapters. 🚀", "source_type": "doc", "path": "docs/en/docs/deployment/manually.md", "symbol": "Deployment Concepts { #deployment-concepts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/manually.md#L143-L156", "start_line": 143, "end_line": 156} {"id": "docs/en/docs/deployment/server-workers.md::Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers }::L1", "text": "# Doc: docs/en/docs/deployment/server-workers.md | Page: Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers } | Section: Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers }\n# Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers }\n\nLet's check back those deployment concepts from before:\n\n* Security - HTTPS\n* Running on startup\n* Restarts\n* **Replication (the number of processes running)**\n* Memory\n* Previous steps before starting\n\nUp to this point, with all the tutorials in the docs, you have probably been running a **server program**, for example, using the `fastapi` command, that runs Uvicorn, running a **single process**.\n\nWhen deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests.\n\nAs you saw in the previous chapter about [Deployment Concepts](concepts.md), there are multiple strategies you can use.\n\nHere I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly.\n\n/// note\n\nIf you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md).\n\nIn particular, when running on **Kubernetes** you will probably **not** want to use workers and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter.\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/server-workers.md", "symbol": "Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/server-workers.md#L1-L27", "start_line": 1, "end_line": 27} {"id": "docs/en/docs/deployment/server-workers.md::Multiple Workers { #multiple-workers }::L28", "text": "# Doc: docs/en/docs/deployment/server-workers.md | Page: Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers } | Section: Multiple Workers { #multiple-workers }\n## Multiple Workers { #multiple-workers }\n\nYou can start multiple workers with the `--workers` command line option:\n\n//// tab | `fastapi`\n\nIf you use the `fastapi` command:\n\n
\n\n```console\n$ fastapi run --workers 4 main.py\n\n FastAPI Starting production server 🚀\n\n Searching for package file structure from directories with\n __init__.py files\n Importing from /home/user/code/awesomeapp\n\n module 🐍 main.py\n\n code Importing the FastAPI app object from the module with the\n following code:\n\n from main import app\n\n app Using import string: main:app\n\n server Server started at http://0.0.0.0:8000\n server Documentation at http://0.0.0.0:8000/docs\n\n Logs:\n\n INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to\n quit)\n INFO Started parent process [27365]\n INFO Started server process [27368]\n INFO Started server process [27369]\n INFO Started server process [27370]\n INFO Started server process [27367]\n INFO Waiting for application startup.\n INFO Waiting for application startup.\n INFO Waiting for application startup.\n INFO Waiting for application startup.\n INFO Application startup complete.\n INFO Application startup complete.\n INFO Application startup complete.\n INFO Application startup complete.\n```\n\n
\n\n////\n\n//// tab | `uvicorn`\n\nIf you prefer to use the `uvicorn` command directly:\n\n
\n\n```console\n$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4\nINFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit)\nINFO: Started parent process [27365]\nINFO: Started server process [27368]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\nINFO: Started server process [27369]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\nINFO: Started server process [27370]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\nINFO: Started server process [27367]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\n```\n\n
\n\n////\n\nThe only new option here is `--workers` telling Uvicorn to start 4 worker processes.\n\nYou can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`.", "source_type": "doc", "path": "docs/en/docs/deployment/server-workers.md", "symbol": "Multiple Workers { #multiple-workers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/server-workers.md#L28-L113", "start_line": 28, "end_line": 113} {"id": "docs/en/docs/deployment/server-workers.md::Deployment Concepts { #deployment-concepts }::L114", "text": "# Doc: docs/en/docs/deployment/server-workers.md | Page: Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers } | Section: Deployment Concepts { #deployment-concepts }\n## Deployment Concepts { #deployment-concepts }\n\nHere you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**.\n\nFrom the list of deployment concepts from above, using workers would mainly help with the **replication** part, and a little bit with the **restarts**, but you still need to take care of the others:\n\n* **Security - HTTPS**\n* **Running on startup**\n* ***Restarts***\n* Replication (the number of processes running)\n* **Memory**\n* **Previous steps before starting**", "source_type": "doc", "path": "docs/en/docs/deployment/server-workers.md", "symbol": "Deployment Concepts { #deployment-concepts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/server-workers.md#L114-L126", "start_line": 114, "end_line": 126} {"id": "docs/en/docs/deployment/server-workers.md::Containers and Docker { #containers-and-docker }::L127", "text": "# Doc: docs/en/docs/deployment/server-workers.md | Page: Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers } | Section: Containers and Docker { #containers-and-docker }\n## Containers and Docker { #containers-and-docker }\n\nIn the next chapter about [FastAPI in Containers - Docker](docker.md) I'll explain some strategies you could use to handle the other **deployment concepts**.\n\nI'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**.", "source_type": "doc", "path": "docs/en/docs/deployment/server-workers.md", "symbol": "Containers and Docker { #containers-and-docker }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/server-workers.md#L127-L132", "start_line": 127, "end_line": 132} {"id": "docs/en/docs/deployment/server-workers.md::Recap { #recap }::L133", "text": "# Doc: docs/en/docs/deployment/server-workers.md | Page: Server Workers - Uvicorn with Workers { #server-workers-uvicorn-with-workers } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**.\n\nYou could use these tools and ideas if you are setting up **your own deployment system** while taking care of the other deployment concepts yourself.\n\nCheck out the next chapter to learn about **FastAPI** with containers (e.g. Docker and Kubernetes). You will see that those tools have simple ways to solve the other **deployment concepts** as well. ✨", "source_type": "doc", "path": "docs/en/docs/deployment/server-workers.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/server-workers.md#L133-L139", "start_line": 133, "end_line": 139} {"id": "docs/en/docs/deployment/versions.md::About FastAPI versions { #about-fastapi-versions }::L1", "text": "# Doc: docs/en/docs/deployment/versions.md | Page: About FastAPI versions { #about-fastapi-versions } | Section: About FastAPI versions { #about-fastapi-versions }\n# About FastAPI versions { #about-fastapi-versions }\n\n**FastAPI** is already being used in production in many applications and systems. And the test coverage is kept at 100%. But its development is still moving quickly.\n\nNew features are added frequently, bugs are fixed regularly, and the code is still continuously improving.\n\nThat's why the current versions are still `0.x.x`, this reflects that each version could potentially have breaking changes. This follows the [Semantic Versioning](https://semver.org/) conventions.\n\nYou can create production applications with **FastAPI** right now (and you have probably been doing it for some time), you just have to make sure that you use a version that works correctly with the rest of your code.", "source_type": "doc", "path": "docs/en/docs/deployment/versions.md", "symbol": "About FastAPI versions { #about-fastapi-versions }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/versions.md#L1-L10", "start_line": 1, "end_line": 10} {"id": "docs/en/docs/deployment/versions.md::Pin your `fastapi` version { #pin-your-fastapi-version }::L11", "text": "# Doc: docs/en/docs/deployment/versions.md | Page: About FastAPI versions { #about-fastapi-versions } | Section: Pin your `fastapi` version { #pin-your-fastapi-version }\n## Pin your `fastapi` version { #pin-your-fastapi-version }\n\nThe first thing you should do is to \"pin\" the version of **FastAPI** you are using to the specific latest version that you know works correctly for your application.\n\nFor example, let's say you are using version `0.112.0` in your app.\n\nIf you use a `requirements.txt` file you could specify the version with:\n\n```txt\nfastapi[standard]==0.112.0\n```\n\nthat would mean that you would use exactly the version `0.112.0`.\n\nOr you could also pin it with:\n\n```txt\nfastapi[standard]>=0.112.0,<0.113.0\n```\n\nthat would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted.\n\nIf you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages.", "source_type": "doc", "path": "docs/en/docs/deployment/versions.md", "symbol": "Pin your `fastapi` version { #pin-your-fastapi-version }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/versions.md#L11-L34", "start_line": 11, "end_line": 34} {"id": "docs/en/docs/deployment/versions.md::Available versions { #available-versions }::L35", "text": "# Doc: docs/en/docs/deployment/versions.md | Page: About FastAPI versions { #about-fastapi-versions } | Section: Available versions { #available-versions }\n## Available versions { #available-versions }\n\nYou can see the available versions (e.g. to check what is the current latest) in the [Release Notes](../release-notes.md).", "source_type": "doc", "path": "docs/en/docs/deployment/versions.md", "symbol": "Available versions { #available-versions }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/versions.md#L35-L38", "start_line": 35, "end_line": 38} {"id": "docs/en/docs/deployment/versions.md::About versions { #about-versions }::L39", "text": "# Doc: docs/en/docs/deployment/versions.md | Page: About FastAPI versions { #about-fastapi-versions } | Section: About versions { #about-versions }\n## About versions { #about-versions }\n\nFollowing the Semantic Versioning conventions, any version below `1.0.0` could potentially add breaking changes.\n\nFastAPI also follows the convention that any \"PATCH\" version change is for bug fixes and non-breaking changes.\n\n/// tip\n\nThe \"PATCH\" is the last number, for example, in `0.2.3`, the PATCH version is `3`.\n\n///\n\nSo, you should be able to pin to a version like:\n\n```txt\nfastapi>=0.45.0,<0.46.0\n```\n\nBreaking changes and new features are added in \"MINOR\" versions.\n\n/// tip\n\nThe \"MINOR\" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`.\n\n///", "source_type": "doc", "path": "docs/en/docs/deployment/versions.md", "symbol": "About versions { #about-versions }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/versions.md#L39-L64", "start_line": 39, "end_line": 64} {"id": "docs/en/docs/deployment/versions.md::Upgrading the FastAPI versions { #upgrading-the-fastapi-versions }::L65", "text": "# Doc: docs/en/docs/deployment/versions.md | Page: About FastAPI versions { #about-fastapi-versions } | Section: Upgrading the FastAPI versions { #upgrading-the-fastapi-versions }\n## Upgrading the FastAPI versions { #upgrading-the-fastapi-versions }\n\nYou should add tests for your app.\n\nWith **FastAPI** it's very easy (thanks to Starlette), check the docs: [Testing](../tutorial/testing.md)\n\nAfter you have tests, then you can upgrade the **FastAPI** version to a more recent one, and make sure that all your code is working correctly by running your tests.\n\nIf everything is working, or after you make the necessary changes, and all your tests are passing, then you can pin your `fastapi` to that new recent version.", "source_type": "doc", "path": "docs/en/docs/deployment/versions.md", "symbol": "Upgrading the FastAPI versions { #upgrading-the-fastapi-versions }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/versions.md#L65-L74", "start_line": 65, "end_line": 74} {"id": "docs/en/docs/deployment/versions.md::About Starlette { #about-starlette }::L75", "text": "# Doc: docs/en/docs/deployment/versions.md | Page: About FastAPI versions { #about-fastapi-versions } | Section: About Starlette { #about-starlette }\n## About Starlette { #about-starlette }\n\nYou shouldn't pin the version of `starlette`.\n\nDifferent versions of **FastAPI** will use a specific newer version of Starlette.\n\nSo, you can just let **FastAPI** use the correct Starlette version.", "source_type": "doc", "path": "docs/en/docs/deployment/versions.md", "symbol": "About Starlette { #about-starlette }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/versions.md#L75-L82", "start_line": 75, "end_line": 82} {"id": "docs/en/docs/deployment/versions.md::About Pydantic { #about-pydantic }::L83", "text": "# Doc: docs/en/docs/deployment/versions.md | Page: About FastAPI versions { #about-fastapi-versions } | Section: About Pydantic { #about-pydantic }\n## About Pydantic { #about-pydantic }\n\nPydantic includes the tests for **FastAPI** with its own tests, so new versions of Pydantic (above `1.0.0`) are always compatible with FastAPI.\n\nYou can pin Pydantic to any version above `1.0.0` that works for you.\n\nFor example:\n\n```txt\npydantic>=2.7.0,<3.0.0\n```", "source_type": "doc", "path": "docs/en/docs/deployment/versions.md", "symbol": "About Pydantic { #about-pydantic }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/deployment/versions.md#L83-L93", "start_line": 83, "end_line": 93} {"id": "docs/en/docs/editor-support.md::Editor Support { #editor-support }::L1", "text": "# Doc: docs/en/docs/editor-support.md | Page: Editor Support { #editor-support } | Section: Editor Support { #editor-support }\n# Editor Support { #editor-support }\n\nThe official [FastAPI Extension](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode) enhances your FastAPI development workflow with *path operation* discovery, navigation, as well as FastAPI Cloud deployment, and live log streaming.\n\nFor more details about the extension, refer to the README on the [GitHub repository](https://github.com/fastapi/fastapi-vscode).", "source_type": "doc", "path": "docs/en/docs/editor-support.md", "symbol": "Editor Support { #editor-support }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/editor-support.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/editor-support.md::Setup and Installation { #setup-and-installation }::L7", "text": "# Doc: docs/en/docs/editor-support.md | Page: Editor Support { #editor-support } | Section: Setup and Installation { #setup-and-installation }\n## Setup and Installation { #setup-and-installation }\n\nThe **FastAPI Extension** is available for both [VS Code](https://code.visualstudio.com/) and [Cursor](https://www.cursor.com/). It can be installed directly from the Extensions panel in each editor by searching for \"FastAPI\" and selecting the extension published by **FastAPI Labs**. The extension also works in browser-based editors such as [vscode.dev](https://vscode.dev) and [github.dev](https://github.dev).\n\n### Application Discovery { #application-discovery }\n\nBy default, the extension will automatically discover FastAPI applications in your workspace by scanning for files that instantiate `FastAPI()`. If auto-detection doesn't work for your project structure, you can specify an entrypoint via `[tool.fastapi]` in `pyproject.toml` or the `fastapi.entryPoint` VS Code setting using module notation (e.g. `myapp.main:app`).", "source_type": "doc", "path": "docs/en/docs/editor-support.md", "symbol": "Setup and Installation { #setup-and-installation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/editor-support.md#L7-L14", "start_line": 7, "end_line": 14} {"id": "docs/en/docs/editor-support.md::Features { #features }::L15", "text": "# Doc: docs/en/docs/editor-support.md | Page: Editor Support { #editor-support } | Section: Features { #features }\n## Features { #features }\n\n- **Path Operation Explorer** - A sidebar tree view of all *path operations* in your application. Click to jump to any route or router definition.\n- **Route Search** - Search by path, method, or name with Ctrl + Shift + E (on macOS: Cmd + Shift + E).\n- **CodeLens Navigation** - Clickable links above test client calls (e.g. `client.get('/items')`) that jump to the matching *path operation* for quick navigation between tests and implementation.\n- **Deploy to FastAPI Cloud** - One-click deployment of your app to [FastAPI Cloud](https://fastapicloud.com/).\n- **Stream Application Logs** - Real-time log streaming from your FastAPI Cloud-deployed application with level filtering and text search.\n\nIf you'd like to familiarize yourself with the extension's features, you can check out the extension walkthrough by opening the Command Palette (Ctrl + Shift + P or on macOS: Cmd + Shift + P) and selecting \"Welcome: Open walkthrough...\" and then choosing the \"Get started with FastAPI\" walkthrough.", "source_type": "doc", "path": "docs/en/docs/editor-support.md", "symbol": "Features { #features }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/editor-support.md#L15-L23", "start_line": 15, "end_line": 23} {"id": "docs/en/docs/environment-variables.md::Environment Variables { #environment-variables }::L1", "text": "# Doc: docs/en/docs/environment-variables.md | Page: Environment Variables { #environment-variables } | Section: Environment Variables { #environment-variables }\n# Environment Variables { #environment-variables }\n\n/// tip\n\nIf you already know what \"environment variables\" are and how to use them, feel free to skip this.\n\n///\n\nAn environment variable (also known as \"**env var**\") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well).\n\nEnvironment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.", "source_type": "doc", "path": "docs/en/docs/environment-variables.md", "symbol": "Environment Variables { #environment-variables }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/environment-variables.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/environment-variables.md::Create and Use Env Vars { #create-and-use-env-vars }::L13", "text": "# Doc: docs/en/docs/environment-variables.md | Page: Environment Variables { #environment-variables } | Section: Create and Use Env Vars { #create-and-use-env-vars }\n## Create and Use Env Vars { #create-and-use-env-vars }\n\nYou can **create** and use environment variables in the **shell (terminal)**, without needing Python:\n\n//// tab | Linux, macOS, Windows Bash\n\n
\n\n```console\n// You could create an env var MY_NAME with\n$ export MY_NAME=\"Wade Wilson\"\n\n// Then you could use it with other programs, like\n$ echo \"Hello $MY_NAME\"\n\nHello Wade Wilson\n```\n\n
\n\n////\n\n//// tab | Windows PowerShell\n\n
\n\n```console\n// Create an env var MY_NAME\n$ $Env:MY_NAME = \"Wade Wilson\"\n\n// Use it with other programs, like\n$ echo \"Hello $Env:MY_NAME\"\n\nHello Wade Wilson\n```\n\n
\n\n////", "source_type": "doc", "path": "docs/en/docs/environment-variables.md", "symbol": "Create and Use Env Vars { #create-and-use-env-vars }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/environment-variables.md#L13-L52", "start_line": 13, "end_line": 52} {"id": "docs/en/docs/environment-variables.md::Read env vars in Python { #read-env-vars-in-python }::L53", "text": "# Doc: docs/en/docs/environment-variables.md | Page: Environment Variables { #environment-variables } | Section: Read env vars in Python { #read-env-vars-in-python }\n## Read env vars in Python { #read-env-vars-in-python }\n\nYou could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**.\n\nFor example you could have a file `main.py` with:\n\n```Python hl_lines=\"3\"\nimport os\n\nname = os.getenv(\"MY_NAME\", \"World\")\nprint(f\"Hello {name} from Python\")\n```\n\n/// tip\n\nThe second argument to [`os.getenv()`](https://docs.python.org/3.8/library/os.html#os.getenv) is the default value to return.\n\nIf not provided, it's `None` by default, here we provide `\"World\"` as the default value to use.\n\n///\n\nThen you could call that Python program:\n\n//// tab | Linux, macOS, Windows Bash\n\n
\n\n```console\n// Here we don't set the env var yet\n$ python main.py\n\n// As we didn't set the env var, we get the default value\n\nHello World from Python\n\n// But if we create an environment variable first\n$ export MY_NAME=\"Wade Wilson\"\n\n// And then call the program again\n$ python main.py\n\n// Now it can read the environment variable\n\nHello Wade Wilson from Python\n```\n\n
\n\n////\n\n//// tab | Windows PowerShell\n\n
\n\n```console\n// Here we don't set the env var yet\n$ python main.py\n\n// As we didn't set the env var, we get the default value\n\nHello World from Python\n\n// But if we create an environment variable first\n$ $Env:MY_NAME = \"Wade Wilson\"\n\n// And then call the program again\n$ python main.py\n\n// Now it can read the environment variable\n\nHello Wade Wilson from Python\n```\n\n
\n\n////\n\nAs environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**.\n\nYou can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration.\n\nTo do that, create it right before the program itself, on the same line:\n\n
\n\n```console\n// Create an env var MY_NAME in line for this program call\n$ MY_NAME=\"Wade Wilson\" python main.py\n\n// Now it can read the environment variable\n\nHello Wade Wilson from Python\n\n// The env var no longer exists afterwards\n$ python main.py\n\nHello World from Python\n```\n\n
\n\n/// tip\n\nYou can read more about it at [The Twelve-Factor App: Config](https://12factor.net/config).\n\n///", "source_type": "doc", "path": "docs/en/docs/environment-variables.md", "symbol": "Read env vars in Python { #read-env-vars-in-python }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/environment-variables.md#L53-L159", "start_line": 53, "end_line": 159} {"id": "docs/en/docs/environment-variables.md::Types and Validation { #types-and-validation }::L160", "text": "# Doc: docs/en/docs/environment-variables.md | Page: Environment Variables { #environment-variables } | Section: Types and Validation { #types-and-validation }\n## Types and Validation { #types-and-validation }\n\nThese environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, such as Linux, Windows, and macOS).\n\nThat means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code.\n\nYou will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md).", "source_type": "doc", "path": "docs/en/docs/environment-variables.md", "symbol": "Types and Validation { #types-and-validation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/environment-variables.md#L160-L167", "start_line": 160, "end_line": 167} {"id": "docs/en/docs/environment-variables.md::`PATH` Environment Variable { #path-environment-variable }::L168", "text": "# Doc: docs/en/docs/environment-variables.md | Page: Environment Variables { #environment-variables } | Section: `PATH` Environment Variable { #path-environment-variable }\n## `PATH` Environment Variable { #path-environment-variable }\n\nThere is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run.\n\nThe value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows.\n\nFor example, the `PATH` environment variable could look like this:\n\n//// tab | Linux, macOS\n\n```plaintext\n/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\n```\n\nThis means that the system should look for programs in the directories:\n\n* `/usr/local/bin`\n* `/usr/bin`\n* `/bin`\n* `/usr/sbin`\n* `/sbin`\n\n////\n\n//// tab | Windows\n\n```plaintext\nC:\\Program Files\\Python312\\Scripts;C:\\Program Files\\Python312;C:\\Windows\\System32\n```\n\nThis means that the system should look for programs in the directories:\n\n* `C:\\Program Files\\Python312\\Scripts`\n* `C:\\Program Files\\Python312`\n* `C:\\Windows\\System32`\n\n////\n\nWhen you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable.\n\nFor example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list.\n\nIf it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**.\n\n### Installing Python and Updating the `PATH` { #installing-python-and-updating-the-path }\n\nWhen you install Python, you might be asked if you want to update the `PATH` environment variable.\n\n//// tab | Linux, macOS\n\nLet's say you install Python and it ends up in a directory `/opt/custompython/bin`.\n\nIf you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable.\n\nIt could look like this:\n\n```plaintext\n/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin\n```\n\nThis way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.\n\n////\n\n//// tab | Windows\n\nLet's say you install Python and it ends up in a directory `C:\\opt\\custompython\\bin`.\n\nIf you say yes to update the `PATH` environment variable, then the installer will add `C:\\opt\\custompython\\bin` to the `PATH` environment variable.\n\n```plaintext\nC:\\Program Files\\Python312\\Scripts;C:\\Program Files\\Python312;C:\\Windows\\System32;C:\\opt\\custompython\\bin\n```\n\nThis way, when you type `python` in the terminal, the system will find the Python program in `C:\\opt\\custompython\\bin` (the last directory) and use that one.\n\n////\n\nSo, if you type:\n\n
\n\n```console\n$ python\n```\n\n
\n\n//// tab | Linux, macOS\n\nThe system will **find** the `python` program in `/opt/custompython/bin` and run it.\n\nIt would be roughly equivalent to typing:\n\n
\n\n```console\n$ /opt/custompython/bin/python\n```\n\n
\n\n////\n\n//// tab | Windows\n\nThe system will **find** the `python` program in `C:\\opt\\custompython\\bin\\python` and run it.\n\nIt would be roughly equivalent to typing:\n\n
\n\n```console\n$ C:\\opt\\custompython\\bin\\python\n```\n\n
\n\n////\n\nThis information will be useful when learning about [Virtual Environments](virtual-environments.md).", "source_type": "doc", "path": "docs/en/docs/environment-variables.md", "symbol": "`PATH` Environment Variable { #path-environment-variable }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/environment-variables.md#L168-L289", "start_line": 168, "end_line": 289} {"id": "docs/en/docs/environment-variables.md::Conclusion { #conclusion }::L290", "text": "# Doc: docs/en/docs/environment-variables.md | Page: Environment Variables { #environment-variables } | Section: Conclusion { #conclusion }\n## Conclusion { #conclusion }\n\nWith this you should have a basic understanding of what **environment variables** are and how to use them in Python.\n\nYou can also read more about them in the [Wikipedia for Environment Variable](https://en.wikipedia.org/wiki/Environment_variable).\n\nIn many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them.\n\nFor example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md).", "source_type": "doc", "path": "docs/en/docs/environment-variables.md", "symbol": "Conclusion { #conclusion }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/environment-variables.md#L290-L298", "start_line": 290, "end_line": 298} {"id": "docs/en/docs/external-links.md::External Links::L1", "text": "# Doc: docs/en/docs/external-links.md | Page: External Links | Section: External Links\n---\ninclude_yaml:\n topic_repos: data/topic_repos.yml\n---\n\n# External Links\n\n**FastAPI** has a great community constantly growing.\n\nThere are many posts, articles, tools, and projects related to **FastAPI**.\n\nYou could easily use a search engine or video platform to find many resources related to FastAPI.\n\n/// note\n\nBefore, this page used to list links to external articles.\n\nBut now that FastAPI is the backend framework with the most GitHub stars across languages, and the most starred and used framework in Python, it no longer makes sense to attempt to list all articles written about it.\n\n///", "source_type": "doc", "path": "docs/en/docs/external-links.md", "symbol": "External Links", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/external-links.md#L1-L21", "start_line": 1, "end_line": 21} {"id": "docs/en/docs/external-links.md::GitHub Repositories::L22", "text": "# Doc: docs/en/docs/external-links.md | Page: External Links | Section: GitHub Repositories\n## GitHub Repositories\n\nMost starred [GitHub repositories with the topic `fastapi`](https://github.com/topics/fastapi):\n\n{% for repo in topic_repos %}\n\n★ {{repo.stars}} - {{repo.name}} by @{{repo.owner_login}}.\n\n{% endfor %}", "source_type": "doc", "path": "docs/en/docs/external-links.md", "symbol": "GitHub Repositories", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/external-links.md#L22-L30", "start_line": 22, "end_line": 30} {"id": "docs/en/docs/fastapi-cli.md::FastAPI CLI { #fastapi-cli }::L1", "text": "# Doc: docs/en/docs/fastapi-cli.md | Page: FastAPI CLI { #fastapi-cli } | Section: FastAPI CLI { #fastapi-cli }\n# FastAPI CLI { #fastapi-cli }\n\n**FastAPI CLI** is a command line program that you can use to serve your FastAPI app, manage your FastAPI project, and more.\n\nWhen you install FastAPI (e.g. with `pip install \"fastapi[standard]\"`), it comes with a command line program you can run in the terminal.\n\nTo run your FastAPI app for development, you can use the `fastapi dev` command:\n\n
\n\n```console\n$ fastapi dev\n\n FastAPI Starting development server 🚀\n\n Searching for package file structure from directories with\n __init__.py files\n Importing from /home/user/code/awesomeapp\n\n module 🐍 main.py\n\n code Importing the FastAPI app object from the module with the\n following code:\n\n from main import app\n\n app Using import string: main:app\n\n server Server started at http://127.0.0.1:8000\n server Documentation at http://127.0.0.1:8000/docs\n\n tip Running in development mode, for production use:\n fastapi run\n\n Logs:\n\n INFO Will watch for changes in these directories:\n ['/home/user/code/awesomeapp']\n INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to\n quit)\n INFO Started reloader process [383138] using WatchFiles\n INFO Started server process [383153]\n INFO Waiting for application startup.\n INFO Application startup complete.\n```\n\n
\n\n/// tip\n\nFor production you would use `fastapi run` instead of `fastapi dev`. 🚀\n\n///\n\nInternally, **FastAPI CLI** uses [Uvicorn](https://www.uvicorn.dev), a high-performance, production-ready, ASGI server. 😎\n\nThe `fastapi` CLI will try to detect automatically the FastAPI app to run, assuming it's an object called `app` in a file `main.py` (or a couple other variants).\n\nBut you can configure explicitly the app to use.", "source_type": "doc", "path": "docs/en/docs/fastapi-cli.md", "symbol": "FastAPI CLI { #fastapi-cli }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-cli.md#L1-L60", "start_line": 1, "end_line": 60} {"id": "docs/en/docs/fastapi-cli.md::Configure the app `entrypoint` in `pyproject.toml` { #configure-the-app-entrypoint-in-pyproject-toml }::L61", "text": "# Doc: docs/en/docs/fastapi-cli.md | Page: FastAPI CLI { #fastapi-cli } | Section: Configure the app `entrypoint` in `pyproject.toml` { #configure-the-app-entrypoint-in-pyproject-toml }\n## Configure the app `entrypoint` in `pyproject.toml` { #configure-the-app-entrypoint-in-pyproject-toml }\n\nYou can configure where your app is located in a `pyproject.toml` file like:\n\n```toml\n[tool.fastapi]\nentrypoint = \"main:app\"\n```\n\nThat `entrypoint` will tell the `fastapi` command that it should import the app like:\n\n```python\nfrom main import app\n```\n\nIf your code was structured like:\n\n```\n.\n├── backend\n│   ├── main.py\n│   ├── __init__.py\n```\n\nThen you would set the `entrypoint` as:\n\n```toml\n[tool.fastapi]\nentrypoint = \"backend.main:app\"\n```\n\nwhich would be equivalent to:\n\n```python\nfrom backend.main import app\n```\n\n### `fastapi dev` with path or with `--entrypoint` CLI option { #fastapi-dev-with-path-or-with-entrypoint-cli-option }\n\nYou can also pass the file path to the `fastapi dev` command, and it will guess the FastAPI app object to use:\n\n```console\n$ fastapi dev main.py\n```\n\nOr, you can also pass the `--entrypoint` option to the `fastapi dev` command:\n\n```console\n$ fastapi dev --entrypoint main:app\n```\n\nBut you would have to remember to pass the correct path\\entrypoint every time you call the `fastapi` command.\n\nAdditionally, other tools might not be able to find it, for example the [VS Code Extension](editor-support.md) or [FastAPI Cloud](https://fastapicloud.com), so it is recommended to use the `entrypoint` in `pyproject.toml`.", "source_type": "doc", "path": "docs/en/docs/fastapi-cli.md", "symbol": "Configure the app `entrypoint` in `pyproject.toml` { #configure-the-app-entrypoint-in-pyproject-toml }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-cli.md#L61-L115", "start_line": 61, "end_line": 115} {"id": "docs/en/docs/fastapi-cli.md::`fastapi dev` { #fastapi-dev }::L116", "text": "# Doc: docs/en/docs/fastapi-cli.md | Page: FastAPI CLI { #fastapi-cli } | Section: `fastapi dev` { #fastapi-dev }\n## `fastapi dev` { #fastapi-dev }\n\nRunning `fastapi dev` initiates development mode.\n\nBy default, **auto-reload** is enabled, automatically reloading the server when you make changes to your code. This is resource-intensive and could be less stable than when it's disabled. You should only use it for development. It also listens on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`).", "source_type": "doc", "path": "docs/en/docs/fastapi-cli.md", "symbol": "`fastapi dev` { #fastapi-dev }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-cli.md#L116-L121", "start_line": 116, "end_line": 121} {"id": "docs/en/docs/fastapi-cli.md::`fastapi run` { #fastapi-run }::L122", "text": "# Doc: docs/en/docs/fastapi-cli.md | Page: FastAPI CLI { #fastapi-cli } | Section: `fastapi run` { #fastapi-run }\n## `fastapi run` { #fastapi-run }\n\nExecuting `fastapi run` starts FastAPI in production mode.\n\nBy default, **auto-reload** is disabled. It also listens on the IP address `0.0.0.0`, which means all the available IP addresses, this way it will be publicly accessible to anyone that can communicate with the machine. This is how you would normally run it in production, for example, in a container.\n\nIn most cases you would (and should) have a \"termination proxy\" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself.\n\n/// tip\n\nYou can learn more about it in the [deployment documentation](deployment/index.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/fastapi-cli.md", "symbol": "`fastapi run` { #fastapi-run }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-cli.md#L122-L134", "start_line": 122, "end_line": 134} {"id": "docs/en/docs/fastapi-people.md::FastAPI People::L1", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: FastAPI People\n---\nhide:\n - navigation\n\ninclude_yaml:\n github_sponsors: data/github_sponsors.yml\n people: data/people.yml\n contributors: data/contributors.yml\n translation_reviewers: data/translation_reviewers.yml\n skip_users: data/skip_users.yml\n members: data/members.yml\n sponsors_badge: data/sponsors_badge.yml\n sponsors: data/sponsors.yml\n---\n\n# FastAPI People\n\nFastAPI has an amazing community that welcomes people from all backgrounds.", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "FastAPI People", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L1-L19", "start_line": 1, "end_line": 19} {"id": "docs/en/docs/fastapi-people.md::Creator::L20", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: Creator\n## Creator\n\nHey! 👋\n\nThis is me:\n\n
\n{% for user in people.maintainers %}\n\n
@{{ contributors.tiangolo.login }}
Answers: {{ user.answers }}
Pull Requests: {{ contributors.tiangolo.count }}
\n{% endfor %}\n\n
\n\nI'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Follow the author](help-fastapi.md#follow-the-author).\n\n...But here I want to show you the community.\n\n---\n\n**FastAPI** receives a lot of support from the community. And I want to highlight their contributions.\n\nThese are the people that:\n\n* [Help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github).\n* Create or review Pull Requests.\n* Help [manage the repository](https://tiangolo.com/open-source/management-tasks/) (team members).\n\nAll these tasks help maintain the repository.\n\nA round of applause to them. 👏 🙇", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "Creator", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L20-L51", "start_line": 20, "end_line": 51} {"id": "docs/en/docs/fastapi-people.md::Team::L52", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: Team\n## Team\n\nThis is the current list of team members. 😎\n\nThey have different levels of involvement and permissions, they can perform [repository management tasks](https://tiangolo.com/open-source/management-tasks/) and together we [manage the FastAPI repository](./management.md).\n\n
\n\n{% for user in members[\"members\"] %}\n\n
@{{ user.login }}
\n\n{% endfor %}\n\n
\n\nAlthough the team members have the permissions to perform privileged tasks, all the help from others maintaining FastAPI is very much appreciated! 🙇‍♂️", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "Team", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L52-L69", "start_line": 52, "end_line": 69} {"id": "docs/en/docs/fastapi-people.md::FastAPI Experts::L70", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: FastAPI Experts\n## FastAPI Experts\n\nThese are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github). 🙇\n\nThey have proven to be **FastAPI Experts** by helping many others. ✨\n\n/// tip\n\nYou could become an official FastAPI Expert too!\n\nJust [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github). 🤓\n\n///\n\nYou can see the **FastAPI Experts** for:\n\n* [Last Month](#fastapi-experts-last-month) 🤓\n* [3 Months](#fastapi-experts-3-months) 😎\n* [6 Months](#fastapi-experts-6-months) 🧐\n* [1 Year](#fastapi-experts-1-year) 🧑‍🔬\n* [**All Time**](#fastapi-experts-all-time) 🧙\n\n### FastAPI Experts - Last Month\n\nThese are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last month. 🤓\n\n
\n\n{% for user in people.last_month_experts[:10] %}\n\n{% if user.login not in skip_users %}\n\n
@{{ user.login }}
Questions replied: {{ user.count }}
\n\n{% endif %}\n\n{% endfor %}\n\n
\n\n### FastAPI Experts - 3 Months\n\nThese are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last 3 months. 😎\n\n
\n\n{% for user in people.three_months_experts[:10] %}\n\n{% if user.login not in skip_users %}\n\n
@{{ user.login }}
Questions replied: {{ user.count }}
\n\n{% endif %}\n\n{% endfor %}\n\n
\n\n### FastAPI Experts - 6 Months\n\nThese are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last 6 months. 🧐\n\n
\n\n{% for user in people.six_months_experts[:10] %}\n\n{% if user.login not in skip_users %}\n\n
@{{ user.login }}
Questions replied: {{ user.count }}
\n\n{% endif %}\n\n{% endfor %}\n\n
\n\n### FastAPI Experts - 1 Year\n\nThese are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) during the last year. 🧑‍🔬\n\n
\n\n{% for user in people.one_year_experts[:20] %}\n\n{% if user.login not in skip_users %}\n\n
@{{ user.login }}
Questions replied: {{ user.count }}
\n\n{% endif %}\n\n{% endfor %}\n\n
\n\n### FastAPI Experts - All Time\n\nHere are the all time **FastAPI Experts**. 🤓🤯\n\nThese are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github) through *all time*. 🧙\n\n
\n\n{% for user in people.experts[:50] %}\n\n{% if user.login not in skip_users %}\n\n
@{{ user.login }}
Questions replied: {{ user.count }}
\n\n{% endif %}\n\n{% endfor %}\n\n
", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "FastAPI Experts", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L70-L183", "start_line": 70, "end_line": 183} {"id": "docs/en/docs/fastapi-people.md::Top Contributors::L184", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: Top Contributors\n## Top Contributors\n\nHere are the **Top Contributors**. 👷\n\nThese users have created the most Pull Requests that have been *merged*.\n\nThey have contributed source code, documentation, etc. 📦\n\n
\n\n{% for user in (contributors.values() | list)[:50] %}\n\n{% if user.login not in skip_users %}\n\n
@{{ user.login }}
Pull Requests: {{ user.count }}
\n\n{% endif %}\n\n{% endfor %}\n\n
\n\nThere are hundreds of other contributors, you can see them all in the [FastAPI GitHub Contributors page](https://github.com/fastapi/fastapi/graphs/contributors). 👷", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "Top Contributors", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L184-L207", "start_line": 184, "end_line": 207} {"id": "docs/en/docs/fastapi-people.md::Top Translation Reviewers::L208", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: Top Translation Reviewers\n## Top Translation Reviewers\n\nThese users are the **Top Translation Reviewers**. 🕵️\n\nTranslation reviewers have the **power to approve translations** of the documentation. Without them, there wouldn't be documentation in several other languages.\n\n
\n{% for user in (translation_reviewers.values() | list)[:50] %}\n\n{% if user.login not in skip_users %}\n\n
@{{ user.login }}
Reviews: {{ user.count }}
\n\n{% endif %}\n\n{% endfor %}\n\n
", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "Top Translation Reviewers", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L208-L226", "start_line": 208, "end_line": 226} {"id": "docs/en/docs/fastapi-people.md::Sponsors::L227", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: Sponsors\n## Sponsors\n\nThese are the **Sponsors**. 😎\n\nThey are supporting my work with **FastAPI** (and others), mainly through [GitHub Sponsors](https://github.com/sponsors/tiangolo).\n\n{% if sponsors %}\n\n{% if sponsors.gold %}\n\n### Gold Sponsors\n\n{% for sponsor in sponsors.gold -%}\n\n{% endfor %}\n{% endif %}\n\n{% if sponsors.silver %}\n\n### Silver Sponsors\n\n{% for sponsor in sponsors.silver -%}\n\n{% endfor %}\n{% endif %}\n\n{% if sponsors.bronze %}\n\n### Bronze Sponsors\n\n{% for sponsor in sponsors.bronze -%}\n\n{% endfor %}\n{% endif %}\n\n{% endif %}\n\n### Individual Sponsors\n\n{% if github_sponsors %}\n{% for group in github_sponsors.sponsors %}\n\n
\n\n{% for user in group %}\n{% if user.login not in sponsors_badge.logins %}\n\n
@{{ user.login }}
\n\n{% endif %}\n{% endfor %}\n\n
\n\n{% endfor %}\n{% endif %}", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "Sponsors", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L227-L283", "start_line": 227, "end_line": 283} {"id": "docs/en/docs/fastapi-people.md::About the data - technical details::L284", "text": "# Doc: docs/en/docs/fastapi-people.md | Page: FastAPI People | Section: About the data - technical details\n## About the data - technical details\n\nThe main intention of this page is to highlight the effort of the community to help others.\n\nEspecially including efforts that are normally less visible, and in many cases more arduous, like helping others with questions and reviewing Pull Requests with translations.\n\nThe data is calculated each month, you can read the [source code here](https://github.com/fastapi/fastapi/blob/master/scripts/).\n\nHere I'm also highlighting contributions from sponsors.\n\nI also reserve the right to update the algorithm, sections, thresholds, etc (just in case 🤷).", "source_type": "doc", "path": "docs/en/docs/fastapi-people.md", "symbol": "About the data - technical details", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#L284-L294", "start_line": 284, "end_line": 294} {"id": "docs/en/docs/features.md::FastAPI features { #fastapi-features }::L3", "text": "# Doc: docs/en/docs/features.md | Page: Features { #features } | Section: FastAPI features { #fastapi-features }\n## FastAPI features { #fastapi-features }\n\n**FastAPI** gives you the following:\n\n### Based on open standards { #based-on-open-standards }\n\n* [**OpenAPI**](https://github.com/OAI/OpenAPI-Specification) for API creation, including declarations of path operations, parameters, request bodies, security, etc.\n* Automatic data model documentation with [**JSON Schema**](https://json-schema.org/) (as OpenAPI itself is based on JSON Schema).\n* Designed around these standards, after a meticulous study. Instead of an afterthought layer on top.\n* This also allows using automatic **client code generation** in many languages.\n\n### Automatic docs { #automatic-docs }\n\nInteractive API documentation and exploration web user interfaces. As the framework is based on OpenAPI, there are multiple options, 2 included by default.\n\n* [**Swagger UI**](https://github.com/swagger-api/swagger-ui), with interactive exploration, call and test your API directly from the browser.\n\n![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)\n\n* Alternative API documentation with [**ReDoc**](https://github.com/Rebilly/ReDoc).\n\n![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)\n\n### Just Modern Python { #just-modern-python }\n\nIt's all based on standard **Python type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python.\n\nIf you need a 2 minute refresher of how to use Python types (even if you don't use FastAPI), check the short tutorial: [Python Types](python-types.md).\n\nYou write standard Python with types:\n\n```Python\nfrom datetime import date\n\nfrom pydantic import BaseModel\n\n# Declare a variable as a str\n# and get editor support inside the function\ndef main(user_id: str):\n return user_id\n\n\n# A Pydantic model\nclass User(BaseModel):\n id: int\n name: str\n joined: date\n```\n\nThat can then be used like:\n\n```Python\nmy_user: User = User(id=3, name=\"John Doe\", joined=\"2018-07-19\")\n\nsecond_user_data = {\n \"id\": 4,\n \"name\": \"Mary\",\n \"joined\": \"2018-11-30\",\n}\n\nmy_second_user: User = User(**second_user_data)\n```\n\n/// note\n\n`**second_user_data` means:\n\nPass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name=\"Mary\", joined=\"2018-11-30\")`\n\n///\n\n### Editor support { #editor-support }\n\nThe whole framework was designed to be easy and intuitive to use, all the decisions were tested on multiple editors even before starting development, to ensure the best development experience.\n\nIn the Python developer surveys, it's clear [that one of the most used features is \"autocompletion\"](https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features).\n\nThe whole **FastAPI** framework is designed to satisfy that. Autocompletion works everywhere.\n\nYou will rarely need to come back to the docs.\n\nHere's how your editor might help you:\n\n* in [Visual Studio Code](https://code.visualstudio.com/):\n\n![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)\n\n* in [PyCharm](https://www.jetbrains.com/pycharm/):\n\n![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png)\n\nYou will get completion in code you might even consider impossible before. As for example, the `price` key inside a JSON body (that could have been nested) that comes from a request.\n\nNo more typing the wrong key names, coming back and forth between docs, or scrolling up and down to find if you finally used `username` or `user_name`.\n\n### Short { #short }\n\nIt has sensible **defaults** for everything, with optional configurations everywhere. All the parameters can be fine-tuned to do what you need and to define the API you need.\n\nBut by default, it all **\"just works\"**.\n\n### Validation { #validation }\n\n* Validation for most (or all?) Python **data types**, including:\n * JSON objects (`dict`).\n * JSON array (`list`) defining item types.\n * String (`str`) fields, defining min and max lengths.\n * Numbers (`int`, `float`) with min and max values, etc.\n\n* Validation for more exotic types, like:\n * URL.\n * Email.\n * UUID.\n * ...and others.\n\nAll the validation is handled by the well-established and robust **Pydantic**.\n\n### Security and authentication { #security-and-authentication }\n\nSecurity and authentication integrated. Without any compromise with databases or data models.\n\nAll the security schemes defined in OpenAPI, including:\n\n* HTTP Basic.\n* **OAuth2** (also with **JWT tokens**). Check the tutorial on [OAuth2 with JWT](tutorial/security/oauth2-jwt.md).\n* API keys in:\n * Headers.\n * Query parameters.\n * Cookies, etc.\n\nPlus all the security features from Starlette (including **session cookies**).\n\nAll built as reusable tools and components that are easy to integrate with your systems, data stores, relational and NoSQL databases, etc.\n\n### Dependency Injection { #dependency-injection }\n\nFastAPI includes an extremely easy to use, but extremely powerful Dependency Injection system.\n\n* Even dependencies can have dependencies, creating a hierarchy or **\"graph\" of dependencies**.\n* All **automatically handled** by the framework.\n* All the dependencies can require data from requests and **augment the path operation** constraints and automatic documentation.\n* **Automatic validation** even for *path operation* parameters defined in dependencies.\n* Support for complex user authentication systems, **database connections**, etc.\n* **No compromise** with databases, frontends, etc. But easy integration with all of them.\n\n### Unlimited \"plug-ins\" { #unlimited-plug-ins }\n\nOr, in other words, no need for them, import and use the code you need.\n\nAny integration is designed to be so simple to use (with dependencies) that you can create a \"plug-in\" for your application in 2 lines of code using the same structure and syntax used for your *path operations*.\n\n### Tested { #tested }\n\n* 100% test coverage.\n* 100% type annotated code base.\n* Used in production applications.", "source_type": "doc", "path": "docs/en/docs/features.md", "symbol": "FastAPI features { #fastapi-features }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/features.md#L3-L159", "start_line": 3, "end_line": 159} {"id": "docs/en/docs/features.md::Starlette features { #starlette-features }::L160", "text": "# Doc: docs/en/docs/features.md | Page: Features { #features } | Section: Starlette features { #starlette-features }\n## Starlette features { #starlette-features }\n\n**FastAPI** is fully compatible with (and based on) [**Starlette**](https://www.starlette.dev/). So, any additional Starlette code you have, will also work.\n\n`FastAPI` is actually a sub-class of `Starlette`. So, if you already know or use Starlette, most of the functionality will work the same way.\n\nWith **FastAPI** you get all of **Starlette**'s features (as FastAPI is just Starlette on steroids):\n\n* Seriously impressive performance. It is [one of the fastest Python frameworks available, on par with **NodeJS** and **Go**](https://github.com/encode/starlette#performance).\n* **WebSocket** support.\n* In-process background tasks.\n* Startup and shutdown events.\n* Test client built on HTTPX.\n* **CORS**, GZip, Static Files, Streaming responses.\n* **Session and Cookie** support.\n* 100% test coverage.\n* 100% type annotated codebase.", "source_type": "doc", "path": "docs/en/docs/features.md", "symbol": "Starlette features { #starlette-features }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/features.md#L160-L177", "start_line": 160, "end_line": 177} {"id": "docs/en/docs/features.md::Pydantic features { #pydantic-features }::L178", "text": "# Doc: docs/en/docs/features.md | Page: Features { #features } | Section: Pydantic features { #pydantic-features }\n## Pydantic features { #pydantic-features }\n\n**FastAPI** is fully compatible with (and based on) [**Pydantic**](https://docs.pydantic.dev/). So, any additional Pydantic code you have, will also work.\n\nIncluding external libraries also based on Pydantic, such as ORMs and ODMs for databases.\n\nThis also means that in many cases you can pass the same object you get from a request **directly to the database**, as everything is validated automatically.\n\nThe same applies the other way around, in many cases you can just pass the object you get from the database **directly to the client**.\n\nWith **FastAPI** you get all of **Pydantic**'s features (as FastAPI is based on Pydantic for all the data handling):\n\n* **No brainfuck**:\n * No new schema definition micro-language to learn.\n * If you know Python types you know how to use Pydantic.\n* Plays nicely with your **IDE/linter/brain**:\n * Because pydantic data structures are just instances of classes you define; auto-completion, linting, mypy and your intuition should all work properly with your validated data.\n* Validate **complex structures**:\n * Use of hierarchical Pydantic models, Python `typing`’s `List` and `Dict`, etc.\n * And validators allow complex data schemas to be clearly and easily defined, checked and documented as JSON Schema.\n * You can have deeply **nested JSON** objects and have them all validated and annotated.\n* **Extensible**:\n * Pydantic allows custom data types to be defined or you can extend validation with methods on a model decorated with the validator decorator.\n* 100% test coverage.", "source_type": "doc", "path": "docs/en/docs/features.md", "symbol": "Pydantic features { #pydantic-features }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/features.md#L178-L201", "start_line": 178, "end_line": 201} {"id": "docs/en/docs/help-fastapi.md::Help { #help }::L1", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Help { #help }\n# Help { #help }\n\nWould you like to help FastAPI or get help about FastAPI?\n\nThere are very simple ways to help and get help.", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Help { #help }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/help-fastapi.md::Subscribe to the newsletter { #subscribe-to-the-newsletter }::L7", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Subscribe to the newsletter { #subscribe-to-the-newsletter }\n## Subscribe to the newsletter { #subscribe-to-the-newsletter }\n\nYou can subscribe to the (infrequent) [**FastAPI and friends** newsletter](newsletter.md) to stay updated about:\n\n* News about FastAPI and friends 🚀\n* Guides 📝\n* Features ✨\n* Breaking changes 🚨\n* Tips and tricks ✅", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Subscribe to the newsletter { #subscribe-to-the-newsletter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L7-L16", "start_line": 7, "end_line": 16} {"id": "docs/en/docs/help-fastapi.md::Follow FastAPI online { #follow-fastapi-online }::L17", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Follow FastAPI online { #follow-fastapi-online }\n## Follow FastAPI online { #follow-fastapi-online }\n\nYou can follow **FastAPI** online in several places:\n\n* [@fastapi on **X / Twitter**](https://x.com/fastapi)\n* [@fastapi.tiangolo.com on **Bluesky**](https://bsky.app/profile/fastapi.tiangolo.com)\n* [FastAPI on **LinkedIn**](https://www.linkedin.com/company/fastapi/)", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Follow FastAPI online { #follow-fastapi-online }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L17-L24", "start_line": 17, "end_line": 24} {"id": "docs/en/docs/help-fastapi.md::Star **FastAPI** in GitHub { #star-fastapi-in-github }::L25", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Star **FastAPI** in GitHub { #star-fastapi-in-github }\n## Star **FastAPI** in GitHub { #star-fastapi-in-github }\n\nYou can \"star\" FastAPI in GitHub (clicking the star button at the top right): [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi). ⭐️\n\nBy adding a star, other users will be able to find it more easily and see that it has already been useful for others.", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Star **FastAPI** in GitHub { #star-fastapi-in-github }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L25-L30", "start_line": 25, "end_line": 30} {"id": "docs/en/docs/help-fastapi.md::Watch the GitHub repository for releases { #watch-the-github-repository-for-releases }::L31", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Watch the GitHub repository for releases { #watch-the-github-repository-for-releases }\n## Watch the GitHub repository for releases { #watch-the-github-repository-for-releases }\n\nYou can \"watch\" FastAPI in GitHub (clicking the \"watch\" button at the top right): [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi). 👀\n\nThere you can select \"Releases only\".\n\nBy doing it, you will receive notifications (in your email) whenever there's a new release (a new version) of **FastAPI** with bug fixes and new features.", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Watch the GitHub repository for releases { #watch-the-github-repository-for-releases }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L31-L38", "start_line": 31, "end_line": 38} {"id": "docs/en/docs/help-fastapi.md::Follow the author { #follow-the-author }::L39", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Follow the author { #follow-the-author }\n## Follow the author { #follow-the-author }\n\nYou can follow [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com), the author in a few places, to hear when I have news to share about FastAPI and friends:\n\n* [@tiangolo on **GitHub**](https://github.com/tiangolo).\n* [@tiangolo on **X (Twitter)**](https://x.com/tiangolo)\n* [@tiangolo.com on **Bluesky**](https://bsky.app/profile/tiangolo.com)\n* [@tiangolo on **LinkedIn**](https://www.linkedin.com/in/tiangolo/).", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Follow the author { #follow-the-author }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L39-L47", "start_line": 39, "end_line": 47} {"id": "docs/en/docs/help-fastapi.md::Help others with questions in GitHub { #help-others-with-questions-in-github }::L48", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Help others with questions in GitHub { #help-others-with-questions-in-github }\n## Help others with questions in GitHub { #help-others-with-questions-in-github }\n\nYou can try and help others with their questions in [GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered).\n\nIn many cases you might already know the answer for those questions. 🤓\n\nIf you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#fastapi-experts). 🎉\n\nJust remember, the most important point is: try to be kind. 🤗\n\n### How to Help { #how-to-help }\n\nFollow the [guide on how to help](https://tiangolo.com/open-source/help/#help-others-with-questions-in-github) here.", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Help others with questions in GitHub { #help-others-with-questions-in-github }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L48-L61", "start_line": 48, "end_line": 61} {"id": "docs/en/docs/help-fastapi.md::Ask Questions { #ask-questions }::L62", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Ask Questions { #ask-questions }\n## Ask Questions { #ask-questions }\n\nYou can [create a new question](https://github.com/fastapi/fastapi/discussions/new?category=questions) in the GitHub repository, for example to:\n\n* Ask a **question** or ask about a **problem**.\n* Suggest a new **feature**.", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Ask Questions { #ask-questions }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L62-L68", "start_line": 62, "end_line": 68} {"id": "docs/en/docs/help-fastapi.md::Join the Chat { #join-the-chat }::L69", "text": "# Doc: docs/en/docs/help-fastapi.md | Page: Help { #help } | Section: Join the Chat { #join-the-chat }\n## Join the Chat { #join-the-chat }\n\nJoin the 👥 [Discord chat server](https://discord.gg/VQjSZaeJmf) 👥 and hang out with others in the FastAPI community.\n\n/// tip\n\nFor questions, ask them in GitHub Discussions, there's a much better chance you will receive help.\n\nUse the chat only for other general conversations.\n\n///\n\n### Don't use the Chat for Questions { #dont-use-the-chat-for-questions }\n\nKeep in mind that as chats allow more \"free conversation\", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers.\n\nIn GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking.\n\nConversations in the chat systems are also not as easily searchable as in GitHub, they get lost.", "source_type": "doc", "path": "docs/en/docs/help-fastapi.md", "symbol": "Join the Chat { #join-the-chat }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/help-fastapi.md#L69-L87", "start_line": 69, "end_line": 87} {"id": "docs/en/docs/history-design-future.md::History, Design and Future { #history-design-and-future }::L1", "text": "# Doc: docs/en/docs/history-design-future.md | Page: History, Design and Future { #history-design-and-future } | Section: History, Design and Future { #history-design-and-future }\n# History, Design and Future { #history-design-and-future }\n\nSome time ago, [a **FastAPI** user asked](https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920):\n\n> What’s the history of this project? It seems to have come from nowhere to awesome in a few weeks [...]\n\nHere's a little bit of that history.", "source_type": "doc", "path": "docs/en/docs/history-design-future.md", "symbol": "History, Design and Future { #history-design-and-future }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/history-design-future.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/history-design-future.md::Alternatives { #alternatives }::L9", "text": "# Doc: docs/en/docs/history-design-future.md | Page: History, Design and Future { #history-design-and-future } | Section: Alternatives { #alternatives }\n## Alternatives { #alternatives }\n\nI have been creating APIs with complex requirements for several years (Machine Learning, distributed systems, asynchronous jobs, NoSQL databases, etc), leading several teams of developers.\n\nAs part of that, I needed to investigate, test and use many alternatives.\n\nThe history of **FastAPI** is in great part the history of its predecessors.\n\nAs said in the section [Alternatives](alternatives.md):\n\n
\n\n**FastAPI** wouldn't exist if not for the previous work of others.\n\nThere have been many tools created before that have helped inspire its creation.\n\nI have been avoiding the creation of a new framework for several years. First I tried to solve all the features covered by **FastAPI** using many different frameworks, plug-ins, and tools.\n\nBut at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).\n\n
", "source_type": "doc", "path": "docs/en/docs/history-design-future.md", "symbol": "Alternatives { #alternatives }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/history-design-future.md#L9-L30", "start_line": 9, "end_line": 30} {"id": "docs/en/docs/history-design-future.md::Investigation { #investigation }::L31", "text": "# Doc: docs/en/docs/history-design-future.md | Page: History, Design and Future { #history-design-and-future } | Section: Investigation { #investigation }\n## Investigation { #investigation }\n\nBy using all the previous alternatives I had the chance to learn from all of them, take ideas, and combine them in the best way I could find for myself and the teams of developers I have worked with.\n\nFor example, it was clear that ideally it should be based on standard Python type hints.\n\nAlso, the best approach was to use already existing standards.\n\nSo, before even starting to code **FastAPI**, I spent several months studying the specs for OpenAPI, JSON Schema, OAuth2, etc. Understanding their relationship, overlap, and differences.", "source_type": "doc", "path": "docs/en/docs/history-design-future.md", "symbol": "Investigation { #investigation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/history-design-future.md#L31-L40", "start_line": 31, "end_line": 40} {"id": "docs/en/docs/history-design-future.md::Design { #design }::L41", "text": "# Doc: docs/en/docs/history-design-future.md | Page: History, Design and Future { #history-design-and-future } | Section: Design { #design }\n## Design { #design }\n\nThen I spent some time designing the developer \"API\" I wanted to have as a user (as a developer using FastAPI).\n\nI tested several ideas in the most popular Python editors: PyCharm, VS Code, Jedi based editors.\n\nBy the last [Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools), that covers about 80% of the users.\n\nIt means that **FastAPI** was specifically tested with the editors used by 80% of the Python developers. And as most of the other editors tend to work similarly, all its benefits should work for virtually all editors.\n\nThat way I could find the best ways to reduce code duplication as much as possible, to have completion everywhere, type and error checks, etc.\n\nAll in a way that provided the best development experience for all the developers.", "source_type": "doc", "path": "docs/en/docs/history-design-future.md", "symbol": "Design { #design }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/history-design-future.md#L41-L54", "start_line": 41, "end_line": 54} {"id": "docs/en/docs/history-design-future.md::Requirements { #requirements }::L55", "text": "# Doc: docs/en/docs/history-design-future.md | Page: History, Design and Future { #history-design-and-future } | Section: Requirements { #requirements }\n## Requirements { #requirements }\n\nAfter testing several alternatives, I decided that I was going to use [**Pydantic**](https://docs.pydantic.dev/) for its advantages.\n\nThen I contributed to it, to make it fully compliant with JSON Schema, to support different ways to define constraint declarations, and to improve editor support (type checks, autocompletion) based on the tests in several editors.\n\nDuring the development, I also contributed to [**Starlette**](https://www.starlette.dev/), the other key requirement.", "source_type": "doc", "path": "docs/en/docs/history-design-future.md", "symbol": "Requirements { #requirements }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/history-design-future.md#L55-L62", "start_line": 55, "end_line": 62} {"id": "docs/en/docs/history-design-future.md::Development { #development }::L63", "text": "# Doc: docs/en/docs/history-design-future.md | Page: History, Design and Future { #history-design-and-future } | Section: Development { #development }\n## Development { #development }\n\nBy the time I started creating **FastAPI** itself, most of the pieces were already in place, the design was defined, the requirements and tools were ready, and the knowledge about the standards and specifications was clear and fresh.", "source_type": "doc", "path": "docs/en/docs/history-design-future.md", "symbol": "Development { #development }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/history-design-future.md#L63-L66", "start_line": 63, "end_line": 66} {"id": "docs/en/docs/history-design-future.md::Future { #future }::L67", "text": "# Doc: docs/en/docs/history-design-future.md | Page: History, Design and Future { #history-design-and-future } | Section: Future { #future }\n## Future { #future }\n\nBy this point, it's already clear that **FastAPI** with its ideas is being useful for many people.\n\nIt is being chosen over previous alternatives for suiting many use cases better.\n\nMany developers and teams already depend on **FastAPI** for their projects (including me and my team).\n\nBut still, there are many improvements and features to come.\n\n**FastAPI** has a great future ahead.\n\nAnd [your help](help-fastapi.md) is greatly appreciated.", "source_type": "doc", "path": "docs/en/docs/history-design-future.md", "symbol": "Future { #future }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/history-design-future.md#L67-L79", "start_line": 67, "end_line": 79} {"id": "docs/en/docs/how-to/authentication-error-status-code.md::Use Old 403 Authentication Error Status Codes { #use-old-403-authentication-error-status-codes }::L1", "text": "# Doc: docs/en/docs/how-to/authentication-error-status-code.md | Page: Use Old 403 Authentication Error Status Codes { #use-old-403-authentication-error-status-codes } | Section: Use Old 403 Authentication Error Status Codes { #use-old-403-authentication-error-status-codes }\n# Use Old 403 Authentication Error Status Codes { #use-old-403-authentication-error-status-codes }\n\nBefore FastAPI version `0.122.0`, when the integrated security utilities returned an error to the client after a failed authentication, they used the HTTP status code `403 Forbidden`.\n\nStarting with FastAPI version `0.122.0`, they use the more appropriate HTTP status code `401 Unauthorized`, and return a sensible `WWW-Authenticate` header in the response, following the HTTP specifications, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized).\n\nBut if for some reason your clients depend on the old behavior, you can revert to it by overriding the method `make_not_authenticated_error` in your security classes.\n\nFor example, you can create a subclass of `HTTPBearer` that returns a `403 Forbidden` error instead of the default `401 Unauthorized` error:\n\n{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *}\n\n/// tip\n\nNotice that the function returns the exception instance, it doesn't raise it. The raising is done in the rest of the internal code.\n\n///", "source_type": "doc", "path": "docs/en/docs/how-to/authentication-error-status-code.md", "symbol": "Use Old 403 Authentication Error Status Codes { #use-old-403-authentication-error-status-codes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/authentication-error-status-code.md#L1-L17", "start_line": 1, "end_line": 17} {"id": "docs/en/docs/how-to/conditional-openapi.md::Conditional OpenAPI { #conditional-openapi }::L1", "text": "# Doc: docs/en/docs/how-to/conditional-openapi.md | Page: Conditional OpenAPI { #conditional-openapi } | Section: Conditional OpenAPI { #conditional-openapi }\n# Conditional OpenAPI { #conditional-openapi }\n\nIf you needed to, you could use settings and environment variables to configure OpenAPI conditionally depending on the environment, and even disable it entirely.", "source_type": "doc", "path": "docs/en/docs/how-to/conditional-openapi.md", "symbol": "Conditional OpenAPI { #conditional-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/conditional-openapi.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/how-to/conditional-openapi.md::About security, APIs, and docs { #about-security-apis-and-docs }::L5", "text": "# Doc: docs/en/docs/how-to/conditional-openapi.md | Page: Conditional OpenAPI { #conditional-openapi } | Section: About security, APIs, and docs { #about-security-apis-and-docs }\n## About security, APIs, and docs { #about-security-apis-and-docs }\n\nHiding your documentation user interfaces in production *shouldn't* be the way to protect your API.\n\nThat doesn't add any extra security to your API, the *path operations* will still be available where they are.\n\nIf there's a security flaw in your code, it will still exist.\n\nHiding the documentation just makes it more difficult to understand how to interact with your API, and could make it more difficult for you to debug it in production. It could be considered simply a form of [Security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity).\n\nIf you want to secure your API, there are several better things you can do, for example:\n\n* Make sure you have well defined Pydantic models for your request bodies and responses.\n* Configure any required permissions and roles using dependencies.\n* Never store plaintext passwords, only password hashes.\n* Implement and use well-known cryptographic tools, like pwdlib and JWT tokens, etc.\n* Add more granular permission controls with OAuth2 scopes where needed.\n* ...etc.\n\nNevertheless, you might have a very specific use case where you really need to disable the API docs for some environment (e.g. for production) or depending on configurations from environment variables.", "source_type": "doc", "path": "docs/en/docs/how-to/conditional-openapi.md", "symbol": "About security, APIs, and docs { #about-security-apis-and-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/conditional-openapi.md#L5-L25", "start_line": 5, "end_line": 25} {"id": "docs/en/docs/how-to/conditional-openapi.md::Conditional OpenAPI from settings and env vars { #conditional-openapi-from-settings-and-env-vars }::L26", "text": "# Doc: docs/en/docs/how-to/conditional-openapi.md | Page: Conditional OpenAPI { #conditional-openapi } | Section: Conditional OpenAPI from settings and env vars { #conditional-openapi-from-settings-and-env-vars }\n## Conditional OpenAPI from settings and env vars { #conditional-openapi-from-settings-and-env-vars }\n\nYou can easily use the same Pydantic settings to configure your generated OpenAPI and the docs UIs.\n\nFor example:\n\n{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *}\n\nHere we declare the setting `openapi_url` with the same default of `\"/openapi.json\"`.\n\nAnd then we use it when creating the `FastAPI` app.\n\nThen you could disable OpenAPI (including the UI docs) by setting the environment variable `OPENAPI_URL` to the empty string, like:\n\n
\n\n```console\n$ OPENAPI_URL= uvicorn main:app\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nThen if you go to the URLs at `/openapi.json`, `/docs`, or `/redoc` you will just get a `404 Not Found` error like:\n\n```JSON\n{\n \"detail\": \"Not Found\"\n}\n```", "source_type": "doc", "path": "docs/en/docs/how-to/conditional-openapi.md", "symbol": "Conditional OpenAPI from settings and env vars { #conditional-openapi-from-settings-and-env-vars }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/conditional-openapi.md#L26-L56", "start_line": 26, "end_line": 56} {"id": "docs/en/docs/how-to/configure-swagger-ui.md::Configure Swagger UI { #configure-swagger-ui }::L1", "text": "# Doc: docs/en/docs/how-to/configure-swagger-ui.md | Page: Configure Swagger UI { #configure-swagger-ui } | Section: Configure Swagger UI { #configure-swagger-ui }\n# Configure Swagger UI { #configure-swagger-ui }\n\nYou can configure some extra [Swagger UI parameters](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).\n\nTo configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function.\n\n`swagger_ui_parameters` receives a dictionary with the configurations passed to Swagger UI directly.\n\nFastAPI converts the configurations to **JSON** to make them compatible with JavaScript, as that's what Swagger UI needs.", "source_type": "doc", "path": "docs/en/docs/how-to/configure-swagger-ui.md", "symbol": "Configure Swagger UI { #configure-swagger-ui }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/configure-swagger-ui.md#L1-L10", "start_line": 1, "end_line": 10} {"id": "docs/en/docs/how-to/configure-swagger-ui.md::Disable Syntax Highlighting { #disable-syntax-highlighting }::L11", "text": "# Doc: docs/en/docs/how-to/configure-swagger-ui.md | Page: Configure Swagger UI { #configure-swagger-ui } | Section: Disable Syntax Highlighting { #disable-syntax-highlighting }\n## Disable Syntax Highlighting { #disable-syntax-highlighting }\n\nFor example, you could disable syntax highlighting in Swagger UI.\n\nWithout changing the settings, syntax highlighting is enabled by default:\n\n\n\nBut you can disable it by setting `syntaxHighlight` to `False`:\n\n{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}\n\n...and then Swagger UI won't show the syntax highlighting anymore:\n\n", "source_type": "doc", "path": "docs/en/docs/how-to/configure-swagger-ui.md", "symbol": "Disable Syntax Highlighting { #disable-syntax-highlighting }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/configure-swagger-ui.md#L11-L26", "start_line": 11, "end_line": 26} {"id": "docs/en/docs/how-to/configure-swagger-ui.md::Change the Theme { #change-the-theme }::L27", "text": "# Doc: docs/en/docs/how-to/configure-swagger-ui.md | Page: Configure Swagger UI { #configure-swagger-ui } | Section: Change the Theme { #change-the-theme }\n## Change the Theme { #change-the-theme }\n\nThe same way you could set the syntax highlighting theme with the key `\"syntaxHighlight.theme\"` (notice that it has a dot in the middle):\n\n{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}\n\nThat configuration would change the syntax highlighting color theme:\n\n", "source_type": "doc", "path": "docs/en/docs/how-to/configure-swagger-ui.md", "symbol": "Change the Theme { #change-the-theme }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/configure-swagger-ui.md#L27-L36", "start_line": 27, "end_line": 36} {"id": "docs/en/docs/how-to/configure-swagger-ui.md::Change Default Swagger UI Parameters { #change-default-swagger-ui-parameters }::L37", "text": "# Doc: docs/en/docs/how-to/configure-swagger-ui.md | Page: Configure Swagger UI { #configure-swagger-ui } | Section: Change Default Swagger UI Parameters { #change-default-swagger-ui-parameters }\n## Change Default Swagger UI Parameters { #change-default-swagger-ui-parameters }\n\nFastAPI includes some default configuration parameters appropriate for most of the use cases.\n\nIt includes these default configurations:\n\n{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}\n\nYou can override any of them by setting a different value in the argument `swagger_ui_parameters`.\n\nFor example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`:\n\n{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}", "source_type": "doc", "path": "docs/en/docs/how-to/configure-swagger-ui.md", "symbol": "Change Default Swagger UI Parameters { #change-default-swagger-ui-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/configure-swagger-ui.md#L37-L50", "start_line": 37, "end_line": 50} {"id": "docs/en/docs/how-to/configure-swagger-ui.md::Other Swagger UI Parameters { #other-swagger-ui-parameters }::L51", "text": "# Doc: docs/en/docs/how-to/configure-swagger-ui.md | Page: Configure Swagger UI { #configure-swagger-ui } | Section: Other Swagger UI Parameters { #other-swagger-ui-parameters }\n## Other Swagger UI Parameters { #other-swagger-ui-parameters }\n\nTo see all the other possible configurations you can use, read the official [docs for Swagger UI parameters](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).", "source_type": "doc", "path": "docs/en/docs/how-to/configure-swagger-ui.md", "symbol": "Other Swagger UI Parameters { #other-swagger-ui-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/configure-swagger-ui.md#L51-L54", "start_line": 51, "end_line": 54} {"id": "docs/en/docs/how-to/configure-swagger-ui.md::JavaScript-only settings { #javascript-only-settings }::L55", "text": "# Doc: docs/en/docs/how-to/configure-swagger-ui.md | Page: Configure Swagger UI { #configure-swagger-ui } | Section: JavaScript-only settings { #javascript-only-settings }\n## JavaScript-only settings { #javascript-only-settings }\n\nSwagger UI also allows other configurations to be **JavaScript-only** objects (for example, JavaScript functions).\n\nFastAPI also includes these JavaScript-only `presets` settings:\n\n```JavaScript\npresets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n]\n```\n\nThese are **JavaScript** objects, not strings, so you can't pass them from Python code directly.\n\nIf you need to use JavaScript-only configurations like those, you can use one of the methods above. Override the whole Swagger UI *path operation* and manually write any JavaScript you need.", "source_type": "doc", "path": "docs/en/docs/how-to/configure-swagger-ui.md", "symbol": "JavaScript-only settings { #javascript-only-settings }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/configure-swagger-ui.md#L55-L70", "start_line": 55, "end_line": 70} {"id": "docs/en/docs/how-to/custom-docs-ui-assets.md::Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting }::L1", "text": "# Doc: docs/en/docs/how-to/custom-docs-ui-assets.md | Page: Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting } | Section: Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting }\n# Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting }\n\nThe API docs use **Swagger UI** and **ReDoc**, and each of those need some JavaScript and CSS files.\n\nBy default, those files are served from a CDN.\n\nBut it's possible to customize it, you can set a specific CDN, or serve the files yourself.", "source_type": "doc", "path": "docs/en/docs/how-to/custom-docs-ui-assets.md", "symbol": "Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-docs-ui-assets.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/how-to/custom-docs-ui-assets.md::Custom CDN for JavaScript and CSS { #custom-cdn-for-javascript-and-css }::L9", "text": "# Doc: docs/en/docs/how-to/custom-docs-ui-assets.md | Page: Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting } | Section: Custom CDN for JavaScript and CSS { #custom-cdn-for-javascript-and-css }\n## Custom CDN for JavaScript and CSS { #custom-cdn-for-javascript-and-css }\n\nLet's say that you want to use a different CDN, for example you want to use `https://unpkg.com/`.\n\nThis could be useful if for example you live in a country that restricts some URLs.\n\n### Disable the automatic docs { #disable-the-automatic-docs }\n\nThe first step is to disable the automatic docs, as by default, those use the default CDN.\n\nTo disable them, set their URLs to `None` when creating your `FastAPI` app:\n\n{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}\n\n### Include the custom docs { #include-the-custom-docs }\n\nNow you can create the *path operations* for the custom docs.\n\nYou can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:\n\n* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`.\n* `title`: the title of your API.\n* `oauth2_redirect_url`: you can use `app.swagger_ui_oauth2_redirect_url` here to use the default.\n* `swagger_js_url`: the URL where the HTML for your Swagger UI docs can get the **JavaScript** file. This is the custom CDN URL.\n* `swagger_css_url`: the URL where the HTML for your Swagger UI docs can get the **CSS** file. This is the custom CDN URL.\n\nAnd similarly for ReDoc...\n\n{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}\n\n/// tip\n\nThe *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.\n\nIf you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.\n\nSwagger UI will handle it behind the scenes for you, but it needs this \"redirect\" helper.\n\n///\n\n### Create a *path operation* to test it { #create-a-path-operation-to-test-it }\n\nNow, to be able to test that everything works, create a *path operation*:\n\n{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}\n\n### Test it { #test-it }\n\nNow, you should be able to go to your docs at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), and reload the page, it will load those assets from the new CDN.", "source_type": "doc", "path": "docs/en/docs/how-to/custom-docs-ui-assets.md", "symbol": "Custom CDN for JavaScript and CSS { #custom-cdn-for-javascript-and-css }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-docs-ui-assets.md#L9-L58", "start_line": 9, "end_line": 58} {"id": "docs/en/docs/how-to/custom-docs-ui-assets.md::Self-hosting JavaScript and CSS for docs { #self-hosting-javascript-and-css-for-docs }::L59", "text": "# Doc: docs/en/docs/how-to/custom-docs-ui-assets.md | Page: Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting } | Section: Self-hosting JavaScript and CSS for docs { #self-hosting-javascript-and-css-for-docs }\n## Self-hosting JavaScript and CSS for docs { #self-hosting-javascript-and-css-for-docs }\n\nSelf-hosting the JavaScript and CSS could be useful if, for example, you need your app to keep working even while offline, without open Internet access, or in a local network.\n\nHere you'll see how to serve those files yourself, in the same FastAPI app, and configure the docs to use them.\n\n### Project file structure { #project-file-structure }\n\nLet's say your project file structure looks like this:\n\n```\n.\n├── app\n│ ├── __init__.py\n│ ├── main.py\n```\n\nNow create a directory to store those static files.\n\nYour new file structure could look like this:\n\n```\n.\n├── app\n│   ├── __init__.py\n│   ├── main.py\n└── static/\n```\n\n### Download the files { #download-the-files }\n\nDownload the static files needed for the docs and put them on that `static/` directory.\n\nYou can probably right-click each link and select an option similar to \"Save link as...\".\n\n**Swagger UI** uses the files:\n\n* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)\n* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)\n\nAnd **ReDoc** uses the file:\n\n* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)\n\nAfter that, your file structure could look like:\n\n```\n.\n├── app\n│   ├── __init__.py\n│   ├── main.py\n└── static\n ├── redoc.standalone.js\n ├── swagger-ui-bundle.js\n └── swagger-ui.css\n```\n\n### Serve the static files { #serve-the-static-files }\n\n* Import `StaticFiles`.\n* \"Mount\" a `StaticFiles()` instance in a specific path.\n\n{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}\n\n### Test the static files { #test-the-static-files }\n\nStart your application and go to [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).\n\nYou should see a very long JavaScript file for **ReDoc**.\n\nIt could start with something like:\n\n```JavaScript\n/*! For license information please see redoc.standalone.js.LICENSE.txt */\n!function(e,t){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=t(require(\"null\")):\n...\n```\n\nThat confirms that you are being able to serve static files from your app, and that you placed the static files for the docs in the correct place.\n\nNow we can configure the app to use those static files for the docs.\n\n### Disable the automatic docs for static files { #disable-the-automatic-docs-for-static-files }\n\nThe same as when using a custom CDN, the first step is to disable the automatic docs, as those use the CDN by default.\n\nTo disable them, set their URLs to `None` when creating your `FastAPI` app:\n\n{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}\n\n### Include the custom docs for static files { #include-the-custom-docs-for-static-files }\n\nAnd the same way as with a custom CDN, now you can create the *path operations* for the custom docs.\n\nAgain, you can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:\n\n* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`.\n* `title`: the title of your API.\n* `oauth2_redirect_url`: you can use `app.swagger_ui_oauth2_redirect_url` here to use the default.\n* `swagger_js_url`: the URL where the HTML for your Swagger UI docs can get the **JavaScript** file. **This is the one that your own app is now serving**.\n* `swagger_css_url`: the URL where the HTML for your Swagger UI docs can get the **CSS** file. **This is the one that your own app is now serving**.\n\nAnd similarly for ReDoc...\n\n{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}\n\n/// tip\n\nThe *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.\n\nIf you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.\n\nSwagger UI will handle it behind the scenes for you, but it needs this \"redirect\" helper.\n\n///\n\n### Create a *path operation* to test static files { #create-a-path-operation-to-test-static-files }\n\nNow, to be able to test that everything works, create a *path operation*:\n\n{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}\n\n### Test Static Files UI { #test-static-files-ui }\n\nNow, you should be able to disconnect your WiFi, go to your docs at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), and reload the page.\n\nAnd even without Internet, you would be able to see the docs for your API and interact with it.", "source_type": "doc", "path": "docs/en/docs/how-to/custom-docs-ui-assets.md", "symbol": "Self-hosting JavaScript and CSS for docs { #self-hosting-javascript-and-css-for-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-docs-ui-assets.md#L59-L185", "start_line": 59, "end_line": 185} {"id": "docs/en/docs/how-to/custom-request-and-route.md::Custom Request and APIRoute class { #custom-request-and-apiroute-class }::L1", "text": "# Doc: docs/en/docs/how-to/custom-request-and-route.md | Page: Custom Request and APIRoute class { #custom-request-and-apiroute-class } | Section: Custom Request and APIRoute class { #custom-request-and-apiroute-class }\n# Custom Request and APIRoute class { #custom-request-and-apiroute-class }\n\nIn some cases, you may want to override the logic used by the `Request` and `APIRoute` classes.\n\nIn particular, this may be a good alternative to logic in a middleware.\n\nFor example, if you want to read or manipulate the request body before it is processed by your application.\n\n/// danger\n\nThis is an \"advanced\" feature.\n\nIf you are just starting with **FastAPI** you might want to skip this section.\n\n///", "source_type": "doc", "path": "docs/en/docs/how-to/custom-request-and-route.md", "symbol": "Custom Request and APIRoute class { #custom-request-and-apiroute-class }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-request-and-route.md#L1-L16", "start_line": 1, "end_line": 16} {"id": "docs/en/docs/how-to/custom-request-and-route.md::Use cases { #use-cases }::L17", "text": "# Doc: docs/en/docs/how-to/custom-request-and-route.md | Page: Custom Request and APIRoute class { #custom-request-and-apiroute-class } | Section: Use cases { #use-cases }\n## Use cases { #use-cases }\n\nSome use cases include:\n\n* Converting non-JSON request bodies to JSON (e.g. [`msgpack`](https://msgpack.org/index.html)).\n* Decompressing gzip-compressed request bodies.\n* Automatically logging all request bodies.", "source_type": "doc", "path": "docs/en/docs/how-to/custom-request-and-route.md", "symbol": "Use cases { #use-cases }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-request-and-route.md#L17-L24", "start_line": 17, "end_line": 24} {"id": "docs/en/docs/how-to/custom-request-and-route.md::Handling custom request body encodings { #handling-custom-request-body-encodings }::L25", "text": "# Doc: docs/en/docs/how-to/custom-request-and-route.md | Page: Custom Request and APIRoute class { #custom-request-and-apiroute-class } | Section: Handling custom request body encodings { #handling-custom-request-body-encodings }\n## Handling custom request body encodings { #handling-custom-request-body-encodings }\n\nLet's see how to make use of a custom `Request` subclass to decompress gzip requests.\n\nAnd an `APIRoute` subclass to use that custom request class.\n\n### Create a custom `GzipRequest` class { #create-a-custom-gziprequest-class }\n\n/// tip\n\nThis is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware).\n\n///\n\nFirst, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header.\n\nIf there's no `gzip` in the header, it will not try to decompress the body.\n\nThat way, the same route class can handle gzip compressed or uncompressed requests.\n\n{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}\n\n### Create a custom `GzipRoute` class { #create-a-custom-gziproute-class }\n\nNext, we create a custom subclass of `fastapi.routing.APIRoute` that will make use of the `GzipRequest`.\n\nThis time, it will overwrite the method `APIRoute.get_route_handler()`.\n\nThis method returns a function. And that function is what will receive a request and return a response.\n\nHere we use it to create a `GzipRequest` from the original request.\n\n{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}\n\n/// note | Technical Details\n\nA `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request.\n\nA `Request` also has a `request.receive`, that's a function to \"receive\" the body of the request.\n\nThe `scope` `dict` and `receive` function are both part of the ASGI specification.\n\nAnd those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.\n\nTo learn more about the `Request` check [Starlette's docs about Requests](https://www.starlette.dev/requests/).\n\n///\n\nThe only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`.\n\nDoing this, our `GzipRequest` will take care of decompressing the data (if necessary) before passing it to our *path operations*.\n\nAfter that, all of the processing logic is the same.\n\nBut because of our changes in `GzipRequest.body`, the request body will be automatically decompressed when it is loaded by **FastAPI** when needed.", "source_type": "doc", "path": "docs/en/docs/how-to/custom-request-and-route.md", "symbol": "Handling custom request body encodings { #handling-custom-request-body-encodings }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-request-and-route.md#L25-L80", "start_line": 25, "end_line": 80} {"id": "docs/en/docs/how-to/custom-request-and-route.md::Accessing the request body in an exception handler { #accessing-the-request-body-in-an-exception-handler }::L81", "text": "# Doc: docs/en/docs/how-to/custom-request-and-route.md | Page: Custom Request and APIRoute class { #custom-request-and-apiroute-class } | Section: Accessing the request body in an exception handler { #accessing-the-request-body-in-an-exception-handler }\n## Accessing the request body in an exception handler { #accessing-the-request-body-in-an-exception-handler }\n\n/// tip\n\nTo solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).\n\nBut this example is still valid and it shows how to interact with the internal components.\n\n///\n\nWe can also use this same approach to access the request body in an exception handler.\n\nAll we need to do is handle the request inside a `try`/`except` block:\n\n{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}\n\nIf an exception occurs, the `Request` instance will still be in scope, so we can read and make use of the request body when handling the error:\n\n{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}", "source_type": "doc", "path": "docs/en/docs/how-to/custom-request-and-route.md", "symbol": "Accessing the request body in an exception handler { #accessing-the-request-body-in-an-exception-handler }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-request-and-route.md#L81-L100", "start_line": 81, "end_line": 100} {"id": "docs/en/docs/how-to/custom-request-and-route.md::Custom `APIRoute` class in a router { #custom-apiroute-class-in-a-router }::L101", "text": "# Doc: docs/en/docs/how-to/custom-request-and-route.md | Page: Custom Request and APIRoute class { #custom-request-and-apiroute-class } | Section: Custom `APIRoute` class in a router { #custom-apiroute-class-in-a-router }\n## Custom `APIRoute` class in a router { #custom-apiroute-class-in-a-router }\n\nYou can also set the `route_class` parameter of an `APIRouter`:\n\n{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}\n\nIn this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response:\n\n{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}", "source_type": "doc", "path": "docs/en/docs/how-to/custom-request-and-route.md", "symbol": "Custom `APIRoute` class in a router { #custom-apiroute-class-in-a-router }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/custom-request-and-route.md#L101-L109", "start_line": 101, "end_line": 109} {"id": "docs/en/docs/how-to/extending-openapi.md::Extending OpenAPI { #extending-openapi }::L1", "text": "# Doc: docs/en/docs/how-to/extending-openapi.md | Page: Extending OpenAPI { #extending-openapi } | Section: Extending OpenAPI { #extending-openapi }\n# Extending OpenAPI { #extending-openapi }\n\nThere are some cases where you might need to modify the generated OpenAPI schema.\n\nIn this section you will see how.", "source_type": "doc", "path": "docs/en/docs/how-to/extending-openapi.md", "symbol": "Extending OpenAPI { #extending-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/extending-openapi.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/how-to/extending-openapi.md::The normal process { #the-normal-process }::L7", "text": "# Doc: docs/en/docs/how-to/extending-openapi.md | Page: Extending OpenAPI { #extending-openapi } | Section: The normal process { #the-normal-process }\n## The normal process { #the-normal-process }\n\nThe normal (default) process, is as follows.\n\nA `FastAPI` application (instance) has an `.openapi()` method that is expected to return the OpenAPI schema.\n\nAs part of the application object creation, a *path operation* for `/openapi.json` (or for whatever you set your `openapi_url`) is registered.\n\nIt just returns a JSON response with the result of the application's `.openapi()` method.\n\nBy default, what the method `.openapi()` does is check the property `.openapi_schema` to see if it has contents and return them.\n\nIf it doesn't, it generates them using the utility function at `fastapi.openapi.utils.get_openapi`.\n\nAnd that function `get_openapi()` receives as parameters:\n\n* `title`: The OpenAPI title, shown in the docs.\n* `version`: The version of your API, e.g. `2.5.0`.\n* `openapi_version`: The version of the OpenAPI specification used. By default, the latest: `3.1.0`.\n* `summary`: A short summary of the API.\n* `description`: The description of your API, this can include markdown and will be shown in the docs.\n* `routes`: The routes from the application, taken from `app.routes`. FastAPI uses them to collect the registered *path operations*, including those from included routers.\n\n/// tip | Technical Details\n\n`app.routes` is a lower-level route tree. It can include route candidates that FastAPI uses internally for included routers, not only final `APIRoute` objects.\n\nYou can still pass `app.routes` to `get_openapi()`. FastAPI will traverse that route tree to collect the effective path operations.\n\n///\n\n/// note\n\nThe parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above.\n\n///", "source_type": "doc", "path": "docs/en/docs/how-to/extending-openapi.md", "symbol": "The normal process { #the-normal-process }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/extending-openapi.md#L7-L43", "start_line": 7, "end_line": 43} {"id": "docs/en/docs/how-to/extending-openapi.md::Overriding the defaults { #overriding-the-defaults }::L44", "text": "# Doc: docs/en/docs/how-to/extending-openapi.md | Page: Extending OpenAPI { #extending-openapi } | Section: Overriding the defaults { #overriding-the-defaults }\n## Overriding the defaults { #overriding-the-defaults }\n\nUsing the information above, you can use the same utility function to generate the OpenAPI schema and override each part that you need.\n\nFor example, let's add [ReDoc's OpenAPI extension to include a custom logo](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).\n\n### Normal **FastAPI** { #normal-fastapi }\n\nFirst, write all your **FastAPI** application as normally:\n\n{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}\n\n### Generate the OpenAPI schema { #generate-the-openapi-schema }\n\nThen, use the same utility function to generate the OpenAPI schema, inside a `custom_openapi()` function:\n\n{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}\n\n### Modify the OpenAPI schema { #modify-the-openapi-schema }\n\nNow you can add the ReDoc extension, adding a custom `x-logo` to the `info` \"object\" in the OpenAPI schema:\n\n{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}\n\n### Cache the OpenAPI schema { #cache-the-openapi-schema }\n\nYou can use the property `.openapi_schema` as a \"cache\", to store your generated schema.\n\nThat way, your application won't have to generate the schema every time a user opens your API docs.\n\nIt will be generated only once, and then the same cached schema will be used for the next requests.\n\n{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}\n\n### Override the method { #override-the-method }\n\nNow you can replace the `.openapi()` method with your new function.\n\n{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}\n\n### Check it { #check-it }\n\nOnce you go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) you will see that you are using your custom logo (in this example, **FastAPI**'s logo):\n\n", "source_type": "doc", "path": "docs/en/docs/how-to/extending-openapi.md", "symbol": "Overriding the defaults { #overriding-the-defaults }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/extending-openapi.md#L44-L88", "start_line": 44, "end_line": 88} {"id": "docs/en/docs/how-to/general.md::General - How To - Recipes { #general-how-to-recipes }::L1", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: General - How To - Recipes { #general-how-to-recipes }\n# General - How To - Recipes { #general-how-to-recipes }\n\nHere are several pointers to other places in the docs, for general or frequent questions.", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "General - How To - Recipes { #general-how-to-recipes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/how-to/general.md::Filter Data - Security { #filter-data-security }::L5", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: Filter Data - Security { #filter-data-security }\n## Filter Data - Security { #filter-data-security }\n\nTo ensure that you don't return more data than you should, read the docs for [Tutorial - Response Model - Return Type](../tutorial/response-model.md).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "Filter Data - Security { #filter-data-security }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L5-L8", "start_line": 5, "end_line": 8} {"id": "docs/en/docs/how-to/general.md::Optimize Response Performance - Response Model - Return Type { #optimize-response-performance-response-model-return-type }::L9", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: Optimize Response Performance - Response Model - Return Type { #optimize-response-performance-response-model-return-type }\n## Optimize Response Performance - Response Model - Return Type { #optimize-response-performance-response-model-return-type }\n\nTo optimize performance when returning JSON data, use a return type or response model, that way Pydantic will handle the serialization to JSON on the Rust side, without going through Python. Read more in the docs for [Tutorial - Response Model - Return Type](../tutorial/response-model.md).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "Optimize Response Performance - Response Model - Return Type { #optimize-response-performance-response-model-return-type }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L9-L12", "start_line": 9, "end_line": 12} {"id": "docs/en/docs/how-to/general.md::Documentation Tags - OpenAPI { #documentation-tags-openapi }::L13", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: Documentation Tags - OpenAPI { #documentation-tags-openapi }\n## Documentation Tags - OpenAPI { #documentation-tags-openapi }\n\nTo add tags to your *path operations*, and group them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "Documentation Tags - OpenAPI { #documentation-tags-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L13-L16", "start_line": 13, "end_line": 16} {"id": "docs/en/docs/how-to/general.md::Documentation Summary and Description - OpenAPI { #documentation-summary-and-description-openapi }::L17", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: Documentation Summary and Description - OpenAPI { #documentation-summary-and-description-openapi }\n## Documentation Summary and Description - OpenAPI { #documentation-summary-and-description-openapi }\n\nTo add a summary and description to your *path operations*, and show them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "Documentation Summary and Description - OpenAPI { #documentation-summary-and-description-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L17-L20", "start_line": 17, "end_line": 20} {"id": "docs/en/docs/how-to/general.md::Documentation Response description - OpenAPI { #documentation-response-description-openapi }::L21", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: Documentation Response description - OpenAPI { #documentation-response-description-openapi }\n## Documentation Response description - OpenAPI { #documentation-response-description-openapi }\n\nTo define the description of the response, shown in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "Documentation Response description - OpenAPI { #documentation-response-description-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L21-L24", "start_line": 21, "end_line": 24} {"id": "docs/en/docs/how-to/general.md::Documentation Deprecate a *Path Operation* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }::L25", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: Documentation Deprecate a *Path Operation* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }\n## Documentation Deprecate a *Path Operation* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }\n\nTo deprecate a *path operation*, and show it in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "Documentation Deprecate a *Path Operation* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L25-L28", "start_line": 25, "end_line": 28} {"id": "docs/en/docs/how-to/general.md::Convert any Data to JSON-compatible { #convert-any-data-to-json-compatible }::L29", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: Convert any Data to JSON-compatible { #convert-any-data-to-json-compatible }\n## Convert any Data to JSON-compatible { #convert-any-data-to-json-compatible }\n\nTo convert any data to JSON-compatible, read the docs for [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "Convert any Data to JSON-compatible { #convert-any-data-to-json-compatible }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L29-L32", "start_line": 29, "end_line": 32} {"id": "docs/en/docs/how-to/general.md::OpenAPI Metadata - Docs { #openapi-metadata-docs }::L33", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: OpenAPI Metadata - Docs { #openapi-metadata-docs }\n## OpenAPI Metadata - Docs { #openapi-metadata-docs }\n\nTo add metadata to your OpenAPI schema, including a license, version, contact, etc, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "OpenAPI Metadata - Docs { #openapi-metadata-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L33-L36", "start_line": 33, "end_line": 36} {"id": "docs/en/docs/how-to/general.md::OpenAPI Custom URL { #openapi-custom-url }::L37", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: OpenAPI Custom URL { #openapi-custom-url }\n## OpenAPI Custom URL { #openapi-custom-url }\n\nTo customize the OpenAPI URL (or remove it), read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "OpenAPI Custom URL { #openapi-custom-url }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L37-L40", "start_line": 37, "end_line": 40} {"id": "docs/en/docs/how-to/general.md::OpenAPI Docs URLs { #openapi-docs-urls }::L41", "text": "# Doc: docs/en/docs/how-to/general.md | Page: General - How To - Recipes { #general-how-to-recipes } | Section: OpenAPI Docs URLs { #openapi-docs-urls }\n## OpenAPI Docs URLs { #openapi-docs-urls }\n\nTo update the URLs used for the automatically generated docs user interfaces, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls).", "source_type": "doc", "path": "docs/en/docs/how-to/general.md", "symbol": "OpenAPI Docs URLs { #openapi-docs-urls }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/general.md#L41-L43", "start_line": 41, "end_line": 43} {"id": "docs/en/docs/how-to/graphql.md::GraphQL { #graphql }::L1", "text": "# Doc: docs/en/docs/how-to/graphql.md | Page: GraphQL { #graphql } | Section: GraphQL { #graphql }\n# GraphQL { #graphql }\n\nAs **FastAPI** is based on the **ASGI** standard, it's very easy to integrate any **GraphQL** library also compatible with ASGI.\n\nYou can combine normal FastAPI *path operations* with GraphQL on the same application.\n\n/// tip\n\n**GraphQL** solves some very specific use cases.\n\nIt has **advantages** and **disadvantages** when compared to common **web APIs**.\n\nMake sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/how-to/graphql.md", "symbol": "GraphQL { #graphql }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/graphql.md#L1-L16", "start_line": 1, "end_line": 16} {"id": "docs/en/docs/how-to/graphql.md::GraphQL Libraries { #graphql-libraries }::L17", "text": "# Doc: docs/en/docs/how-to/graphql.md | Page: GraphQL { #graphql } | Section: GraphQL Libraries { #graphql-libraries }\n## GraphQL Libraries { #graphql-libraries }\n\nHere are some of the **GraphQL** libraries that have **ASGI** support. You could use them with **FastAPI**:\n\n* [Strawberry](https://strawberry.rocks/) 🍓\n * With [docs for FastAPI](https://strawberry.rocks/docs/integrations/fastapi)\n* [Ariadne](https://ariadnegraphql.org/)\n * With [docs for FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)\n* [Tartiflette](https://tartiflette.io/)\n * With [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) to provide ASGI integration\n* [Graphene](https://graphene-python.org/)\n * With [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)", "source_type": "doc", "path": "docs/en/docs/how-to/graphql.md", "symbol": "GraphQL Libraries { #graphql-libraries }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/graphql.md#L17-L29", "start_line": 17, "end_line": 29} {"id": "docs/en/docs/how-to/graphql.md::GraphQL with Strawberry { #graphql-with-strawberry }::L30", "text": "# Doc: docs/en/docs/how-to/graphql.md | Page: GraphQL { #graphql } | Section: GraphQL with Strawberry { #graphql-with-strawberry }\n## GraphQL with Strawberry { #graphql-with-strawberry }\n\nIf you need or want to work with **GraphQL**, [**Strawberry**](https://strawberry.rocks/) is the **recommended** library as it has the design closest to **FastAPI's** design, it's all based on **type annotations**.\n\nDepending on your use case, you might prefer to use a different library, but if you asked me, I would probably suggest you try **Strawberry**.\n\nHere's a small preview of how you could integrate Strawberry with FastAPI:\n\n{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}\n\nYou can learn more about Strawberry in the [Strawberry documentation](https://strawberry.rocks/).\n\nAnd also the docs about [Strawberry with FastAPI](https://strawberry.rocks/docs/integrations/fastapi).", "source_type": "doc", "path": "docs/en/docs/how-to/graphql.md", "symbol": "GraphQL with Strawberry { #graphql-with-strawberry }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/graphql.md#L30-L43", "start_line": 30, "end_line": 43} {"id": "docs/en/docs/how-to/graphql.md::Older `GraphQLApp` from Starlette { #older-graphqlapp-from-starlette }::L44", "text": "# Doc: docs/en/docs/how-to/graphql.md | Page: GraphQL { #graphql } | Section: Older `GraphQLApp` from Starlette { #older-graphqlapp-from-starlette }\n## Older `GraphQLApp` from Starlette { #older-graphqlapp-from-starlette }\n\nPrevious versions of Starlette included a `GraphQLApp` class to integrate with [Graphene](https://graphene-python.org/).\n\nIt was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3), that covers the same use case and has an **almost identical interface**.\n\n/// tip\n\nIf you need GraphQL, I still would recommend you check out [Strawberry](https://strawberry.rocks/), as it's based on type annotations instead of custom classes and types.\n\n///", "source_type": "doc", "path": "docs/en/docs/how-to/graphql.md", "symbol": "Older `GraphQLApp` from Starlette { #older-graphqlapp-from-starlette }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/graphql.md#L44-L55", "start_line": 44, "end_line": 55} {"id": "docs/en/docs/how-to/graphql.md::Learn More { #learn-more }::L56", "text": "# Doc: docs/en/docs/how-to/graphql.md | Page: GraphQL { #graphql } | Section: Learn More { #learn-more }\n## Learn More { #learn-more }\n\nYou can learn more about **GraphQL** in the [official GraphQL documentation](https://graphql.org/).\n\nYou can also read more about each of those libraries described above in their links.", "source_type": "doc", "path": "docs/en/docs/how-to/graphql.md", "symbol": "Learn More { #learn-more }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/graphql.md#L56-L60", "start_line": 56, "end_line": 60} {"id": "docs/en/docs/how-to/index.md::How To - Recipes { #how-to-recipes }::L1", "text": "# Doc: docs/en/docs/how-to/index.md | Page: How To - Recipes { #how-to-recipes } | Section: How To - Recipes { #how-to-recipes }\n# How To - Recipes { #how-to-recipes }\n\nHere you will see different recipes or \"how to\" guides for **several topics**.\n\nMost of these ideas would be more or less **independent**, and in most cases you should only need to study them if they apply directly to **your project**.\n\nIf something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them.\n\n/// tip\n\nIf you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md) chapter by chapter instead.\n\n///", "source_type": "doc", "path": "docs/en/docs/how-to/index.md", "symbol": "How To - Recipes { #how-to-recipes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/index.md#L1-L13", "start_line": 1, "end_line": 13} {"id": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md::Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }::L1", "text": "# Doc: docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md | Page: Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 } | Section: Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }\n# Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }\n\nIf you have an old FastAPI app, you might be using Pydantic version 1.\n\nFastAPI version 0.100.0 had support for either Pydantic v1 or v2. It would use whichever you had installed.\n\nFastAPI version 0.119.0 introduced partial support for Pydantic v1 from inside of Pydantic v2 (as `pydantic.v1`), to facilitate the migration to v2.\n\nFastAPI 0.126.0 dropped support for Pydantic v1, while still supporting `pydantic.v1` for a little while.\n\nFastAPI 0.128.0 dropped support for `pydantic.v1` as well, so the latest versions of FastAPI require Pydantic v2.\n\n/// warning\n\nThe Pydantic team stopped support for Pydantic v1 for the latest versions of Python, starting with **Python 3.14**.\n\nThis includes `pydantic.v1`, which is no longer supported in Python 3.14 and above.\n\nIf you want to use the latest features of Python, you will need to make sure you use Pydantic v2.\n\n///\n\nIf you have an old FastAPI app with Pydantic v1, here I'll show you how to migrate it to Pydantic v2, and the **features in FastAPI 0.119.0** to help you with a gradual migration.", "source_type": "doc", "path": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md", "symbol": "Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md#L1-L24", "start_line": 1, "end_line": 24} {"id": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md::Official Guide { #official-guide }::L25", "text": "# Doc: docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md | Page: Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 } | Section: Official Guide { #official-guide }\n## Official Guide { #official-guide }\n\nPydantic has an official [Migration Guide](https://docs.pydantic.dev/latest/migration/) from v1 to v2.\n\nIt also includes what has changed, how validations are now more correct and strict, possible caveats, etc.\n\nYou can read it to understand better what has changed.", "source_type": "doc", "path": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md", "symbol": "Official Guide { #official-guide }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md#L25-L32", "start_line": 25, "end_line": 32} {"id": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md::Tests { #tests }::L33", "text": "# Doc: docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md | Page: Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 } | Section: Tests { #tests }\n## Tests { #tests }\n\nMake sure you have [tests](../tutorial/testing.md) for your app and you run them on continuous integration (CI).\n\nThis way, you can do the upgrade and make sure everything is still working as expected.", "source_type": "doc", "path": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md", "symbol": "Tests { #tests }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md#L33-L38", "start_line": 33, "end_line": 38} {"id": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md::`bump-pydantic` { #bump-pydantic }::L39", "text": "# Doc: docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md | Page: Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 } | Section: `bump-pydantic` { #bump-pydantic }\n## `bump-pydantic` { #bump-pydantic }\n\nIn many cases, when you use regular Pydantic models without customizations, you will be able to automate most of the process of migrating from Pydantic v1 to Pydantic v2.\n\nYou can use [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) from the same Pydantic team.\n\nThis tool will help you to automatically change most of the code that needs to be changed.\n\nAfter this, you can run the tests and check if everything works. If it does, you are done. 😎", "source_type": "doc", "path": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md", "symbol": "`bump-pydantic` { #bump-pydantic }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md#L39-L48", "start_line": 39, "end_line": 48} {"id": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md::Pydantic v1 in v2 { #pydantic-v1-in-v2 }::L49", "text": "# Doc: docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md | Page: Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 } | Section: Pydantic v1 in v2 { #pydantic-v1-in-v2 }\n## Pydantic v1 in v2 { #pydantic-v1-in-v2 }\n\nPydantic v2 includes everything from Pydantic v1 as a submodule `pydantic.v1`. But this is no longer supported in versions above Python 3.13.\n\nThis means that you can install the latest version of Pydantic v2 and import and use the old Pydantic v1 components from this submodule, as if you had the old Pydantic v1 installed.\n\n{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}\n\n### FastAPI support for Pydantic v1 in v2 { #fastapi-support-for-pydantic-v1-in-v2 }\n\n/// warning\n\nThis FastAPI support for `pydantic.v1` models was added in **FastAPI 0.119.0** and removed in **FastAPI 0.128.0**. It was meant to be a temporary aid for the migration to Pydantic v2.\n\nIn current versions of FastAPI, using a `pydantic.v1` model in your app will raise an error.\n\nThe rest of this section describes the temporary support available only in those older versions.\n\n///\n\nSince FastAPI 0.119.0, there's also partial support for Pydantic v1 from inside of Pydantic v2, to facilitate the migration to v2.\n\nSo, you could upgrade Pydantic to the latest version 2, and change the imports to use the `pydantic.v1` submodule, and in many cases it would just work.\n\n{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}\n\n/// warning\n\nHave in mind that as the Pydantic team no longer supports Pydantic v1 in recent versions of Python, starting from Python 3.14, using `pydantic.v1` is also not supported in Python 3.14 and above.\n\n///\n\n### Pydantic v1 and v2 on the same app { #pydantic-v1-and-v2-on-the-same-app }\n\nIt's **not supported** by Pydantic to have a model of Pydantic v2 with its own fields defined as Pydantic v1 models or vice versa.\n\n```mermaid\ngraph TB\n subgraph \"❌ Not Supported\"\n direction TB\n subgraph V2[\"Pydantic v2 Model\"]\n V1Field[\"Pydantic v1 Model\"]\n end\n subgraph V1[\"Pydantic v1 Model\"]\n V2Field[\"Pydantic v2 Model\"]\n end\n end\n\n style V2 fill:#f9fff3\n style V1 fill:#fff6f0\n style V1Field fill:#fff6f0\n style V2Field fill:#f9fff3\n```\n\n...but you can have separate models, some using Pydantic v1 and others using Pydantic v2, in the same app.\n\n```mermaid\ngraph TB\n subgraph \"✅ Supported\"\n direction TB\n subgraph V2[\"Pydantic v2 Model\"]\n V2Field[\"Pydantic v2 Model\"]\n end\n subgraph V1[\"Pydantic v1 Model\"]\n V1Field[\"Pydantic v1 Model\"]\n end\n end\n\n style V2 fill:#f9fff3\n style V1 fill:#fff6f0\n style V1Field fill:#fff6f0\n style V2Field fill:#f9fff3\n```\n\nIn some cases, it's even possible to have both Pydantic v1 and v2 models in the same **path operation** in your FastAPI app:\n\n{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}\n\nIn this example above, the input model is a Pydantic v1 model, and the output model (defined in `response_model=ItemV2`) is a Pydantic v2 model.\n\n### Pydantic v1 parameters { #pydantic-v1-parameters }\n\nIf you need to use some of the FastAPI-specific tools for parameters like `Body`, `Query`, `Form`, etc. with Pydantic v1 models, you can import them from `fastapi.temp_pydantic_v1_params` while you finish the migration to Pydantic v2:\n\n{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}\n\n### Migrate in steps { #migrate-in-steps }\n\n/// warning\n\nThe gradual migration using both Pydantic v1 and v2 models in the same app described below only works in **FastAPI 0.119.0 to 0.127.x**. It was removed in **FastAPI 0.128.0**, the latest versions require **Pydantic v2** models.\n\n///\n\n/// tip\n\nFirst try with `bump-pydantic`, if your tests pass and that works, then you're done in one command. ✨\n\n///\n\nIf `bump-pydantic` doesn't work for your use case, you can use the support for both Pydantic v1 and v2 models in the same app to do the migration to Pydantic v2 gradually.\n\nYou could first upgrade Pydantic to use the latest version 2, and change the imports to use `pydantic.v1` for all your models.\n\nThen, you can start migrating your models from Pydantic v1 to v2 in groups, in gradual steps. 🚶", "source_type": "doc", "path": "docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md", "symbol": "Pydantic v1 in v2 { #pydantic-v1-in-v2 }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md#L49-L153", "start_line": 49, "end_line": 153} {"id": "docs/en/docs/how-to/separate-openapi-schemas.md::Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not }::L1", "text": "# Doc: docs/en/docs/how-to/separate-openapi-schemas.md | Page: Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not } | Section: Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not }\n# Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not }\n\nSince **Pydantic v2** was released, the generated OpenAPI is a bit more exact and **correct** than before. 😎\n\nIn fact, in some cases, it will even have **two JSON Schemas** in OpenAPI for the same Pydantic model, for input and output, depending on if they have **default values**.\n\nLet's see how that works and how to change it if you need to do that.", "source_type": "doc", "path": "docs/en/docs/how-to/separate-openapi-schemas.md", "symbol": "Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/separate-openapi-schemas.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/how-to/separate-openapi-schemas.md::Pydantic Models for Input and Output { #pydantic-models-for-input-and-output }::L9", "text": "# Doc: docs/en/docs/how-to/separate-openapi-schemas.md | Page: Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not } | Section: Pydantic Models for Input and Output { #pydantic-models-for-input-and-output }\n## Pydantic Models for Input and Output { #pydantic-models-for-input-and-output }\n\nLet's say you have a Pydantic model with default values, like this one:\n\n{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}\n\n### Model for Input { #model-for-input }\n\nIf you use this model as an input like here:\n\n{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}\n\n...then the `description` field will **not be required**. Because it has a default value of `None`.\n\n### Input Model in Docs { #input-model-in-docs }\n\nYou can confirm that in the docs, the `description` field doesn't have a **red asterisk**, it's not marked as required:\n\n
\n\n
\n\n### Model for Output { #model-for-output }\n\nBut if you use the same model as an output, like here:\n\n{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *}\n\n...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**.\n\n### Model for Output Response Data { #model-for-output-response-data }\n\nIf you interact with the docs and check the response, even though the code didn't add anything in one of the `description` fields, the JSON response contains the default value (`null`):\n\n
\n\n
\n\nThis means that it will **always have a value**, it's just that sometimes the value could be `None` (or `null` in JSON).\n\nThat means that clients using your API don't have to check if the value exists or not, they can **assume the field will always be there**, but just that in some cases it will have the default value of `None`.\n\nThe way to describe this in OpenAPI, is to mark that field as **required**, because it will always be there.\n\nBecause of that, the JSON Schema for a model can be different depending on if it's used for **input or output**:\n\n* for **input** the `description` will **not be required**\n* for **output** it will be **required** (and possibly `None`, or in JSON terms, `null`)\n\n### Model for Output in Docs { #model-for-output-in-docs }\n\nYou can check the output model in the docs too, **both** `name` and `description` are marked as **required** with a **red asterisk**:\n\n
\n\n
\n\n### Model for Input and Output in Docs { #model-for-input-and-output-in-docs }\n\nAnd if you check all the available Schemas (JSON Schemas) in OpenAPI, you will see that there are two, one `Item-Input` and one `Item-Output`.\n\nFor `Item-Input`, `description` is **not required**, it doesn't have a red asterisk.\n\nBut for `Item-Output`, `description` is **required**, it has a red asterisk.\n\n
\n\n
\n\nWith this feature from **Pydantic v2**, your API documentation is more **precise**, and if you have autogenerated clients and SDKs, they will be more precise too, with a better **developer experience** and consistency. 🎉", "source_type": "doc", "path": "docs/en/docs/how-to/separate-openapi-schemas.md", "symbol": "Pydantic Models for Input and Output { #pydantic-models-for-input-and-output }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/separate-openapi-schemas.md#L9-L79", "start_line": 9, "end_line": 79} {"id": "docs/en/docs/how-to/separate-openapi-schemas.md::Do not Separate Schemas { #do-not-separate-schemas }::L80", "text": "# Doc: docs/en/docs/how-to/separate-openapi-schemas.md | Page: Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not } | Section: Do not Separate Schemas { #do-not-separate-schemas }\n## Do not Separate Schemas { #do-not-separate-schemas }\n\nNow, there are some cases where you might want to have the **same schema for input and output**.\n\nProbably the main use case for this is if you already have some autogenerated client code/SDKs and you don't want to update all the autogenerated client code/SDKs yet, you probably will want to do it at some point, but maybe not right now.\n\nIn that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`.\n\n/// note\n\nSupport for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓\n\n///\n\n{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *}\n\n### Same Schema for Input and Output Models in Docs { #same-schema-for-input-and-output-models-in-docs }\n\nAnd now there will be one single schema for input and output for the model, only `Item`, and it will have `description` as **not required**:\n\n
\n\n
", "source_type": "doc", "path": "docs/en/docs/how-to/separate-openapi-schemas.md", "symbol": "Do not Separate Schemas { #do-not-separate-schemas }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/separate-openapi-schemas.md#L80-L102", "start_line": 80, "end_line": 102} {"id": "docs/en/docs/how-to/testing-database.md::Testing a Database { #testing-a-database }::L1", "text": "# Doc: docs/en/docs/how-to/testing-database.md | Page: Testing a Database { #testing-a-database } | Section: Testing a Database { #testing-a-database }\n# Testing a Database { #testing-a-database }\n\nYou can study about databases, SQL, and SQLModel in the [SQLModel docs](https://sqlmodel.tiangolo.com/). 🤓\n\nThere's a mini [tutorial on using SQLModel with FastAPI](https://sqlmodel.tiangolo.com/tutorial/fastapi/). ✨\n\nThat tutorial includes a section about [testing SQL databases](https://sqlmodel.tiangolo.com/tutorial/fastapi/tests/). 😎", "source_type": "doc", "path": "docs/en/docs/how-to/testing-database.md", "symbol": "Testing a Database { #testing-a-database }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/how-to/testing-database.md#L1-L7", "start_line": 1, "end_line": 7} {"id": "docs/en/docs/index.md::FastAPI { #fastapi }::L1", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: FastAPI { #fastapi }\n---\ninclude_yaml:\n sponsors: data/sponsors.yml\n---\n\n# FastAPI { #fastapi }\n\n\n\n

\n \"FastAPI\"\n

\n

\n FastAPI framework, high performance, easy to learn, fast to code, ready for production\n

\n

\n\n \"Test\"\n\n\n \"Coverage\"\n\n\n \"Package\n\n\n \"Supported\n\n

\n\n---\n\n**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com)\n\n**Source Code**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)\n\n---\n\nFastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.\n\nThe key features are:\n\n* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).\n* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *\n* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *\n* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.\n* **Easy**: Designed to be easy to use and learn. Less time reading docs.\n* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.\n* **Robust**: Get production-ready code. With automatic interactive documentation.\n* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (previously known as Swagger) and [JSON Schema](https://json-schema.org/).\n\n* estimation based on tests conducted by an internal development team, building production applications.", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "FastAPI { #fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L1-L55", "start_line": 1, "end_line": 55} {"id": "docs/en/docs/index.md::Sponsors { #sponsors }::L56", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Sponsors { #sponsors }\n## Sponsors { #sponsors }\n\n\n\n### Keystone Sponsor { #keystone-sponsor }\n\n
\n{% for sponsor in sponsors.keystone -%}\n\"{{\n{% endfor -%}\n
\n\n### Gold Sponsors { #gold-sponsors }\n\n
\n{% for sponsor in sponsors.gold -%}\n\"{{\n{% endfor -%}\n
\n\n### Silver Sponsors { #silver-sponsors }\n\n
\n{% for sponsor in sponsors.silver -%}\n\"{{\n{% endfor %}\n
\n\n\n\n[Other sponsors](https://fastapi.tiangolo.com/fastapi-people/#sponsors)", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Sponsors { #sponsors }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L56-L87", "start_line": 56, "end_line": 87} {"id": "docs/en/docs/index.md::Opinions { #opinions }::L88", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Opinions { #opinions }\n## Opinions { #opinions }\n\n\n
\n
\n \n \n \n \n
\n\n
\n
\"I'm using FastAPI a ton these days. I'm actually planning to use it for all of my team's ML services at Microsoft. Some of them are getting integrated into the core Windows product and some Office products.\"
\n
— Kabir Khan, Microsoft (ref)
\n
\n \n \n \n
\n\n\n
\n\n\"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._\"\n\n
Kabir Khan - Microsoft (ref)
\n\n---\n\n\"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_\"\n\n
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
\n\n---\n\n\"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_\"\n\n
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
\n\n---\n\n\"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._\"\n\n
Deon Pillsbury - Cisco (ref)
\n\n---\n\n
", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Opinions { #opinions }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L88-L153", "start_line": 88, "end_line": 153} {"id": "docs/en/docs/index.md::FastAPI Conf { #fastapi-conf }::L154", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: FastAPI Conf { #fastapi-conf }\n## FastAPI Conf { #fastapi-conf }\n\n[**FastAPI Conf '26**](https://fastapiconf.com) is happening on **October 28, 2026** in **Amsterdam, NL**. All about FastAPI, right from the source. 🎤\n\n\"FastAPI", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "FastAPI Conf { #fastapi-conf }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L154-L159", "start_line": 154, "end_line": 159} {"id": "docs/en/docs/index.md::FastAPI mini documentary { #fastapi-mini-documentary }::L160", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: FastAPI mini documentary { #fastapi-mini-documentary }\n## FastAPI mini documentary { #fastapi-mini-documentary }\n\nThere's a [FastAPI mini documentary](https://www.youtube.com/watch?v=mpR8ngthqiE) released at the end of 2025, you can watch it online:\n\n\"FastAPI", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "FastAPI mini documentary { #fastapi-mini-documentary }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L160-L165", "start_line": 160, "end_line": 165} {"id": "docs/en/docs/index.md::**Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }::L166", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: **Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }\n## **Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }\n\n\n\nIf you are building a CLI app to be used in the terminal instead of a web API, check out [**Typer**](https://typer.tiangolo.com/).\n\n**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "**Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L166-L173", "start_line": 166, "end_line": 173} {"id": "docs/en/docs/index.md::Requirements { #requirements }::L174", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Requirements { #requirements }\n## Requirements { #requirements }\n\nFastAPI stands on the shoulders of giants:\n\n* [Starlette](https://www.starlette.dev/) for the web parts.\n* [Pydantic](https://docs.pydantic.dev/) for the data parts.", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Requirements { #requirements }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L174-L180", "start_line": 174, "end_line": 180} {"id": "docs/en/docs/index.md::Installation { #installation }::L181", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Installation { #installation }\n## Installation { #installation }\n\nCreate and activate a [virtual environment](https://fastapi.tiangolo.com/virtual-environments/) and then install FastAPI:\n\n
\n\n```console\n$ pip install \"fastapi[standard]\"\n\n---> 100%\n```\n\n
\n\n**Note**: Make sure you put `\"fastapi[standard]\"` in quotes to ensure it works in all terminals.", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Installation { #installation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L181-L196", "start_line": 181, "end_line": 196} {"id": "docs/en/docs/index.md::Example { #example }::L197", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Example { #example }\n## Example { #example }\n\n### Create it { #create-it }\n\nCreate a file `main.py` with:\n\n```Python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/items/{item_id}\")\ndef read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n```\n\n
\nOr use async def...\n\nIf your code uses `async` / `await`, use `async def`:\n\n```Python hl_lines=\"7 12\"\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n```\n\n**Note**:\n\nIf you don't know, check the _\"In a hurry?\"_ section about [`async` and `await` in the docs](https://fastapi.tiangolo.com/async/#in-a-hurry).\n\n
\n\n### Run it { #run-it }\n\nRun the server with:\n\n
\n\n```console\n$ fastapi dev\n\n ╭────────── FastAPI CLI - Development mode ───────────╮\n │ │\n │ Serving at: http://127.0.0.1:8000 │\n │ │\n │ API docs: http://127.0.0.1:8000/docs │\n │ │\n │ Running in development mode, for production use: │\n │ │\n │ fastapi run │\n │ │\n ╰─────────────────────────────────────────────────────╯\n\nINFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\nINFO: Started reloader process [2248755] using WatchFiles\nINFO: Started server process [2248757]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\n```\n\n
\n\n
\nAbout the command fastapi dev...\n\nThe command `fastapi dev` reads your `main.py` file automatically, detects the **FastAPI** app in it, and starts a server using [Uvicorn](https://www.uvicorn.dev).\n\nBy default, `fastapi dev` will start with auto-reload enabled for local development.\n\nYou can read more about it in the [FastAPI CLI docs](https://fastapi.tiangolo.com/fastapi-cli/).\n\n
\n\n### Check it { #check-it }\n\nOpen your browser at [http://127.0.0.1:8000/items/5?q=somequery](http://127.0.0.1:8000/items/5?q=somequery).\n\nYou will see the JSON response as:\n\n```JSON\n{\"item_id\": 5, \"q\": \"somequery\"}\n```\n\nYou already created an API that:\n\n* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.\n* Both _paths_ take `GET` operations (also known as HTTP _methods_).\n* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.\n* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.\n\n### Interactive API docs { #interactive-api-docs }\n\nNow go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see the automatic interactive API documentation (provided by [Swagger UI](https://github.com/swagger-api/swagger-ui)):\n\n![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)\n\n### Alternative API docs { #alternative-api-docs }\n\nAnd now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).\n\nYou will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):\n\n![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Example { #example }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L197-L320", "start_line": 197, "end_line": 320} {"id": "docs/en/docs/index.md::Example upgrade { #example-upgrade }::L321", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Example upgrade { #example-upgrade }\n## Example upgrade { #example-upgrade }\n\nNow modify the file `main.py` to receive a body from a `PUT` request.\n\nDeclare the body using standard Python types, thanks to Pydantic.\n\n```Python hl_lines=\"2 7-10 23-25\"\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n price: float\n is_offer: bool | None = None\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.get(\"/items/{item_id}\")\ndef read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n\n\n@app.put(\"/items/{item_id}\")\ndef update_item(item_id: int, item: Item):\n return {\"item_name\": item.name, \"item_id\": item_id}\n```\n\nThe `fastapi dev` server should reload automatically.\n\n### Interactive API docs upgrade { #interactive-api-docs-upgrade }\n\nNow go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\n* The interactive API documentation will be automatically updated, including the new body:\n\n![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)\n\n* Click on the button \"Try it out\", it allows you to fill the parameters and directly interact with the API:\n\n![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)\n\n* Then click on the \"Execute\" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:\n\n![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)\n\n### Alternative API docs upgrade { #alternative-api-docs-upgrade }\n\nAnd now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).\n\n* The alternative documentation will also reflect the new query parameter and body:\n\n![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)\n\n### Recap { #recap }\n\nIn summary, you declare **once** the types of parameters, body, etc. as function parameters.\n\nYou do that with standard modern Python types.\n\nYou don't have to learn a new syntax, the methods or classes of a specific library, etc.\n\nJust standard **Python**.\n\nFor example, for an `int`:\n\n```Python\nitem_id: int\n```\n\nor for a more complex `Item` model:\n\n```Python\nitem: Item\n```\n\n...and with that single declaration you get:\n\n* Editor support, including:\n * Completion.\n * Type checks.\n* Validation of data:\n * Automatic and clear errors when the data is invalid.\n * Validation even for deeply nested JSON objects.\n* Conversion of input data: coming from the network to Python data and types. Reading from:\n * JSON.\n * Path parameters.\n * Query parameters.\n * Cookies.\n * Headers.\n * Forms.\n * Files.\n* Conversion of output data: converting from Python data and types to network data (as JSON):\n * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).\n * `datetime` objects.\n * `UUID` objects.\n * Database models.\n * ...and many more.\n* Automatic interactive API documentation, including 2 alternative user interfaces:\n * Swagger UI.\n * ReDoc.\n\n---\n\nComing back to the previous code example, **FastAPI** will:\n\n* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.\n* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.\n * If it is not, the client will see a useful, clear error.\n* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.\n * As the `q` parameter is declared with `= None`, it is optional.\n * Without the `None` it would be required (as is the body in the case with `PUT`).\n* For `PUT` requests to `/items/{item_id}`, read the body as JSON:\n * Check that it has a required attribute `name` that should be a `str`.\n * Check that it has a required attribute `price` that has to be a `float`.\n * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.\n * All this would also work for deeply nested JSON objects.\n* Convert from and to JSON automatically.\n* Document everything with OpenAPI, that can be used by:\n * Interactive documentation systems.\n * Automatic client code generation systems, for many languages.\n* Provide 2 interactive documentation web interfaces directly.\n\n---\n\nWe just scratched the surface, but you already get the idea of how it all works.\n\nTry changing the line with:\n\n```Python\n return {\"item_name\": item.name, \"item_id\": item_id}\n```\n\n...from:\n\n```Python\n ... \"item_name\": item.name ...\n```\n\n...to:\n\n```Python\n ... \"item_price\": item.price ...\n```\n\n...and see how your editor will auto-complete the attributes and know their types:\n\n![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)\n\nFor a more complete example including more features, see the Tutorial - User Guide.\n\n**Spoiler alert**: the tutorial - user guide includes:\n\n* Declaration of **parameters** from other different places such as: **headers**, **cookies**, **form fields** and **files**.\n* How to set **validation constraints** such as `maximum_length` or `regex`.\n* A very powerful and easy to use **Dependency Injection** system.\n* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.\n* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).\n* **GraphQL** integration with [Strawberry](https://strawberry.rocks) and other libraries.\n* Many extra features (thanks to Starlette) such as:\n * **WebSockets**\n * extremely easy tests based on HTTPX and `pytest`\n * **CORS**\n * **Cookie Sessions**\n * ...and more.\n\n### Deploy your app (optional) { #deploy-your-app-optional }\n\nYou can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀\n\n
\n\n```console\n$ fastapi deploy\n\nDeploying to FastAPI Cloud...\n\n✅ Deployment successful!\n\n🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev\n```\n\n
\n\nThe CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.\n\nThat's it! Now you can access your app at that URL. ✨\n\n#### About FastAPI Cloud { #about-fastapi-cloud }\n\n**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**.\n\nIt streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort.\n\nIt brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉\n\nFastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨\n\n#### Deploy to other cloud providers { #deploy-to-other-cloud-providers }\n\nFastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.\n\nFollow your cloud provider's guides to deploy FastAPI apps with them. 🤓", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Example upgrade { #example-upgrade }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L321-L530", "start_line": 321, "end_line": 530} {"id": "docs/en/docs/index.md::Performance { #performance }::L531", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Performance { #performance }\n## Performance { #performance }\n\nIndependent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as [one of the fastest Python frameworks available](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)\n\nTo understand more about it, see the section [Benchmarks](https://fastapi.tiangolo.com/benchmarks/).", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Performance { #performance }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L531-L536", "start_line": 531, "end_line": 536} {"id": "docs/en/docs/index.md::Dependencies { #dependencies }::L537", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Dependencies { #dependencies }\n## Dependencies { #dependencies }\n\nFastAPI depends on Pydantic and Starlette.\n\n### `standard` Dependencies { #standard-dependencies }\n\nWhen you install FastAPI with `pip install \"fastapi[standard]\"` it comes with the `standard` group of optional dependencies:\n\nUsed by Pydantic:\n\n* [`email-validator`](https://github.com/JoshData/python-email-validator) - for email validation.\n\nUsed by Starlette:\n\n* [`httpx`](https://www.python-httpx.org) - Required if you want to use the `TestClient`.\n* [`jinja2`](https://jinja.palletsprojects.com) - Required if you want to use the default template configuration.\n* [`python-multipart`](https://github.com/Kludex/python-multipart) - Required if you want to support form \"parsing\", with `request.form()`.\n\nUsed by FastAPI:\n\n* [`uvicorn`](https://www.uvicorn.dev) - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.\n* `fastapi-cli[standard]` - to provide the `fastapi` command.\n * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [FastAPI Cloud](https://fastapicloud.com).\n\n### Without `standard` Dependencies { #without-standard-dependencies }\n\nIf you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install \"fastapi[standard]\"`.\n\n### Without `fastapi-cloud-cli` { #without-fastapi-cloud-cli }\n\nIf you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install \"fastapi[standard-no-fastapi-cloud-cli]\"`.\n\n### Additional Optional Dependencies { #additional-optional-dependencies }\n\nThere are some additional dependencies you might want to install.\n\nAdditional optional Pydantic dependencies:\n\n* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.\n* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.\n\nAdditional optional FastAPI dependencies:\n\n* [`orjson`](https://github.com/ijl/orjson) - Required if you want to use `ORJSONResponse`.\n* [`ujson`](https://github.com/esnme/ultrajson) - Required if you want to use `UJSONResponse`.", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "Dependencies { #dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L537-L582", "start_line": 537, "end_line": 582} {"id": "docs/en/docs/index.md::License { #license }::L583", "text": "# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: License { #license }\n## License { #license }\n\nThis project is licensed under the terms of the MIT license.", "source_type": "doc", "path": "docs/en/docs/index.md", "symbol": "License { #license }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/index.md#L583-L585", "start_line": 583, "end_line": 585} {"id": "docs/en/docs/learn/index.md::Learn { #learn }::L1", "text": "# Doc: docs/en/docs/learn/index.md | Page: Learn { #learn } | Section: Learn { #learn }\n# Learn { #learn }\n\nHere are the introductory sections and the tutorials to learn **FastAPI**.\n\nYou could consider this a **book**, a **course**, the **official** and recommended way to learn FastAPI. 😎", "source_type": "doc", "path": "docs/en/docs/learn/index.md", "symbol": "Learn { #learn }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/learn/index.md#L1-L5", "start_line": 1, "end_line": 5} {"id": "docs/en/docs/management.md::Repository Management::L1", "text": "# Doc: docs/en/docs/management.md | Page: Repository Management | Section: Repository Management\n# Repository Management\n\nHere's a short description of how the FastAPI repository is managed and maintained.", "source_type": "doc", "path": "docs/en/docs/management.md", "symbol": "Repository Management", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/management.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/management.md::Owner::L5", "text": "# Doc: docs/en/docs/management.md | Page: Repository Management | Section: Owner\n## Owner\n\nI, [@tiangolo](https://github.com/tiangolo), am the creator and owner of the FastAPI repository. 🤓\n\nI normally give the final review to each PR before merging them. I make the final decisions on the project, I'm the [BDFL](https://en.wikipedia.org/wiki/Benevolent_dictator_for_life). 😅", "source_type": "doc", "path": "docs/en/docs/management.md", "symbol": "Owner", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/management.md#L5-L10", "start_line": 5, "end_line": 10} {"id": "docs/en/docs/management.md::Team::L11", "text": "# Doc: docs/en/docs/management.md | Page: Repository Management | Section: Team\n## Team\n\nThere's a team of people that help manage and maintain the project. 😎\n\nLearn more about it in [tiangolo.com - GitHub FastAPI](https://tiangolo.com/github-fastapi/).", "source_type": "doc", "path": "docs/en/docs/management.md", "symbol": "Team", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/management.md#L11-L16", "start_line": 11, "end_line": 16} {"id": "docs/en/docs/management.md::FastAPI Experts::L17", "text": "# Doc: docs/en/docs/management.md | Page: Repository Management | Section: FastAPI Experts\n## FastAPI Experts\n\nThe people that help others the most in GitHub Discussions can become [**FastAPI Experts**](./fastapi-people.md#fastapi-experts).\n\nThis is normally the best way to contribute to the project.", "source_type": "doc", "path": "docs/en/docs/management.md", "symbol": "FastAPI Experts", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/management.md#L17-L22", "start_line": 17, "end_line": 22} {"id": "docs/en/docs/management.md::External Help::L23", "text": "# Doc: docs/en/docs/management.md | Page: Repository Management | Section: External Help\n## External Help\n\nExternal help is very much appreciated. There are many ways to [help](./help-fastapi.md). ☕️", "source_type": "doc", "path": "docs/en/docs/management.md", "symbol": "External Help", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/management.md#L23-L25", "start_line": 23, "end_line": 25} {"id": "docs/en/docs/newsletter.md::FastAPI and friends newsletter::L1", "text": "# Doc: docs/en/docs/newsletter.md | Page: FastAPI and friends newsletter | Section: FastAPI and friends newsletter\n# FastAPI and friends newsletter\n\n\n\n", "source_type": "doc", "path": "docs/en/docs/newsletter.md", "symbol": "FastAPI and friends newsletter", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/newsletter.md#L1-L5", "start_line": 1, "end_line": 5} {"id": "docs/en/docs/project-generation.md::Full Stack FastAPI Template { #full-stack-fastapi-template }::L1", "text": "# Doc: docs/en/docs/project-generation.md | Page: Full Stack FastAPI Template { #full-stack-fastapi-template } | Section: Full Stack FastAPI Template { #full-stack-fastapi-template }\n# Full Stack FastAPI Template { #full-stack-fastapi-template }\n\nTemplates, while they typically come with a specific setup, are designed to be flexible and customizable. This allows you to modify and adapt them to your project's requirements, making them an excellent starting point. 🏁\n\nYou can use this template to get started, as it includes a lot of the initial setup, security, database and some API endpoints already done for you.\n\nGitHub Repository: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)", "source_type": "doc", "path": "docs/en/docs/project-generation.md", "symbol": "Full Stack FastAPI Template { #full-stack-fastapi-template }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/project-generation.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/project-generation.md::Full Stack FastAPI Template - Technology Stack and Features { #full-stack-fastapi-template-technology-stack-and-features }::L9", "text": "# Doc: docs/en/docs/project-generation.md | Page: Full Stack FastAPI Template { #full-stack-fastapi-template } | Section: Full Stack FastAPI Template - Technology Stack and Features { #full-stack-fastapi-template-technology-stack-and-features }\n## Full Stack FastAPI Template - Technology Stack and Features { #full-stack-fastapi-template-technology-stack-and-features }\n\n- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API.\n - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM).\n - 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management.\n - 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database.\n- 🚀 [React](https://react.dev) for the frontend.\n - 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.\n - 🎨 [Tailwind CSS](https://tailwindcss.com) and [shadcn/ui](https://ui.shadcn.com) for the frontend components.\n - 🤖 An automatically generated frontend client.\n - 🧪 [Playwright](https://playwright.dev) for End-to-End testing.\n - 🦇 Dark mode support.\n- 🐋 [Docker Compose](https://www.docker.com) for development and production.\n- 🔒 Secure password hashing by default.\n- 🔑 JWT (JSON Web Token) authentication.\n- 📫 Email based password recovery.\n- ✅ Tests with [Pytest](https://pytest.org).\n- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.\n- 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates.\n- 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions.", "source_type": "doc", "path": "docs/en/docs/project-generation.md", "symbol": "Full Stack FastAPI Template - Technology Stack and Features { #full-stack-fastapi-template-technology-stack-and-features }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/project-generation.md#L9-L28", "start_line": 9, "end_line": 28} {"id": "docs/en/docs/python-types.md::Python Types Intro { #python-types-intro }::L1", "text": "# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Python Types Intro { #python-types-intro }\n# Python Types Intro { #python-types-intro }\n\nPython has support for optional \"type hints\" (also called \"type annotations\").\n\nThese **\"type hints\"** or annotations are a special syntax that allows declaring the type of a variable.\n\nBy declaring types for your variables, editors and tools can give you better support.\n\nThis is just a **quick tutorial / refresher** about Python type hints. It covers only the minimum necessary to use them with **FastAPI**... which is actually very little.\n\n**FastAPI** is all based on these type hints, they give it many advantages and benefits.\n\nBut even if you never use **FastAPI**, you would benefit from learning a bit about them.\n\n/// note\n\nIf you are a Python expert, and you already know everything about type hints, skip to the next chapter.\n\n///", "source_type": "doc", "path": "docs/en/docs/python-types.md", "symbol": "Python Types Intro { #python-types-intro }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/python-types.md#L1-L20", "start_line": 1, "end_line": 20} {"id": "docs/en/docs/python-types.md::Motivation { #motivation }::L21", "text": "# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Motivation { #motivation }\n## Motivation { #motivation }\n\nLet's start with a simple example:\n\n{* ../../docs_src/python_types/tutorial001_py310.py *}\n\nCalling this program outputs:\n\n```\nJohn Doe\n```\n\nThe function does the following:\n\n* Takes a `first_name` and `last_name`.\n* Converts the first letter of each one to upper case with `title()`.\n* Concatenates them with a space in the middle.\n\n{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}\n\n### Edit it { #edit-it }\n\nIt's a very simple program.\n\nBut now imagine that you were writing it from scratch.\n\nAt some point you start defining the function, and you have the parameters ready...\n\nBut then you have to call \"that method that converts the first letter to upper case\".\n\nWas it `upper`? Was it `uppercase`? `first_uppercase`? `capitalize`?\n\nThen, you try with the old programmer's friend, editor autocompletion.\n\nYou type the first parameter of the function, `first_name`, then a dot (`.`) and then hit `Ctrl+Space` to trigger the completion.\n\nBut, sadly, you get nothing useful:\n\n\n\n### Add types { #add-types }\n\nLet's modify a single line from the previous version.\n\nWe will change exactly this fragment, the parameters of the function, from:\n\n```Python\n first_name, last_name\n```\n\nto:\n\n```Python\n first_name: str, last_name: str\n```\n\nThat's it.\n\nThose are the \"type hints\":\n\n{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}\n\nThat is not the same as declaring default values like it would be with:\n\n```Python\n first_name=\"john\", last_name=\"doe\"\n```\n\nIt's a different thing.\n\nWe are using colons (`:`), not equals (`=`).\n\nAnd adding type hints normally doesn't change what happens from what would happen without them.\n\nBut now, imagine you are again in the middle of creating that function, but with type hints.\n\nAt the same point, you try to trigger the autocomplete with `Ctrl+Space` and you see:\n\n\n\nWith that, you can scroll, seeing the options, until you find the one that \"rings a bell\":\n\n", "source_type": "doc", "path": "docs/en/docs/python-types.md", "symbol": "Motivation { #motivation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/python-types.md#L21-L104", "start_line": 21, "end_line": 104} {"id": "docs/en/docs/python-types.md::More motivation { #more-motivation }::L105", "text": "# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: More motivation { #more-motivation }\n## More motivation { #more-motivation }\n\nCheck this function, it already has type hints:\n\n{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}\n\nBecause the editor knows the types of the variables, you don't only get completion, you also get error checks:\n\n\n\nNow you know that you have to fix it, convert `age` to a string with `str(age)`:\n\n{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}", "source_type": "doc", "path": "docs/en/docs/python-types.md", "symbol": "More motivation { #more-motivation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/python-types.md#L105-L118", "start_line": 105, "end_line": 118} {"id": "docs/en/docs/python-types.md::Declaring types { #declaring-types }::L119", "text": "# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Declaring types { #declaring-types }\n## Declaring types { #declaring-types }\n\nYou just saw the main place to declare type hints. As function parameters.\n\nThis is also the main place you would use them with **FastAPI**.\n\n### Simple types { #simple-types }\n\nYou can declare all the standard Python types, not only `str`.\n\nYou can use, for example:\n\n* `int`\n* `float`\n* `bool`\n* `bytes`\n\n{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}\n\n### `typing` module { #typing-module }\n\nFor some additional use cases, you might need to import some things from the standard library `typing` module, for example when you want to declare that something has \"any type\", you can use `Any` from `typing`:\n\n```python\nfrom typing import Any\n\n\ndef some_function(data: Any):\n print(data)\n```\n\n### Generic types { #generic-types }\n\nSome types can take \"type parameters\" in square brackets, to define their internal types, for example a \"list of strings\" would be declared `list[str]`.\n\nThese types that can take type parameters are called **Generic types** or **Generics**.\n\nYou can use the same builtin types as generics (with square brackets and types inside):\n\n* `list`\n* `tuple`\n* `set`\n* `dict`\n\n#### List { #list }\n\nFor example, let's define a variable to be a `list` of `str`.\n\nDeclare the variable, with the same colon (`:`) syntax.\n\nAs the type, put `list`.\n\nAs the list is a type that contains some internal types, you put them in square brackets:\n\n{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}\n\n/// note\n\nThose internal types in the square brackets are called \"type parameters\".\n\nIn this case, `str` is the type parameter passed to `list`.\n\n///\n\nThat means: \"the variable `items` is a `list`, and each of the items in this list is a `str`\".\n\nBy doing that, your editor can provide support even while processing items from the list:\n\n\n\nWithout types, that's almost impossible to achieve.\n\nNotice that the variable `item` is one of the elements in the list `items`.\n\nAnd still, the editor knows it is a `str`, and provides support for that.\n\n#### Tuple and Set { #tuple-and-set }\n\nYou would do the same to declare `tuple`s and `set`s:\n\n{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}\n\nThis means:\n\n* The variable `items_t` is a `tuple` with 3 items, an `int`, another `int`, and a `str`.\n* The variable `items_s` is a `set`, and each of its items is of type `bytes`.\n\n#### Dict { #dict }\n\nTo define a `dict`, you pass 2 type parameters, separated by commas.\n\nThe first type parameter is for the keys of the `dict`.\n\nThe second type parameter is for the values of the `dict`:\n\n{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}\n\nThis means:\n\n* The variable `prices` is a `dict`:\n * The keys of this `dict` are of type `str` (let's say, the name of each item).\n * The values of this `dict` are of type `float` (let's say, the price of each item).\n\n#### Union { #union }\n\nYou can declare that a variable can be any of **several types**, for example, an `int` or a `str`.\n\nTo define it you use the vertical bar (`|`) to separate both types.\n\nThis is called a \"union\", because the variable can be anything in the union of those two sets of types.\n\n```Python hl_lines=\"1\"\n{!> ../../docs_src/python_types/tutorial008b_py310.py!}\n```\n\nThis means that `item` could be an `int` or a `str`.\n\n#### Possibly `None` { #possibly-none }\n\nYou can declare that a value could have a type, like `str`, but that it could also be `None`.\n\n//// tab | Python 3.10+\n\n```Python hl_lines=\"1\"\n{!> ../../docs_src/python_types/tutorial009_py310.py!}\n```\n\n////\n\nUsing `str | None` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too.\n\n### Classes as types { #classes-as-types }\n\nYou can also declare a class as the type of a variable.\n\nLet's say you have a class `Person`, with a name:\n\n{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}\n\nThen you can declare a variable to be of type `Person`:\n\n{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}\n\nAnd then, again, you get all the editor support:\n\n\n\nNotice that this means \"`one_person` is an **instance** of the class `Person`\".\n\nIt doesn't mean \"`one_person` is the **class** called `Person`\".", "source_type": "doc", "path": "docs/en/docs/python-types.md", "symbol": "Declaring types { #declaring-types }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/python-types.md#L119-L269", "start_line": 119, "end_line": 269} {"id": "docs/en/docs/python-types.md::Pydantic models { #pydantic-models }::L270", "text": "# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Pydantic models { #pydantic-models }\n## Pydantic models { #pydantic-models }\n\n[Pydantic](https://docs.pydantic.dev/) is a Python library to perform data validation.\n\nYou declare the \"shape\" of the data as classes with attributes.\n\nAnd each attribute has a type.\n\nThen you create an instance of that class with some values and it will validate the values, convert them to the appropriate type (if that's the case) and give you an object with all the data.\n\nAnd you get all the editor support with that resulting object.\n\nAn example from the official Pydantic docs:\n\n{* ../../docs_src/python_types/tutorial011_py310.py *}\n\n/// note\n\nTo learn more about [Pydantic, check its docs](https://docs.pydantic.dev/).\n\n///\n\n**FastAPI** is all based on Pydantic.\n\nYou will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md).", "source_type": "doc", "path": "docs/en/docs/python-types.md", "symbol": "Pydantic models { #pydantic-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/python-types.md#L270-L295", "start_line": 270, "end_line": 295} {"id": "docs/en/docs/python-types.md::Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }::L296", "text": "# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }\n## Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }\n\nPython also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.\n\nYou can import `Annotated` from `typing`.\n\n{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}\n\nPython itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.\n\nBut you can use this space in `Annotated` to provide **FastAPI** with additional metadata about how you want your application to behave.\n\nThe important thing to remember is that **the first *type parameter*** you pass to `Annotated` is the **actual type**. The rest, is just metadata for other tools.\n\nFor now, you just need to know that `Annotated` exists, and that it's standard Python. 😎\n\nLater you will see how **powerful** it can be.\n\n/// tip\n\nThe fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨\n\nAnd also that your code will be very compatible with many other Python tools and libraries. 🚀\n\n///", "source_type": "doc", "path": "docs/en/docs/python-types.md", "symbol": "Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/python-types.md#L296-L321", "start_line": 296, "end_line": 321} {"id": "docs/en/docs/python-types.md::Type hints in **FastAPI** { #type-hints-in-fastapi }::L322", "text": "# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Type hints in **FastAPI** { #type-hints-in-fastapi }\n## Type hints in **FastAPI** { #type-hints-in-fastapi }\n\n**FastAPI** takes advantage of these type hints to do several things.\n\nWith **FastAPI** you declare parameters with type hints and you get:\n\n* **Editor support**.\n* **Type checks**.\n\n...and **FastAPI** uses the same declarations to:\n\n* **Define requirements**: from request path parameters, query parameters, headers, bodies, dependencies, etc.\n* **Convert data**: from the request to the required type.\n* **Validate data**: coming from each request:\n * Generating **automatic errors** returned to the client when the data is invalid.\n* **Document** the API using OpenAPI:\n * which is then used by the automatic interactive documentation user interfaces.\n\nThis might all sound abstract. Don't worry. You'll see all this in action in the [Tutorial - User Guide](tutorial/index.md).\n\nThe important thing is that by using standard Python types, in a single place (instead of adding more classes, decorators, etc), **FastAPI** will do a lot of the work for you.\n\n/// note\n\nIf you already went through all the tutorial and came back to see more about types, a good resource is [the \"cheat sheet\" from `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).\n\n///", "source_type": "doc", "path": "docs/en/docs/python-types.md", "symbol": "Type hints in **FastAPI** { #type-hints-in-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/python-types.md#L322-L348", "start_line": 322, "end_line": 348} {"id": "docs/en/docs/reference/apirouter.md::`APIRouter` class::L1", "text": "# Doc: docs/en/docs/reference/apirouter.md | Page: `APIRouter` class | Section: `APIRouter` class\n# `APIRouter` class\n\nHere's the reference information for the `APIRouter` class, with all its parameters, attributes and methods.\n\nYou can import the `APIRouter` class directly from `fastapi`:\n\n```python\nfrom fastapi import APIRouter\n```\n\n::: fastapi.APIRouter\n options:\n members:\n - websocket\n - include_router\n - frontend\n - get\n - put\n - post\n - delete\n - options\n - head\n - patch\n - trace\n - on_event", "source_type": "doc", "path": "docs/en/docs/reference/apirouter.md", "symbol": "`APIRouter` class", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/apirouter.md#L1-L25", "start_line": 1, "end_line": 25} {"id": "docs/en/docs/reference/background.md::Background Tasks - `BackgroundTasks`::L1", "text": "# Doc: docs/en/docs/reference/background.md | Page: Background Tasks - `BackgroundTasks` | Section: Background Tasks - `BackgroundTasks`\n# Background Tasks - `BackgroundTasks`\n\nYou can declare a parameter in a *path operation function* or dependency function with the type `BackgroundTasks`, and then you can use it to schedule the execution of background tasks after the response is sent.\n\nYou can import it directly from `fastapi`:\n\n```python\nfrom fastapi import BackgroundTasks\n```\n\n::: fastapi.BackgroundTasks", "source_type": "doc", "path": "docs/en/docs/reference/background.md", "symbol": "Background Tasks - `BackgroundTasks`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/background.md#L1-L11", "start_line": 1, "end_line": 11} {"id": "docs/en/docs/reference/dependencies.md::`Depends()`::L3", "text": "# Doc: docs/en/docs/reference/dependencies.md | Page: Dependencies - `Depends()` and `Security()` | Section: `Depends()`\n## `Depends()`\n\nDependencies are handled mainly with the special function `Depends()` that takes a callable.\n\nHere is the reference for it and its parameters.\n\nYou can import it directly from `fastapi`:\n\n```python\nfrom fastapi import Depends\n```\n\n::: fastapi.Depends", "source_type": "doc", "path": "docs/en/docs/reference/dependencies.md", "symbol": "`Depends()`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/dependencies.md#L3-L16", "start_line": 3, "end_line": 16} {"id": "docs/en/docs/reference/dependencies.md::`Security()`::L17", "text": "# Doc: docs/en/docs/reference/dependencies.md | Page: Dependencies - `Depends()` and `Security()` | Section: `Security()`\n## `Security()`\n\nFor many scenarios, you can handle security (authorization, authentication, etc.) with dependencies, using `Depends()`.\n\nBut when you want to also declare OAuth2 scopes, you can use `Security()` instead of `Depends()`.\n\nYou can import `Security()` directly from `fastapi`:\n\n```python\nfrom fastapi import Security\n```\n\n::: fastapi.Security", "source_type": "doc", "path": "docs/en/docs/reference/dependencies.md", "symbol": "`Security()`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/dependencies.md#L17-L29", "start_line": 17, "end_line": 29} {"id": "docs/en/docs/reference/encoders.md::Encoders - `jsonable_encoder`::L1", "text": "# Doc: docs/en/docs/reference/encoders.md | Page: Encoders - `jsonable_encoder` | Section: Encoders - `jsonable_encoder`\n# Encoders - `jsonable_encoder`\n\n::: fastapi.encoders.jsonable_encoder", "source_type": "doc", "path": "docs/en/docs/reference/encoders.md", "symbol": "Encoders - `jsonable_encoder`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/encoders.md#L1-L3", "start_line": 1, "end_line": 3} {"id": "docs/en/docs/reference/exceptions.md::Exceptions - `HTTPException` and `WebSocketException`::L1", "text": "# Doc: docs/en/docs/reference/exceptions.md | Page: Exceptions - `HTTPException` and `WebSocketException` | Section: Exceptions - `HTTPException` and `WebSocketException`\n# Exceptions - `HTTPException` and `WebSocketException`\n\nThese are the exceptions that you can raise to show errors to the client.\n\nWhen you raise an exception, as would happen with normal Python, the rest of the execution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client.\n\nYou can use:\n\n* `HTTPException`\n* `WebSocketException`\n\nThese exceptions can be imported directly from `fastapi`:\n\n```python\nfrom fastapi import HTTPException, WebSocketException\n```\n\n::: fastapi.HTTPException\n\n::: fastapi.WebSocketException", "source_type": "doc", "path": "docs/en/docs/reference/exceptions.md", "symbol": "Exceptions - `HTTPException` and `WebSocketException`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/exceptions.md#L1-L20", "start_line": 1, "end_line": 20} {"id": "docs/en/docs/reference/fastapi.md::`FastAPI` class::L1", "text": "# Doc: docs/en/docs/reference/fastapi.md | Page: `FastAPI` class | Section: `FastAPI` class\n# `FastAPI` class\n\nHere's the reference information for the `FastAPI` class, with all its parameters, attributes and methods.\n\nYou can import the `FastAPI` class directly from `fastapi`:\n\n```python\nfrom fastapi import FastAPI\n```\n\n::: fastapi.FastAPI\n options:\n members:\n - openapi_version\n - webhooks\n - state\n - dependency_overrides\n - openapi\n - websocket\n - include_router\n - frontend\n - get\n - put\n - post\n - delete\n - options\n - head\n - patch\n - trace\n - on_event\n - middleware\n - exception_handler", "source_type": "doc", "path": "docs/en/docs/reference/fastapi.md", "symbol": "`FastAPI` class", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/fastapi.md#L1-L32", "start_line": 1, "end_line": 32} {"id": "docs/en/docs/reference/httpconnection.md::`HTTPConnection` class::L1", "text": "# Doc: docs/en/docs/reference/httpconnection.md | Page: `HTTPConnection` class | Section: `HTTPConnection` class\n# `HTTPConnection` class\n\nWhen you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.\n\nYou can import it from `fastapi.requests`:\n\n```python\nfrom fastapi.requests import HTTPConnection\n```\n\n::: fastapi.requests.HTTPConnection", "source_type": "doc", "path": "docs/en/docs/reference/httpconnection.md", "symbol": "`HTTPConnection` class", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/httpconnection.md#L1-L11", "start_line": 1, "end_line": 11} {"id": "docs/en/docs/reference/index.md::Reference::L1", "text": "# Doc: docs/en/docs/reference/index.md | Page: Reference | Section: Reference\n# Reference\n\nHere's the reference or code API, the classes, functions, parameters, attributes, and\nall the FastAPI parts you can use in your applications.\n\nIf you want to **learn FastAPI** you are much better off reading the\n[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/).", "source_type": "doc", "path": "docs/en/docs/reference/index.md", "symbol": "Reference", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/index.md#L1-L7", "start_line": 1, "end_line": 7} {"id": "docs/en/docs/reference/middleware.md::Middleware::L1", "text": "# Doc: docs/en/docs/reference/middleware.md | Page: Middleware | Section: Middleware\n# Middleware\n\nThere are several middlewares available provided by Starlette directly.\n\nRead more about them in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/).\n\n::: fastapi.middleware.cors.CORSMiddleware\n\nIt can be imported from `fastapi`:\n\n```python\nfrom fastapi.middleware.cors import CORSMiddleware\n```\n\n::: fastapi.middleware.gzip.GZipMiddleware\n\nIt can be imported from `fastapi`:\n\n```python\nfrom fastapi.middleware.gzip import GZipMiddleware\n```\n\n::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware\n\nIt can be imported from `fastapi`:\n\n```python\nfrom fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware\n```\n\n::: fastapi.middleware.trustedhost.TrustedHostMiddleware\n\nIt can be imported from `fastapi`:\n\n```python\nfrom fastapi.middleware.trustedhost import TrustedHostMiddleware\n```", "source_type": "doc", "path": "docs/en/docs/reference/middleware.md", "symbol": "Middleware", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/middleware.md#L1-L37", "start_line": 1, "end_line": 37} {"id": "docs/en/docs/reference/openapi/docs.md::OpenAPI `docs`::L1", "text": "# Doc: docs/en/docs/reference/openapi/docs.md | Page: OpenAPI `docs` | Section: OpenAPI `docs`\n# OpenAPI `docs`\n\nUtilities to handle OpenAPI automatic UI documentation, including Swagger UI (by default at `/docs`) and ReDoc (by default at `/redoc`).\n\n::: fastapi.openapi.docs.get_swagger_ui_html\n\n::: fastapi.openapi.docs.get_redoc_html\n\n::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html\n\n::: fastapi.openapi.docs.swagger_ui_default_parameters", "source_type": "doc", "path": "docs/en/docs/reference/openapi/docs.md", "symbol": "OpenAPI `docs`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/openapi/docs.md#L1-L11", "start_line": 1, "end_line": 11} {"id": "docs/en/docs/reference/openapi/index.md::OpenAPI::L1", "text": "# Doc: docs/en/docs/reference/openapi/index.md | Page: OpenAPI | Section: OpenAPI\n# OpenAPI\n\nThere are several utilities to handle OpenAPI.\n\nYou normally don't need to use them unless you have a specific advanced use case that requires it.", "source_type": "doc", "path": "docs/en/docs/reference/openapi/index.md", "symbol": "OpenAPI", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/openapi/index.md#L1-L5", "start_line": 1, "end_line": 5} {"id": "docs/en/docs/reference/openapi/models.md::OpenAPI `models`::L1", "text": "# Doc: docs/en/docs/reference/openapi/models.md | Page: OpenAPI `models` | Section: OpenAPI `models`\n# OpenAPI `models`\n\nOpenAPI Pydantic models used to generate and validate the generated OpenAPI.\n\n::: fastapi.openapi.models", "source_type": "doc", "path": "docs/en/docs/reference/openapi/models.md", "symbol": "OpenAPI `models`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/openapi/models.md#L1-L5", "start_line": 1, "end_line": 5} {"id": "docs/en/docs/reference/parameters.md::Request Parameters::L1", "text": "# Doc: docs/en/docs/reference/parameters.md | Page: Request Parameters | Section: Request Parameters\n# Request Parameters\n\nHere's the reference information for the request parameters.\n\nThese are the special functions that you can put in *path operation function* parameters or dependency functions with `Annotated` to get data from the request.\n\nIt includes:\n\n* `Query()`\n* `Path()`\n* `Body()`\n* `Cookie()`\n* `Header()`\n* `Form()`\n* `File()`\n\nYou can import them all directly from `fastapi`:\n\n```python\nfrom fastapi import Body, Cookie, File, Form, Header, Path, Query\n```\n\n::: fastapi.Query\n\n::: fastapi.Path\n\n::: fastapi.Body\n\n::: fastapi.Cookie\n\n::: fastapi.Header\n\n::: fastapi.Form\n\n::: fastapi.File", "source_type": "doc", "path": "docs/en/docs/reference/parameters.md", "symbol": "Request Parameters", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/parameters.md#L1-L35", "start_line": 1, "end_line": 35} {"id": "docs/en/docs/reference/request.md::`Request` class::L1", "text": "# Doc: docs/en/docs/reference/request.md | Page: `Request` class | Section: `Request` class\n# `Request` class\n\nYou can declare a parameter in a *path operation function* or dependency to be of type `Request` and then you can access the raw request object directly, without any validation, etc.\n\nRead more about it in the [FastAPI docs about using Request directly](https://fastapi.tiangolo.com/advanced/using-request-directly/)\n\nYou can import it directly from `fastapi`:\n\n```python\nfrom fastapi import Request\n```\n\n/// tip\n\nWhen you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.\n\n///\n\n::: fastapi.Request", "source_type": "doc", "path": "docs/en/docs/reference/request.md", "symbol": "`Request` class", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/request.md#L1-L19", "start_line": 1, "end_line": 19} {"id": "docs/en/docs/reference/response.md::`Response` class::L1", "text": "# Doc: docs/en/docs/reference/response.md | Page: `Response` class | Section: `Response` class\n# `Response` class\n\nYou can declare a parameter in a *path operation function* or dependency to be of type `Response` and then you can set data for the response like headers or cookies.\n\nYou can also use it directly to create an instance of it and return it from your *path operations*.\n\nRead more about it in the [FastAPI docs about returning a custom Response](https://fastapi.tiangolo.com/advanced/response-directly/#returning-a-custom-response)\n\nYou can import it directly from `fastapi`:\n\n```python\nfrom fastapi import Response\n```\n\n::: fastapi.Response", "source_type": "doc", "path": "docs/en/docs/reference/response.md", "symbol": "`Response` class", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/response.md#L1-L15", "start_line": 1, "end_line": 15} {"id": "docs/en/docs/reference/responses.md::Custom Response Classes - File, HTML, Redirect, Streaming, etc.::L1", "text": "# Doc: docs/en/docs/reference/responses.md | Page: Custom Response Classes - File, HTML, Redirect, Streaming, etc. | Section: Custom Response Classes - File, HTML, Redirect, Streaming, etc.\n# Custom Response Classes - File, HTML, Redirect, Streaming, etc.\n\nThere are several custom response classes you can use to create an instance and return them directly from your *path operations*.\n\nRead more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/).\n\nYou can import them directly from `fastapi.responses`:\n\n```python\nfrom fastapi.responses import (\n FileResponse,\n HTMLResponse,\n JSONResponse,\n ORJSONResponse,\n PlainTextResponse,\n RedirectResponse,\n Response,\n StreamingResponse,\n UJSONResponse,\n)\n```", "source_type": "doc", "path": "docs/en/docs/reference/responses.md", "symbol": "Custom Response Classes - File, HTML, Redirect, Streaming, etc.", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/responses.md#L1-L22", "start_line": 1, "end_line": 22} {"id": "docs/en/docs/reference/responses.md::FastAPI Responses::L23", "text": "# Doc: docs/en/docs/reference/responses.md | Page: Custom Response Classes - File, HTML, Redirect, Streaming, etc. | Section: FastAPI Responses\n## FastAPI Responses\n\nThere were a couple of custom FastAPI response classes that were intended to optimize JSON performance.\n\nHowever, they are now deprecated as you will now get better performance by using a [Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/).\n\nThat way, Pydantic will serialize the data into JSON bytes on the Rust side, which will achieve better performance than these custom JSON responses.\n\nRead more about it in [Custom Response - HTML, Stream, File, others - `orjson` or Response Model](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model).\n\n::: fastapi.responses.UJSONResponse\n options:\n members:\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie\n\n::: fastapi.responses.ORJSONResponse\n options:\n members:\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie", "source_type": "doc", "path": "docs/en/docs/reference/responses.md", "symbol": "FastAPI Responses", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/responses.md#L23-L62", "start_line": 23, "end_line": 62} {"id": "docs/en/docs/reference/responses.md::Starlette Responses::L63", "text": "# Doc: docs/en/docs/reference/responses.md | Page: Custom Response Classes - File, HTML, Redirect, Streaming, etc. | Section: Starlette Responses\n## Starlette Responses\n\nYou can read more about all of them in the [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/) and in the [Starlette docs about Responses](https://starlette.dev/responses/).\n\n::: fastapi.responses.FileResponse\n options:\n members:\n - chunk_size\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie\n\n::: fastapi.responses.HTMLResponse\n options:\n members:\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie\n\n::: fastapi.responses.JSONResponse\n options:\n members:\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie\n\n::: fastapi.responses.PlainTextResponse\n options:\n members:\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie\n\n::: fastapi.responses.RedirectResponse\n options:\n members:\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie\n\n::: fastapi.responses.Response\n options:\n members:\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie\n\n::: fastapi.responses.StreamingResponse\n options:\n members:\n - body_iterator\n - charset\n - status_code\n - media_type\n - body\n - background\n - raw_headers\n - render\n - init_headers\n - headers\n - set_cookie\n - delete_cookie", "source_type": "doc", "path": "docs/en/docs/reference/responses.md", "symbol": "Starlette Responses", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/responses.md#L63-L172", "start_line": 63, "end_line": 172} {"id": "docs/en/docs/reference/security/index.md::Security Tools::L1", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: Security Tools\n# Security Tools\n\nWhen you need to declare dependencies with OAuth2 scopes you use `Security()`.\n\nBut you still need to define what is the dependable, the callable that you pass as a parameter to `Depends()` or `Security()`.\n\nThere are multiple tools that you can use to create those dependables, and they get integrated into OpenAPI so they are shown in the automatic docs UI, they can be used by automatically generated clients and SDKs, etc.\n\nYou can import them from `fastapi.security`:\n\n```python\nfrom fastapi.security import (\n APIKeyCookie,\n APIKeyHeader,\n APIKeyQuery,\n HTTPAuthorizationCredentials,\n HTTPBasic,\n HTTPBasicCredentials,\n HTTPBearer,\n HTTPDigest,\n OAuth2,\n OAuth2AuthorizationCodeBearer,\n OAuth2PasswordBearer,\n OAuth2PasswordRequestForm,\n OAuth2PasswordRequestFormStrict,\n OpenIdConnect,\n SecurityScopes,\n)\n```\n\nRead more about them in the [FastAPI docs about Security](https://fastapi.tiangolo.com/tutorial/security/).", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "Security Tools", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L1-L32", "start_line": 1, "end_line": 32} {"id": "docs/en/docs/reference/security/index.md::API Key Security Schemes::L33", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: API Key Security Schemes\n## API Key Security Schemes\n\n::: fastapi.security.APIKeyCookie\n\n::: fastapi.security.APIKeyHeader\n\n::: fastapi.security.APIKeyQuery", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "API Key Security Schemes", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L33-L40", "start_line": 33, "end_line": 40} {"id": "docs/en/docs/reference/security/index.md::HTTP Authentication Schemes::L41", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: HTTP Authentication Schemes\n## HTTP Authentication Schemes\n\n::: fastapi.security.HTTPBasic\n\n::: fastapi.security.HTTPBearer\n\n::: fastapi.security.HTTPDigest", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "HTTP Authentication Schemes", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L41-L48", "start_line": 41, "end_line": 48} {"id": "docs/en/docs/reference/security/index.md::HTTP Credentials::L49", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: HTTP Credentials\n## HTTP Credentials\n\n::: fastapi.security.HTTPAuthorizationCredentials\n\n::: fastapi.security.HTTPBasicCredentials", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "HTTP Credentials", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L49-L54", "start_line": 49, "end_line": 54} {"id": "docs/en/docs/reference/security/index.md::OAuth2 Authentication::L55", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OAuth2 Authentication\n## OAuth2 Authentication\n\n::: fastapi.security.OAuth2\n\n::: fastapi.security.OAuth2AuthorizationCodeBearer\n\n::: fastapi.security.OAuth2PasswordBearer", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "OAuth2 Authentication", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L55-L62", "start_line": 55, "end_line": 62} {"id": "docs/en/docs/reference/security/index.md::OAuth2 Password Form::L63", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OAuth2 Password Form\n## OAuth2 Password Form\n\n::: fastapi.security.OAuth2PasswordRequestForm\n\n::: fastapi.security.OAuth2PasswordRequestFormStrict", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "OAuth2 Password Form", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L63-L68", "start_line": 63, "end_line": 68} {"id": "docs/en/docs/reference/security/index.md::OAuth2 Security Scopes in Dependencies::L69", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OAuth2 Security Scopes in Dependencies\n## OAuth2 Security Scopes in Dependencies\n\n::: fastapi.security.SecurityScopes", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "OAuth2 Security Scopes in Dependencies", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L69-L72", "start_line": 69, "end_line": 72} {"id": "docs/en/docs/reference/security/index.md::OpenID Connect::L73", "text": "# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OpenID Connect\n## OpenID Connect\n\n::: fastapi.security.OpenIdConnect", "source_type": "doc", "path": "docs/en/docs/reference/security/index.md", "symbol": "OpenID Connect", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/security/index.md#L73-L75", "start_line": 73, "end_line": 75} {"id": "docs/en/docs/reference/staticfiles.md::Static Files - `StaticFiles`::L1", "text": "# Doc: docs/en/docs/reference/staticfiles.md | Page: Static Files - `StaticFiles` | Section: Static Files - `StaticFiles`\n# Static Files - `StaticFiles`\n\nYou can use the `StaticFiles` class to serve static files, like JavaScript, CSS, images, etc.\n\nRead more about it in the [FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/).\n\nYou can import it directly from `fastapi.staticfiles`:\n\n```python\nfrom fastapi.staticfiles import StaticFiles\n```\n\n::: fastapi.staticfiles.StaticFiles", "source_type": "doc", "path": "docs/en/docs/reference/staticfiles.md", "symbol": "Static Files - `StaticFiles`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/staticfiles.md#L1-L13", "start_line": 1, "end_line": 13} {"id": "docs/en/docs/reference/status.md::Status Codes::L1", "text": "# Doc: docs/en/docs/reference/status.md | Page: Status Codes | Section: Status Codes\n# Status Codes\n\nYou can import the `status` module from `fastapi`:\n\n```python\nfrom fastapi import status\n```\n\n`status` is provided directly by Starlette.\n\nIt contains a group of named constants (variables) with integer status codes.\n\nFor example:\n\n* 200: `status.HTTP_200_OK`\n* 403: `status.HTTP_403_FORBIDDEN`\n* etc.\n\nIt can be convenient to quickly access HTTP (and WebSocket) status codes in your app, using autocompletion for the name without having to memorize the integer status codes.\n\nRead more about it in the [FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).", "source_type": "doc", "path": "docs/en/docs/reference/status.md", "symbol": "Status Codes", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/status.md#L1-L22", "start_line": 1, "end_line": 22} {"id": "docs/en/docs/reference/status.md::Example::L23", "text": "# Doc: docs/en/docs/reference/status.md | Page: Status Codes | Section: Example\n## Example\n\n```python\nfrom fastapi import FastAPI, status\n\napp = FastAPI()\n\n\n@app.get(\"/items/\", status_code=status.HTTP_418_IM_A_TEAPOT)\ndef read_items():\n return [{\"name\": \"Plumbus\"}, {\"name\": \"Portal Gun\"}]\n```\n\n::: fastapi.status", "source_type": "doc", "path": "docs/en/docs/reference/status.md", "symbol": "Example", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/status.md#L23-L36", "start_line": 23, "end_line": 36} {"id": "docs/en/docs/reference/templating.md::Templating - `Jinja2Templates`::L1", "text": "# Doc: docs/en/docs/reference/templating.md | Page: Templating - `Jinja2Templates` | Section: Templating - `Jinja2Templates`\n# Templating - `Jinja2Templates`\n\nYou can use the `Jinja2Templates` class to render Jinja templates.\n\nRead more about it in the [FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/).\n\nYou can import it directly from `fastapi.templating`:\n\n```python\nfrom fastapi.templating import Jinja2Templates\n```\n\n::: fastapi.templating.Jinja2Templates", "source_type": "doc", "path": "docs/en/docs/reference/templating.md", "symbol": "Templating - `Jinja2Templates`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/templating.md#L1-L13", "start_line": 1, "end_line": 13} {"id": "docs/en/docs/reference/testclient.md::Test Client - `TestClient`::L1", "text": "# Doc: docs/en/docs/reference/testclient.md | Page: Test Client - `TestClient` | Section: Test Client - `TestClient`\n# Test Client - `TestClient`\n\nYou can use the `TestClient` class to test FastAPI applications without creating an actual HTTP and socket connection, just communicating directly with the FastAPI code.\n\nRead more about it in the [FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/).\n\nYou can import it directly from `fastapi.testclient`:\n\n```python\nfrom fastapi.testclient import TestClient\n```\n\n::: fastapi.testclient.TestClient", "source_type": "doc", "path": "docs/en/docs/reference/testclient.md", "symbol": "Test Client - `TestClient`", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/testclient.md#L1-L13", "start_line": 1, "end_line": 13} {"id": "docs/en/docs/reference/uploadfile.md::`UploadFile` class::L1", "text": "# Doc: docs/en/docs/reference/uploadfile.md | Page: `UploadFile` class | Section: `UploadFile` class\n# `UploadFile` class\n\nYou can define *path operation function* parameters to be of the type `UploadFile` to receive files from the request.\n\nYou can import it directly from `fastapi`:\n\n```python\nfrom fastapi import UploadFile\n```\n\n::: fastapi.UploadFile\n options:\n members:\n - file\n - filename\n - size\n - headers\n - content_type\n - read\n - write\n - seek\n - close", "source_type": "doc", "path": "docs/en/docs/reference/uploadfile.md", "symbol": "`UploadFile` class", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/uploadfile.md#L1-L22", "start_line": 1, "end_line": 22} {"id": "docs/en/docs/reference/websockets.md::WebSockets::L1", "text": "# Doc: docs/en/docs/reference/websockets.md | Page: WebSockets | Section: WebSockets\n# WebSockets\n\nWhen defining WebSockets, you normally declare a parameter of type `WebSocket` and with it you can read data from the client and send data to it.\n\nRead more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/)\n\nIt is provided directly by Starlette, but you can import it from `fastapi`:\n\n```python\nfrom fastapi import WebSocket\n```\n\n/// tip\n\nWhen you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.\n\n///\n\n::: fastapi.WebSocket\n options:\n members:\n - scope\n - app\n - url\n - base_url\n - headers\n - query_params\n - path_params\n - cookies\n - client\n - state\n - url_for\n - client_state\n - application_state\n - receive\n - send\n - accept\n - receive_text\n - receive_bytes\n - receive_json\n - iter_text\n - iter_bytes\n - iter_json\n - send_text\n - send_bytes\n - send_json\n - close", "source_type": "doc", "path": "docs/en/docs/reference/websockets.md", "symbol": "WebSockets", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/websockets.md#L1-L48", "start_line": 1, "end_line": 48} {"id": "docs/en/docs/reference/websockets.md::WebSockets - additional classes::L49", "text": "# Doc: docs/en/docs/reference/websockets.md | Page: WebSockets | Section: WebSockets - additional classes\n## WebSockets - additional classes\n\nAdditional classes for handling WebSockets.\n\nProvided directly by Starlette, but you can import them from `fastapi`:\n\n```python\nfrom fastapi.websockets import WebSocketDisconnect, WebSocketState\n```\n\n::: fastapi.websockets.WebSocketDisconnect\n\nWhen a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch it.\n\nYou can import it directly from `fastapi`:\n\n```python\nfrom fastapi import WebSocketDisconnect\n```\n\nRead more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/#handling-disconnections-and-multiple-clients)\n\n::: fastapi.websockets.WebSocketState\n\n`WebSocketState` is an enumeration of the possible states of a WebSocket connection.", "source_type": "doc", "path": "docs/en/docs/reference/websockets.md", "symbol": "WebSockets - additional classes", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/reference/websockets.md#L49-L73", "start_line": 49, "end_line": 73} {"id": "docs/en/docs/resources/index.md::Resources { #resources }::L1", "text": "# Doc: docs/en/docs/resources/index.md | Page: Resources { #resources } | Section: Resources { #resources }\n# Resources { #resources }\n\nAdditional resources, external links, and more. ✈️", "source_type": "doc", "path": "docs/en/docs/resources/index.md", "symbol": "Resources { #resources }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/resources/index.md#L1-L3", "start_line": 1, "end_line": 3} {"id": "docs/en/docs/translation-banner.md::docs/en/docs/translation-banner.md::L1", "text": "# Doc: docs/en/docs/translation-banner.md | Page: docs/en/docs/translation-banner.md | Section: docs/en/docs/translation-banner.md\n/// details | 🌐 Translation by AI and humans\n\nThis translation was made by AI guided by humans. 🤝\n\nIt could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖\n\nYou can improve this translation by [helping us guide the AI LLM better](https://fastapi.tiangolo.com/contributing/#translations).\n\n[English version](ENGLISH_VERSION_URL)\n\n///", "source_type": "doc", "path": "docs/en/docs/translation-banner.md", "symbol": "docs/en/docs/translation-banner.md", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/translation-banner.md#L1-L11", "start_line": 1, "end_line": 11} {"id": "docs/en/docs/translations.md::Translations::L1", "text": "# Doc: docs/en/docs/translations.md | Page: Translations | Section: Translations\n# Translations\n\nTranslation pull requests are made by LLMs guided with prompts designed by the FastAPI team together with the community of native speakers for each supported language.", "source_type": "doc", "path": "docs/en/docs/translations.md", "symbol": "Translations", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/translations.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/translations.md::LLM Prompt per Language::L5", "text": "# Doc: docs/en/docs/translations.md | Page: Translations | Section: LLM Prompt per Language\n## LLM Prompt per Language\n\nEach language has a directory: [https://github.com/fastapi/fastapi/tree/master/docs](https://github.com/fastapi/fastapi/tree/master/docs), in it you can see a file `llm-prompt.md` with the prompt specific for that language.\n\nFor example, for Spanish, the prompt is at: [`docs/es/llm-prompt.md`](https://github.com/fastapi/fastapi/blob/master/docs/es/llm-prompt.md).\n\nIf you see mistakes in your language, you can make suggestions to the prompt in that file for your language, and request the specific pages you would like to re-generate after the changes.\n\nPRs with suggestions to the language-specific LLM prompt require approval from at least one native speaker. Your help here is very much appreciated!", "source_type": "doc", "path": "docs/en/docs/translations.md", "symbol": "LLM Prompt per Language", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/translations.md#L5-L14", "start_line": 5, "end_line": 14} {"id": "docs/en/docs/translations.md::Request a New Language::L15", "text": "# Doc: docs/en/docs/translations.md | Page: Translations | Section: Request a New Language\n## Request a New Language\n\nLet's say that you want to request translations for a language that is not yet translated, not even some pages. For example, Latin.\n\n* The first step would be for you to find 2 other people who would be willing to be reviewing translation PRs for that language with you.\n* Once there are at least 3 people that would be willing to commit to help maintain that language, you can continue the next steps.\n* Create a new discussion following the template.\n* Tag the other 2 people that will help with the language, and ask them to confirm in the comments that they will help.\n\nOnce there are several people in the discussion, the FastAPI team can evaluate it and can make it an official translation.\n\nThen the docs will be automatically translated using LLMs, and the team of native speakers can review the translation, and help tweak the LLM prompts.\n\nOnce there's a new translation, for example if docs are updated or there's a new section, there will be a comment in the same discussion with the link to the new translation to review.", "source_type": "doc", "path": "docs/en/docs/translations.md", "symbol": "Request a New Language", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/translations.md#L15-L28", "start_line": 15, "end_line": 28} {"id": "docs/en/docs/tutorial/background-tasks.md::Background Tasks { #background-tasks }::L1", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Background Tasks { #background-tasks }\n# Background Tasks { #background-tasks }\n\nYou can define background tasks to be run *after* returning a response.\n\nThis is useful for operations that need to happen after a request, but that the client doesn't really have to be waiting for the operation to complete before receiving the response.\n\nThis includes, for example:\n\n* Email notifications sent after performing an action:\n * As connecting to an email server and sending an email tends to be \"slow\" (several seconds), you can return the response right away and send the email notification in the background.\n* Processing data:\n * For example, let's say you receive a file that must go through a slow process, you can return a response of \"Accepted\" (HTTP 202) and process the file in the background.", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Background Tasks { #background-tasks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L1-L13", "start_line": 1, "end_line": 13} {"id": "docs/en/docs/tutorial/background-tasks.md::Using `BackgroundTasks` { #using-backgroundtasks }::L14", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Using `BackgroundTasks` { #using-backgroundtasks }\n## Using `BackgroundTasks` { #using-backgroundtasks }\n\nFirst, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:\n\n{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}\n\n**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Using `BackgroundTasks` { #using-backgroundtasks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L14-L21", "start_line": 14, "end_line": 21} {"id": "docs/en/docs/tutorial/background-tasks.md::Create a task function { #create-a-task-function }::L22", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Create a task function { #create-a-task-function }\n## Create a task function { #create-a-task-function }\n\nCreate a function to be run as the background task.\n\nIt is just a standard function that can receive parameters.\n\nIt can be an `async def` or normal `def` function, **FastAPI** will know how to handle it correctly.\n\nIn this case, the task function will write to a file (simulating sending an email).\n\nAnd as the write operation doesn't use `async` and `await`, we define the function with normal `def`:\n\n{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Create a task function { #create-a-task-function }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L22-L35", "start_line": 22, "end_line": 35} {"id": "docs/en/docs/tutorial/background-tasks.md::Add the background task { #add-the-background-task }::L36", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Add the background task { #add-the-background-task }\n## Add the background task { #add-the-background-task }\n\nInside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:\n\n{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}\n\n`.add_task()` receives as arguments:\n\n* A task function to be run in the background (`write_notification`).\n* Any sequence of arguments that should be passed to the task function in order (`email`).\n* Any keyword arguments that should be passed to the task function (`message=\"some notification\"`).", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Add the background task { #add-the-background-task }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L36-L47", "start_line": 36, "end_line": 47} {"id": "docs/en/docs/tutorial/background-tasks.md::Dependency Injection { #dependency-injection }::L48", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Dependency Injection { #dependency-injection }\n## Dependency Injection { #dependency-injection }\n\nUsing `BackgroundTasks` also works with the dependency injection system, you can declare a parameter of type `BackgroundTasks` at multiple levels: in a *path operation function*, in a dependency (dependable), in a sub-dependency, etc.\n\n**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards:\n\n\n{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}\n\n\nIn this example, the messages will be written to the `log.txt` file *after* the response is sent.\n\nIf there was a query in the request, it will be written to the log in a background task.\n\nAnd then another background task generated at the *path operation function* will write a message using the `email` path parameter.", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Dependency Injection { #dependency-injection }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L48-L63", "start_line": 48, "end_line": 63} {"id": "docs/en/docs/tutorial/background-tasks.md::Technical Details { #technical-details }::L64", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Technical Details { #technical-details }\n## Technical Details { #technical-details }\n\nThe class `BackgroundTasks` comes directly from [`starlette.background`](https://www.starlette.dev/background/).\n\nIt is imported/included directly into FastAPI so that you can import it from `fastapi` and avoid accidentally importing the alternative `BackgroundTask` (without the `s` at the end) from `starlette.background`.\n\nBy only using `BackgroundTasks` (and not `BackgroundTask`), it's then possible to use it as a *path operation function* parameter and have **FastAPI** handle the rest for you, just like when using the `Request` object directly.\n\nIt's still possible to use `BackgroundTask` alone in FastAPI, but you have to create the object in your code and return a Starlette `Response` including it.\n\nYou can see more details in [Starlette's official docs for Background Tasks](https://www.starlette.dev/background/).", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Technical Details { #technical-details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L64-L75", "start_line": 64, "end_line": 75} {"id": "docs/en/docs/tutorial/background-tasks.md::Caveat { #caveat }::L76", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Caveat { #caveat }\n## Caveat { #caveat }\n\nIf you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like [Celery](https://docs.celeryq.dev).\n\nThey tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers.\n\nBut if you need to access variables and objects from the same **FastAPI** app, or you need to perform small background tasks (like sending an email notification), you can simply just use `BackgroundTasks`.", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Caveat { #caveat }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L76-L83", "start_line": 76, "end_line": 83} {"id": "docs/en/docs/tutorial/background-tasks.md::Recap { #recap }::L84", "text": "# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Recap { #recap }\n## Recap { #recap }\n\nImport and use `BackgroundTasks` with parameters in *path operation functions* and dependencies to add background tasks.", "source_type": "doc", "path": "docs/en/docs/tutorial/background-tasks.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/background-tasks.md#L84-L86", "start_line": 84, "end_line": 86} {"id": "docs/en/docs/tutorial/bigger-applications.md::Bigger Applications - Multiple Files { #bigger-applications-multiple-files }::L1", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Bigger Applications - Multiple Files { #bigger-applications-multiple-files }\n# Bigger Applications - Multiple Files { #bigger-applications-multiple-files }\n\nIf you are building an application or a web API, it's rarely the case that you can put everything in a single file.\n\n**FastAPI** provides a convenience tool to structure your application while keeping all the flexibility.\n\n/// note\n\nIf you come from Flask, this would be the equivalent of Flask's Blueprints.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "Bigger Applications - Multiple Files { #bigger-applications-multiple-files }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/tutorial/bigger-applications.md::An example file structure { #an-example-file-structure }::L13", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: An example file structure { #an-example-file-structure }\n## An example file structure { #an-example-file-structure }\n\nLet's say you have a file structure like this:\n\n```\n.\n├── app\n│ ├── __init__.py\n│ ├── main.py\n│ ├── dependencies.py\n│ └── routers\n│ │ ├── __init__.py\n│ │ ├── items.py\n│ │ └── users.py\n│ └── internal\n│ ├── __init__.py\n│ └── admin.py\n```\n\n/// tip\n\nThere are several `__init__.py` files: one in each directory or subdirectory.\n\nThis is what allows importing code from one file into another.\n\nFor example, in `app/main.py` you could have a line like:\n\n```\nfrom app.routers import items\n```\n\n///\n\n* The `app` directory contains everything. And it has an empty file `app/__init__.py`, so it is a \"Python package\" (a collection of \"Python modules\"): `app`.\n* It contains an `app/main.py` file. As it is inside a Python package (a directory with a file `__init__.py`), it is a \"module\" of that package: `app.main`.\n* There's also an `app/dependencies.py` file, just like `app/main.py`, it is a \"module\": `app.dependencies`.\n* There's a subdirectory `app/routers/` with another file `__init__.py`, so it's a \"Python subpackage\": `app.routers`.\n* The file `app/routers/items.py` is inside a package, `app/routers/`, so, it's a submodule: `app.routers.items`.\n* The same with `app/routers/users.py`, it's another submodule: `app.routers.users`.\n* There's also a subdirectory `app/internal/` with another file `__init__.py`, so it's another \"Python subpackage\": `app.internal`.\n* And the file `app/internal/admin.py` is another submodule: `app.internal.admin`.\n\n\n\nThe same file structure with comments:\n\n```bash\n.\n├── app # \"app\" is a Python package\n│   ├── __init__.py # this file makes \"app\" a \"Python package\"\n│   ├── main.py # \"main\" module, e.g. import app.main\n│   ├── dependencies.py # \"dependencies\" module, e.g. import app.dependencies\n│   └── routers # \"routers\" is a \"Python subpackage\"\n│   │ ├── __init__.py # makes \"routers\" a \"Python subpackage\"\n│   │ ├── items.py # \"items\" submodule, e.g. import app.routers.items\n│   │ └── users.py # \"users\" submodule, e.g. import app.routers.users\n│   └── internal # \"internal\" is a \"Python subpackage\"\n│   ├── __init__.py # makes \"internal\" a \"Python subpackage\"\n│   └── admin.py # \"admin\" submodule, e.g. import app.internal.admin\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "An example file structure { #an-example-file-structure }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L13-L73", "start_line": 13, "end_line": 73} {"id": "docs/en/docs/tutorial/bigger-applications.md::`APIRouter` { #apirouter }::L74", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: `APIRouter` { #apirouter }\n## `APIRouter` { #apirouter }\n\nLet's say the file dedicated to handling just users is the submodule at `/app/routers/users.py`.\n\nYou want to have the *path operations* related to your users separated from the rest of the code, to keep it organized.\n\nBut it's still part of the same **FastAPI** application/web API (it's part of the same \"Python Package\").\n\nYou can create the *path operations* for that module using `APIRouter`.\n\n### Import `APIRouter` { #import-apirouter }\n\nYou import it and create an \"instance\" the same way you would with the class `FastAPI`:\n\n{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title[\"app/routers/users.py\"] *}\n\n### *Path operations* with `APIRouter` { #path-operations-with-apirouter }\n\nAnd then you use it to declare your *path operations*.\n\nUse it the same way you would use the `FastAPI` class:\n\n{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title[\"app/routers/users.py\"] *}\n\nYou can think of `APIRouter` as a \"mini `FastAPI`\" class.\n\nAll the same options are supported.\n\nAll the same `parameters`, `responses`, `dependencies`, `tags`, etc.\n\n/// tip\n\nIn this example, the variable is called `router`, but you can name it however you want.\n\n///\n\nWe are going to include this `APIRouter` in the main `FastAPI` app, but first, let's check the dependencies and another `APIRouter`.", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "`APIRouter` { #apirouter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L74-L111", "start_line": 74, "end_line": 111} {"id": "docs/en/docs/tutorial/bigger-applications.md::Dependencies { #dependencies }::L112", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Dependencies { #dependencies }\n## Dependencies { #dependencies }\n\nWe see that we are going to need some dependencies used in several places of the application.\n\nSo we put them in their own `dependencies` module (`app/dependencies.py`).\n\nWe will now use a simple dependency to read a custom `X-Token` header:\n\n{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title[\"app/dependencies.py\"] *}\n\n/// tip\n\nWe are using an invented header to simplify this example.\n\nBut in real cases you will get better results using the integrated [Security utilities](security/index.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "Dependencies { #dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L112-L129", "start_line": 112, "end_line": 129} {"id": "docs/en/docs/tutorial/bigger-applications.md::Another module with `APIRouter` { #another-module-with-apirouter }::L130", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Another module with `APIRouter` { #another-module-with-apirouter }\n## Another module with `APIRouter` { #another-module-with-apirouter }\n\nLet's say you also have the endpoints dedicated to handling \"items\" from your application in the module at `app/routers/items.py`.\n\nYou have *path operations* for:\n\n* `/items/`\n* `/items/{item_id}`\n\nIt's all the same structure as with `app/routers/users.py`.\n\nBut we want to be smarter and simplify the code a bit.\n\nWe know all the *path operations* in this module have the same:\n\n* Path `prefix`: `/items`.\n* `tags`: (just one tag: `items`).\n* Extra `responses`.\n* `dependencies`: they all need that `X-Token` dependency we created.\n\nSo, instead of adding all that to each *path operation*, we can add it to the `APIRouter`.\n\n{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title[\"app/routers/items.py\"] *}\n\nAs the path of each *path operation* has to start with `/`, like in:\n\n```Python hl_lines=\"1\"\n@router.get(\"/{item_id}\")\nasync def read_item(item_id: str):\n ...\n```\n\n...the prefix must not include a final `/`.\n\nSo, the prefix in this case is `/items`.\n\nWe can also add a list of `tags` and extra `responses` that will be applied to all the *path operations* included in this router.\n\nAnd we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them.\n\n/// tip\n\nNote that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md), no value will be passed to your *path operation function*.\n\n///\n\nThe end result is that the item paths are now:\n\n* `/items/`\n* `/items/{item_id}`\n\n...as we intended.\n\n* They will be marked with a list of tags that contain a single string `\"items\"`.\n * These \"tags\" are especially useful for the automatic interactive documentation systems (using OpenAPI).\n* All of them will include the predefined `responses`.\n* All these *path operations* will have the list of `dependencies` evaluated/executed before them.\n * If you also declare dependencies in a specific *path operation*, **they will be executed too**.\n * The router dependencies are executed first, then the [`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md), and then the normal parameter dependencies.\n * You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md).\n\n/// tip\n\nHaving `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them.\n\n///\n\n/// tip\n\nThe `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.\n\n///\n\n### Import the dependencies { #import-the-dependencies }\n\nThis code lives in the module `app.routers.items`, the file `app/routers/items.py`.\n\nAnd we need to get the dependency function from the module `app.dependencies`, the file `app/dependencies.py`.\n\nSo we use a relative import with `..` for the dependencies:\n\n{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title[\"app/routers/items.py\"] *}\n\n#### How relative imports work { #how-relative-imports-work }\n\n/// tip\n\nIf you know perfectly how imports work, continue to the next section below.\n\n///\n\nA single dot `.`, like in:\n\n```Python\nfrom .dependencies import get_token_header\n```\n\nwould mean:\n\n* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...\n* find the module `dependencies` (an imaginary file at `app/routers/dependencies.py`)...\n* and from it, import the function `get_token_header`.\n\nBut that file doesn't exist, our dependencies are in a file at `app/dependencies.py`.\n\nRemember what our app/file structure looks like:\n\n\n\n---\n\nThe two dots `..`, like in:\n\n```Python\nfrom ..dependencies import get_token_header\n```\n\nmean:\n\n* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...\n* go to the parent package (the directory `app/`)...\n* and in there, find the module `dependencies` (the file at `app/dependencies.py`)...\n* and from it, import the function `get_token_header`.\n\nThat works correctly! 🎉\n\n---\n\nThe same way, if we had used three dots `...`, like in:\n\n```Python\nfrom ...dependencies import get_token_header\n```\n\nthat would mean:\n\n* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...\n* go to the parent package (the directory `app/`)...\n* then go to the parent of that package (there's no parent package, `app` is the top level 😱)...\n* and in there, find the module `dependencies` (the file at `app/dependencies.py`)...\n* and from it, import the function `get_token_header`.\n\nThat would refer to some package above `app/`, with its own file `__init__.py`, etc. But we don't have that. So, that would throw an error in our example. 🚨\n\nBut now you know how it works, so you can use relative imports in your own apps no matter how complex they are. 🤓\n\n### Add some custom `tags`, `responses`, and `dependencies` { #add-some-custom-tags-responses-and-dependencies }\n\nWe are not adding the prefix `/items` nor the `tags=[\"items\"]` to each *path operation* because we added them to the `APIRouter`.\n\nBut we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*:\n\n{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title[\"app/routers/items.py\"] *}\n\n/// tip\n\nThis last path operation will have the combination of tags: `[\"items\", \"custom\"]`.\n\nAnd it will also have both responses in the documentation, one for `404` and one for `403`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "Another module with `APIRouter` { #another-module-with-apirouter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L130-L291", "start_line": 130, "end_line": 291} {"id": "docs/en/docs/tutorial/bigger-applications.md::The main `FastAPI` { #the-main-fastapi }::L292", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: The main `FastAPI` { #the-main-fastapi }\n## The main `FastAPI` { #the-main-fastapi }\n\nNow, let's see the module at `app/main.py`.\n\nHere's where you import and use the class `FastAPI`.\n\nThis will be the main file in your application that ties everything together.\n\nAnd as most of your logic will now live in its own specific module, the main file will be quite simple.\n\n### Import `FastAPI` { #import-fastapi }\n\nYou import and create a `FastAPI` class as normally.\n\nAnd we can even declare [global dependencies](dependencies/global-dependencies.md) that will be combined with the dependencies for each `APIRouter`:\n\n{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title[\"app/main.py\"] *}\n\n### Import the `APIRouter` { #import-the-apirouter }\n\nNow we import the other submodules that have `APIRouter`s:\n\n{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title[\"app/main.py\"] *}\n\nAs the files `app/routers/users.py` and `app/routers/items.py` are submodules that are part of the same Python package `app`, we can use a single dot `.` to import them using \"relative imports\".\n\n### How the importing works { #how-the-importing-works }\n\nThe section:\n\n```Python\nfrom .routers import items, users\n```\n\nmeans:\n\n* Starting in the same package that this module (the file `app/main.py`) lives in (the directory `app/`)...\n* look for the subpackage `routers` (the directory at `app/routers/`)...\n* and from it, import the submodule `items` (the file at `app/routers/items.py`) and `users` (the file at `app/routers/users.py`)...\n\nThe module `items` will have a variable `router` (`items.router`). This is the same one we created in the file `app/routers/items.py`, it's an `APIRouter` object.\n\nAnd then we do the same for the module `users`.\n\nWe could also import them like:\n\n```Python\nfrom app.routers import items, users\n```\n\n/// note\n\nThe first version is a \"relative import\":\n\n```Python\nfrom .routers import items, users\n```\n\nThe second version is an \"absolute import\":\n\n```Python\nfrom app.routers import items, users\n```\n\nTo learn more about Python Packages and Modules, read [the official Python documentation about Modules](https://docs.python.org/3/tutorial/modules.html).\n\n///\n\n### Avoid name collisions { #avoid-name-collisions }\n\nWe are importing the submodule `items` directly, instead of importing just its variable `router`.\n\nThis is because we also have another variable named `router` in the submodule `users`.\n\nIf we had imported one after the other, like:\n\n```Python\nfrom .routers.items import router\nfrom .routers.users import router\n```\n\nthe `router` from `users` would overwrite the one from `items` and we wouldn't be able to use them at the same time.\n\nSo, to be able to use both of them in the same file, we import the submodules directly:\n\n{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title[\"app/main.py\"] *}\n\n### Include the `APIRouter`s for `users` and `items` { #include-the-apirouters-for-users-and-items }\n\nNow, let's include the `router`s from the submodules `users` and `items`:\n\n{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title[\"app/main.py\"] *}\n\n/// note\n\n`users.router` contains the `APIRouter` inside of the file `app/routers/users.py`.\n\nAnd `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`.\n\n///\n\nWith `app.include_router()` we can add each `APIRouter` to the main `FastAPI` application.\n\nIt will include all the routes from that router as part of it.\n\n/// note | Technical Details\n\nFastAPI keeps the original `APIRouter` and its `APIRoute`s active when the router is included in the main application.\n\nThat means custom `APIRouter` and `APIRoute` subclasses can still participate after the router is included.\n\n///\n\n/// tip\n\nYou don't have to worry about performance when including routers.\n\nThis is designed to be lightweight and to avoid adding overhead to each request.\n\nSo it won't affect performance. ⚡\n\n///\n\n### Include an `APIRouter` with a custom `prefix`, `tags`, `responses`, and `dependencies` { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }\n\nNow, let's imagine your organization gave you the `app/internal/admin.py` file.\n\nIt contains an `APIRouter` with some admin *path operations* that your organization shares between several projects.\n\nFor this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`:\n\n{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title[\"app/internal/admin.py\"] *}\n\nBut we still want to set a custom `prefix` when including the `APIRouter` so that all its *path operations* start with `/admin`, we want to secure it with the `dependencies` we already have for this project, and we want to include `tags` and `responses`.\n\nWe can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`:\n\n{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title[\"app/main.py\"] *}\n\nThat way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization.\n\nThe result is that in our app, each of the *path operations* from the `admin` module will have:\n\n* The prefix `/admin`.\n* The tag `admin`.\n* The dependency `get_token_header`.\n* The response `418`. 🍵\n\nBut that will only affect that `APIRouter` in our app, not in any other code that uses it.\n\nSo, for example, other projects could use the same `APIRouter` with a different authentication method.\n\n### Include a *path operation* { #include-a-path-operation }\n\nWe can also add *path operations* directly to the `FastAPI` app.\n\nHere we do it... just to show that we can 🤷:\n\n{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title[\"app/main.py\"] *}\n\nand it will work correctly, together with all the other *path operations* added with `app.include_router()`.\n\n/// note | Very Technical Details\n\n**Note**: this is a very technical detail that you probably can **just skip**.\n\n---\n\nThe `APIRouter`s are not \"mounted\", they are not isolated from the rest of the application.\n\nThis is because we want to include their *path operations* in the OpenAPI schema and the user interfaces.\n\nFastAPI keeps the original routers and path operations active, and combines the router prefixes, dependencies, tags, responses, and other metadata when handling requests and generating OpenAPI.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "The main `FastAPI` { #the-main-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L292-L467", "start_line": 292, "end_line": 467} {"id": "docs/en/docs/tutorial/bigger-applications.md::Configure the `entrypoint` in `pyproject.toml` { #configure-the-entrypoint-in-pyproject-toml }::L468", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Configure the `entrypoint` in `pyproject.toml` { #configure-the-entrypoint-in-pyproject-toml }\n## Configure the `entrypoint` in `pyproject.toml` { #configure-the-entrypoint-in-pyproject-toml }\n\nAs your FastAPI `app` object lives in `app/main.py`, you can configure the `entrypoint` in your `pyproject.toml` file like this:\n\n```toml\n[tool.fastapi]\nentrypoint = \"app.main:app\"\n```\n\nthat is equivalent to importing like:\n\n```python\nfrom app.main import app\n```\n\nThat way the `fastapi` command will know where to find your app.\n\n/// Note\n\nYou could also pass the path to the command, like:\n\n```console\n$ fastapi dev app/main.py\n```\n\nBut you would have to remember to pass the correct path every time you call the `fastapi` command.\n\nAdditionally, other tools might not be able to find it, for example the [VS Code Extension](../editor-support.md) or [FastAPI Cloud](https://fastapicloud.com), so it is recommended to use the `entrypoint` in `pyproject.toml`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "Configure the `entrypoint` in `pyproject.toml` { #configure-the-entrypoint-in-pyproject-toml }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L468-L498", "start_line": 468, "end_line": 498} {"id": "docs/en/docs/tutorial/bigger-applications.md::Check the automatic API docs { #check-the-automatic-api-docs }::L499", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Check the automatic API docs { #check-the-automatic-api-docs }\n## Check the automatic API docs { #check-the-automatic-api-docs }\n\nNow, run your app:\n\n
\n\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nAnd open the docs at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see the automatic API docs, including the paths from all the submodules, using the correct paths (and prefixes) and the correct tags:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "Check the automatic API docs { #check-the-automatic-api-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L499-L518", "start_line": 499, "end_line": 518} {"id": "docs/en/docs/tutorial/bigger-applications.md::Include the same router multiple times with different `prefix` { #include-the-same-router-multiple-times-with-different-prefix }::L519", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Include the same router multiple times with different `prefix` { #include-the-same-router-multiple-times-with-different-prefix }\n## Include the same router multiple times with different `prefix` { #include-the-same-router-multiple-times-with-different-prefix }\n\nYou can also use `.include_router()` multiple times with the *same* router using different prefixes.\n\nThis could be useful, for example, to expose the same API under different prefixes, e.g. `/api/v1` and `/api/latest`.\n\nThis is an advanced usage that you might not really need, but it's there in case you do.", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "Include the same router multiple times with different `prefix` { #include-the-same-router-multiple-times-with-different-prefix }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L519-L526", "start_line": 519, "end_line": 526} {"id": "docs/en/docs/tutorial/bigger-applications.md::Include an `APIRouter` in another { #include-an-apirouter-in-another }::L527", "text": "# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Include an `APIRouter` in another { #include-an-apirouter-in-another }\n## Include an `APIRouter` in another { #include-an-apirouter-in-another }\n\nThe same way you can include an `APIRouter` in a `FastAPI` application, you can include an `APIRouter` in another `APIRouter` using:\n\n```Python\nrouter.include_router(other_router)\n```\n\nYou can do this before or after including `router` in the `FastAPI` app. FastAPI will still include the *path operations* from `other_router` in routing and OpenAPI.\n\nThe same applies to *path operations* added later to the routers. They will be visible through the earlier inclusion too.\n\n/// warning | Technical Details\n\nAvoid directly mutating `router.routes` after including a router. FastAPI treats router inclusion as live, so the original router and its routes remain part of routing and OpenAPI generation.\n\nUse documented APIs such as path operation decorators and `.include_router()` to add routes and routers.\n\nTreat `router.routes` as a lower-level route tree that can contain route definitions and included routers, and avoid relying on it as a flat list of final path operations.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/bigger-applications.md", "symbol": "Include an `APIRouter` in another { #include-an-apirouter-in-another }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/bigger-applications.md#L527-L547", "start_line": 527, "end_line": 547} {"id": "docs/en/docs/tutorial/body-fields.md::Body - Fields { #body-fields }::L1", "text": "# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Body - Fields { #body-fields }\n# Body - Fields { #body-fields }\n\nThe same way you can declare additional validation and metadata in *path operation function* parameters with `Query`, `Path` and `Body`, you can declare validation and metadata inside of Pydantic models using Pydantic's `Field`.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-fields.md", "symbol": "Body - Fields { #body-fields }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-fields.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/body-fields.md::Import `Field` { #import-field }::L5", "text": "# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Import `Field` { #import-field }\n## Import `Field` { #import-field }\n\nFirst, you have to import it:\n\n{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}\n\n\n/// warning\n\nNotice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-fields.md", "symbol": "Import `Field` { #import-field }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-fields.md#L5-L17", "start_line": 5, "end_line": 17} {"id": "docs/en/docs/tutorial/body-fields.md::Declare model attributes { #declare-model-attributes }::L18", "text": "# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Declare model attributes { #declare-model-attributes }\n## Declare model attributes { #declare-model-attributes }\n\nYou can then use `Field` with model attributes:\n\n{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}\n\n`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.\n\n/// note | Technical Details\n\nActually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class.\n\nAnd Pydantic's `Field` returns an instance of `FieldInfo` as well.\n\n`Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class.\n\nRemember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes.\n\n///\n\n/// tip\n\nNotice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-fields.md", "symbol": "Declare model attributes { #declare-model-attributes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-fields.md#L18-L43", "start_line": 18, "end_line": 43} {"id": "docs/en/docs/tutorial/body-fields.md::Add extra information { #add-extra-information }::L44", "text": "# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Add extra information { #add-extra-information }\n## Add extra information { #add-extra-information }\n\nYou can declare extra information in `Field`, `Query`, `Body`, etc. And it will be included in the generated JSON Schema.\n\nYou will learn more about adding extra information later in the docs, when learning to declare examples.\n\n/// warning\n\nExtra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.\nAs these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-fields.md", "symbol": "Add extra information { #add-extra-information }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-fields.md#L44-L56", "start_line": 44, "end_line": 56} {"id": "docs/en/docs/tutorial/body-fields.md::Recap { #recap }::L57", "text": "# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can use Pydantic's `Field` to declare extra validations and metadata for model attributes.\n\nYou can also use the extra keyword arguments to pass additional JSON Schema metadata.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-fields.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-fields.md#L57-L61", "start_line": 57, "end_line": 61} {"id": "docs/en/docs/tutorial/body-multiple-params.md::Body - Multiple Parameters { #body-multiple-parameters }::L1", "text": "# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Body - Multiple Parameters { #body-multiple-parameters }\n# Body - Multiple Parameters { #body-multiple-parameters }\n\nNow that we have seen how to use `Path` and `Query`, let's see more advanced uses of request body declarations.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-multiple-params.md", "symbol": "Body - Multiple Parameters { #body-multiple-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-multiple-params.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/body-multiple-params.md::Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }::L5", "text": "# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }\n## Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }\n\nFirst, of course, you can mix `Path`, `Query` and request body parameter declarations freely and **FastAPI** will know what to do.\n\nAnd you can also declare body parameters as optional, by setting the default to `None`:\n\n{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}\n\n/// note\n\nNotice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-multiple-params.md", "symbol": "Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-multiple-params.md#L5-L18", "start_line": 5, "end_line": 18} {"id": "docs/en/docs/tutorial/body-multiple-params.md::Multiple body parameters { #multiple-body-parameters }::L19", "text": "# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Multiple body parameters { #multiple-body-parameters }\n## Multiple body parameters { #multiple-body-parameters }\n\nIn the previous example, the *path operations* would expect a JSON body with the attributes of an `Item`, like:\n\n```JSON\n{\n \"name\": \"Foo\",\n \"description\": \"The pretender\",\n \"price\": 42.0,\n \"tax\": 3.2\n}\n```\n\nBut you can also declare multiple body parameters, e.g. `item` and `user`:\n\n{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}\n\n\nIn this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models).\n\nSo, it will then use the parameter names as keys (field names) in the body, and expect a body like:\n\n```JSON\n{\n \"item\": {\n \"name\": \"Foo\",\n \"description\": \"The pretender\",\n \"price\": 42.0,\n \"tax\": 3.2\n },\n \"user\": {\n \"username\": \"dave\",\n \"full_name\": \"Dave Grohl\"\n }\n}\n```\n\n/// note\n\nNotice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`.\n\n///\n\n**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`.\n\nIt will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-multiple-params.md", "symbol": "Multiple body parameters { #multiple-body-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-multiple-params.md#L19-L65", "start_line": 19, "end_line": 65} {"id": "docs/en/docs/tutorial/body-multiple-params.md::Singular values in body { #singular-values-in-body }::L66", "text": "# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Singular values in body { #singular-values-in-body }\n## Singular values in body { #singular-values-in-body }\n\nThe same way there is a `Query` and `Path` to define extra data for query and path parameters, **FastAPI** provides an equivalent `Body`.\n\nFor example, extending the previous model, you could decide that you want to have another key `importance` in the same body, besides the `item` and `user`.\n\nIf you declare it as is, because it is a singular value, **FastAPI** will assume that it is a query parameter.\n\nBut you can instruct **FastAPI** to treat it as another body key using `Body`:\n\n{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}\n\n\nIn this case, **FastAPI** will expect a body like:\n\n```JSON\n{\n \"item\": {\n \"name\": \"Foo\",\n \"description\": \"The pretender\",\n \"price\": 42.0,\n \"tax\": 3.2\n },\n \"user\": {\n \"username\": \"dave\",\n \"full_name\": \"Dave Grohl\"\n },\n \"importance\": 5\n}\n```\n\nAgain, it will convert the data types, validate, document, etc.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-multiple-params.md", "symbol": "Singular values in body { #singular-values-in-body }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-multiple-params.md#L66-L98", "start_line": 66, "end_line": 98} {"id": "docs/en/docs/tutorial/body-multiple-params.md::Multiple body params and query { #multiple-body-params-and-query }::L99", "text": "# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Multiple body params and query { #multiple-body-params-and-query }\n## Multiple body params and query { #multiple-body-params-and-query }\n\nOf course, you can also declare additional query parameters whenever you need, additional to any body parameters.\n\nAs, by default, singular values are interpreted as query parameters, you don't have to explicitly add a `Query`, you can just do:\n\n```Python\nq: str | None = None\n```\n\nFor example:\n\n{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}\n\n\n/// note\n\n`Body` also has all the same extra validation and metadata parameters as `Query`, `Path` and others you will see later.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-multiple-params.md", "symbol": "Multiple body params and query { #multiple-body-params-and-query }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-multiple-params.md#L99-L119", "start_line": 99, "end_line": 119} {"id": "docs/en/docs/tutorial/body-multiple-params.md::Embed a single body parameter { #embed-a-single-body-parameter }::L120", "text": "# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Embed a single body parameter { #embed-a-single-body-parameter }\n## Embed a single body parameter { #embed-a-single-body-parameter }\n\nLet's say you only have a single `item` body parameter from a Pydantic model `Item`.\n\nBy default, **FastAPI** will then expect its body directly.\n\nBut if you want it to expect a JSON with a key `item` and inside of it the model contents, as it does when you declare extra body parameters, you can use the special `Body` parameter `embed`:\n\n```Python\nitem: Annotated[Item, Body(embed=True)]\n```\n\nas in:\n\n{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}\n\n\nIn this case **FastAPI** will expect a body like:\n\n```JSON hl_lines=\"2\"\n{\n \"item\": {\n \"name\": \"Foo\",\n \"description\": \"The pretender\",\n \"price\": 42.0,\n \"tax\": 3.2\n }\n}\n```\n\ninstead of:\n\n```JSON\n{\n \"name\": \"Foo\",\n \"description\": \"The pretender\",\n \"price\": 42.0,\n \"tax\": 3.2\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/body-multiple-params.md", "symbol": "Embed a single body parameter { #embed-a-single-body-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-multiple-params.md#L120-L160", "start_line": 120, "end_line": 160} {"id": "docs/en/docs/tutorial/body-multiple-params.md::Recap { #recap }::L161", "text": "# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can add multiple body parameters to your *path operation function*, even though a request can only have a single body.\n\nBut **FastAPI** will handle it, give you the correct data in your function, and validate and document the correct schema in the *path operation*.\n\nYou can also declare singular values to be received as part of the body.\n\nAnd you can instruct **FastAPI** to embed the body in a key even when there is only a single parameter declared.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-multiple-params.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-multiple-params.md#L161-L169", "start_line": 161, "end_line": 169} {"id": "docs/en/docs/tutorial/body-nested-models.md::Body - Nested Models { #body-nested-models }::L1", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Body - Nested Models { #body-nested-models }\n# Body - Nested Models { #body-nested-models }\n\nWith **FastAPI**, you can define, validate, document, and use arbitrarily deeply nested models (thanks to Pydantic).", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Body - Nested Models { #body-nested-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/body-nested-models.md::List fields { #list-fields }::L5", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: List fields { #list-fields }\n## List fields { #list-fields }\n\nYou can define an attribute to be a subtype. For example, a Python `list`:\n\n{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}\n\nThis will make `tags` be a list, although it doesn't declare the type of the elements of the list.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "List fields { #list-fields }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L5-L12", "start_line": 5, "end_line": 12} {"id": "docs/en/docs/tutorial/body-nested-models.md::List fields with type parameter { #list-fields-with-type-parameter }::L13", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: List fields with type parameter { #list-fields-with-type-parameter }\n## List fields with type parameter { #list-fields-with-type-parameter }\n\nBut Python has a specific way to declare lists with internal types, or \"type parameters\":\n\n### Declare a `list` with a type parameter { #declare-a-list-with-a-type-parameter }\n\nTo declare types that have type parameters (internal types), like `list`, `dict`, `tuple`,\npass the internal type(s) as \"type parameters\" using square brackets: `[` and `]`\n\n```Python\nmy_list: list[str]\n```\n\nThat's all standard Python syntax for type declarations.\n\nUse that same standard syntax for model attributes with internal types.\n\nSo, in our example, we can make `tags` be specifically a \"list of strings\":\n\n{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "List fields with type parameter { #list-fields-with-type-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L13-L33", "start_line": 13, "end_line": 33} {"id": "docs/en/docs/tutorial/body-nested-models.md::Set types { #set-types }::L34", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Set types { #set-types }\n## Set types { #set-types }\n\nBut then we think about it, and realize that tags shouldn't repeat, they would probably be unique strings.\n\nAnd Python has a special data type for sets of unique items, the `set`.\n\nThen we can declare `tags` as a set of strings:\n\n{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}\n\nWith this, even if you receive a request with duplicate data, it will be converted to a set of unique items.\n\nAnd whenever you output that data, even if the source had duplicates, it will be output as a set of unique items.\n\nAnd it will be annotated / documented accordingly too.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Set types { #set-types }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L34-L49", "start_line": 34, "end_line": 49} {"id": "docs/en/docs/tutorial/body-nested-models.md::Nested Models { #nested-models }::L50", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Nested Models { #nested-models }\n## Nested Models { #nested-models }\n\nEach attribute of a Pydantic model has a type.\n\nBut that type can itself be another Pydantic model.\n\nSo, you can declare deeply nested JSON \"objects\" with specific attribute names, types and validations.\n\nAll that, arbitrarily nested.\n\n### Define a submodel { #define-a-submodel }\n\nFor example, we can define an `Image` model:\n\n{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}\n\n### Use the submodel as a type { #use-the-submodel-as-a-type }\n\nAnd then we can use it as the type of an attribute:\n\n{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}\n\nThis would mean that **FastAPI** would expect a body similar to:\n\n```JSON\n{\n \"name\": \"Foo\",\n \"description\": \"The pretender\",\n \"price\": 42.0,\n \"tax\": 3.2,\n \"tags\": [\"rock\", \"metal\", \"bar\"],\n \"image\": {\n \"url\": \"http://example.com/baz.jpg\",\n \"name\": \"The Foo live\"\n }\n}\n```\n\nAgain, doing just that declaration, with **FastAPI** you get:\n\n* Editor support (completion, etc.), even for nested models\n* Data conversion\n* Data validation\n* Automatic documentation", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Nested Models { #nested-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L50-L94", "start_line": 50, "end_line": 94} {"id": "docs/en/docs/tutorial/body-nested-models.md::Special types and validation { #special-types-and-validation }::L95", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Special types and validation { #special-types-and-validation }\n## Special types and validation { #special-types-and-validation }\n\nApart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`.\n\nTo see all the options you have, check out [Pydantic's Type Overview](https://docs.pydantic.dev/latest/concepts/types/). You will see some examples in the next chapter.\n\nFor example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`:\n\n{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}\n\nThe string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Special types and validation { #special-types-and-validation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L95-L106", "start_line": 95, "end_line": 106} {"id": "docs/en/docs/tutorial/body-nested-models.md::Attributes with lists of submodels { #attributes-with-lists-of-submodels }::L107", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Attributes with lists of submodels { #attributes-with-lists-of-submodels }\n## Attributes with lists of submodels { #attributes-with-lists-of-submodels }\n\nYou can also use Pydantic models as subtypes of `list`, `set`, etc.:\n\n{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}\n\nThis will expect (convert, validate, document, etc.) a JSON body like:\n\n```JSON hl_lines=\"11\"\n{\n \"name\": \"Foo\",\n \"description\": \"The pretender\",\n \"price\": 42.0,\n \"tax\": 3.2,\n \"tags\": [\n \"rock\",\n \"metal\",\n \"bar\"\n ],\n \"images\": [\n {\n \"url\": \"http://example.com/baz.jpg\",\n \"name\": \"The Foo live\"\n },\n {\n \"url\": \"http://example.com/dave.jpg\",\n \"name\": \"The Baz\"\n }\n ]\n}\n```\n\n/// note\n\nNotice how the `images` key now has a list of image objects.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Attributes with lists of submodels { #attributes-with-lists-of-submodels }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L107-L144", "start_line": 107, "end_line": 144} {"id": "docs/en/docs/tutorial/body-nested-models.md::Deeply nested models { #deeply-nested-models }::L145", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Deeply nested models { #deeply-nested-models }\n## Deeply nested models { #deeply-nested-models }\n\nYou can define arbitrarily deeply nested models:\n\n{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}\n\n/// note\n\nNotice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Deeply nested models { #deeply-nested-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L145-L156", "start_line": 145, "end_line": 156} {"id": "docs/en/docs/tutorial/body-nested-models.md::Bodies of pure lists { #bodies-of-pure-lists }::L157", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Bodies of pure lists { #bodies-of-pure-lists }\n## Bodies of pure lists { #bodies-of-pure-lists }\n\nIf the top level value of the JSON body you expect is a JSON `array` (a Python `list`), you can declare the type in the parameter of the function, the same as in Pydantic models:\n\n```Python\nimages: list[Image]\n```\n\nas in:\n\n{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Bodies of pure lists { #bodies-of-pure-lists }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L157-L168", "start_line": 157, "end_line": 168} {"id": "docs/en/docs/tutorial/body-nested-models.md::Editor support everywhere { #editor-support-everywhere }::L169", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Editor support everywhere { #editor-support-everywhere }\n## Editor support everywhere { #editor-support-everywhere }\n\nAnd you get editor support everywhere.\n\nEven for items inside of lists:\n\n\n\nYou couldn't get this kind of editor support if you were working directly with `dict` instead of Pydantic models.\n\nBut you don't have to worry about them either, incoming dicts are converted automatically and your output is converted automatically to JSON too.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Editor support everywhere { #editor-support-everywhere }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L169-L180", "start_line": 169, "end_line": 180} {"id": "docs/en/docs/tutorial/body-nested-models.md::Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }::L181", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }\n## Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }\n\nYou can also declare a body as a `dict` with keys of some type and values of some other type.\n\nThis way, you don't have to know beforehand what the valid field/attribute names are (as would be the case with Pydantic models).\n\nThis would be useful if you want to receive keys that you don't already know.\n\n---\n\nAnother useful case is when you want to have keys of another type (e.g., `int`).\n\nThat's what we are going to see here.\n\nIn this case, you would accept any `dict` as long as it has `int` keys with `float` values:\n\n{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}\n\n/// tip\n\nKeep in mind that JSON only supports `str` as keys.\n\nBut Pydantic has automatic data conversion.\n\nThis means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.\n\nAnd the `dict` you receive as `weights` will actually have `int` keys and `float` values.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L181-L210", "start_line": 181, "end_line": 210} {"id": "docs/en/docs/tutorial/body-nested-models.md::Recap { #recap }::L211", "text": "# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Recap { #recap }\n## Recap { #recap }\n\nWith **FastAPI** you have the maximum flexibility provided by Pydantic models, while keeping your code simple, short and elegant.\n\nBut with all the benefits:\n\n* Editor support (completion everywhere!)\n* Data conversion (a.k.a. parsing / serialization)\n* Data validation\n* Schema documentation\n* Automatic docs", "source_type": "doc", "path": "docs/en/docs/tutorial/body-nested-models.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-nested-models.md#L211-L221", "start_line": 211, "end_line": 221} {"id": "docs/en/docs/tutorial/body-updates.md::Update replacing with `PUT` { #update-replacing-with-put }::L3", "text": "# Doc: docs/en/docs/tutorial/body-updates.md | Page: Body - Updates { #body-updates } | Section: Update replacing with `PUT` { #update-replacing-with-put }\n## Update replacing with `PUT` { #update-replacing-with-put }\n\nTo update an item you can use the [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) operation.\n\nYou can use the `jsonable_encoder` to convert the input data to data that can be stored as JSON (e.g. with a NoSQL database). For example, converting `datetime` to `str`.\n\n{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}\n\n`PUT` is used to receive data that should replace the existing data.\n\n### Warning about replacing { #warning-about-replacing }\n\nThat means that if you want to update the item `bar` using `PUT` with a body containing:\n\n```Python\n{\n \"name\": \"Barz\",\n \"price\": 3,\n \"description\": None,\n}\n```\n\nbecause it doesn't include the already stored attribute `\"tax\": 20.2`, the input model would take the default value of `\"tax\": 10.5`.\n\nAnd the data would be saved with that \"new\" `tax` of `10.5`.", "source_type": "doc", "path": "docs/en/docs/tutorial/body-updates.md", "symbol": "Update replacing with `PUT` { #update-replacing-with-put }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-updates.md#L3-L28", "start_line": 3, "end_line": 28} {"id": "docs/en/docs/tutorial/body-updates.md::Partial updates with `PATCH` { #partial-updates-with-patch }::L29", "text": "# Doc: docs/en/docs/tutorial/body-updates.md | Page: Body - Updates { #body-updates } | Section: Partial updates with `PATCH` { #partial-updates-with-patch }\n## Partial updates with `PATCH` { #partial-updates-with-patch }\n\nYou can also use the [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) operation to *partially* update data.\n\nThis means that you can send only the data that you want to update, leaving the rest intact.\n\n/// note\n\n`PATCH` is less commonly used and known than `PUT`.\n\nAnd many teams use only `PUT`, even for partial updates.\n\nYou are **free** to use them however you want, **FastAPI** doesn't impose any restrictions.\n\nBut this guide shows you, more or less, how they are intended to be used.\n\n///\n\n### Using Pydantic's `exclude_unset` parameter { #using-pydantics-exclude-unset-parameter }\n\nIf you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.model_dump()`.\n\nLike `item.model_dump(exclude_unset=True)`.\n\nThat would generate a `dict` with only the data that was set when creating the `item` model, excluding default values.\n\nThen you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:\n\n{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}\n\n### Using Pydantic's `update` parameter { #using-pydantics-update-parameter }\n\nNow, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update.\n\nLike `stored_item_model.model_copy(update=update_data)`:\n\n{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}\n\n### Partial updates recap { #partial-updates-recap }\n\nIn summary, to apply partial updates you would:\n\n* (Optionally) use `PATCH` instead of `PUT`.\n* Retrieve the stored data.\n* Put that data in a Pydantic model.\n* Generate a `dict` without default values from the input model (using `exclude_unset`).\n * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model.\n* Create a copy of the stored model, updating its attributes with the received partial updates (using the `update` parameter).\n* Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`).\n * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`.\n* Save the data to your DB.\n* Return the updated model.\n\n{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}\n\n/// tip\n\nYou can actually use this same technique with an HTTP `PUT` operation.\n\nBut the example here uses `PATCH` because it was created for these use cases.\n\n///\n\n/// note\n\nNotice that the input model is still validated.\n\nSo, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`).\n\nTo distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body-updates.md", "symbol": "Partial updates with `PATCH` { #partial-updates-with-patch }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body-updates.md#L29-L100", "start_line": 29, "end_line": 100} {"id": "docs/en/docs/tutorial/body.md::Request Body { #request-body }::L1", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Request Body { #request-body }\n# Request Body { #request-body }\n\nWhen you need to send data from a client (let's say, a browser) to your API, you send it as a **request body**.\n\nA **request** body is data sent by the client to your API. A **response** body is the data your API sends to the client.\n\nYour API almost always has to send a **response** body. But clients don't necessarily need to send **request bodies** all the time, sometimes they only request a path, maybe with some query parameters, but don't send a body.\n\nTo declare a **request** body, you use [Pydantic](https://docs.pydantic.dev/) models with all their power and benefits.\n\n/// note\n\nTo send data, you should use one of: `POST` (the most common), `PUT`, `DELETE` or `PATCH`.\n\nSending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases.\n\nAs it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Request Body { #request-body }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L1-L20", "start_line": 1, "end_line": 20} {"id": "docs/en/docs/tutorial/body.md::Import Pydantic's `BaseModel` { #import-pydantics-basemodel }::L21", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Import Pydantic's `BaseModel` { #import-pydantics-basemodel }\n## Import Pydantic's `BaseModel` { #import-pydantics-basemodel }\n\nFirst, you need to import `BaseModel` from `pydantic`:\n\n{* ../../docs_src/body/tutorial001_py310.py hl[2] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Import Pydantic's `BaseModel` { #import-pydantics-basemodel }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L21-L26", "start_line": 21, "end_line": 26} {"id": "docs/en/docs/tutorial/body.md::Create your data model { #create-your-data-model }::L27", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Create your data model { #create-your-data-model }\n## Create your data model { #create-your-data-model }\n\nThen you declare your data model as a class that inherits from `BaseModel`.\n\nUse standard Python types for all the attributes:\n\n{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}\n\n\nThe same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use `None` to make it just optional.\n\nFor example, this model above declares a JSON \"`object`\" (or Python `dict`) like:\n\n```JSON\n{\n \"name\": \"Foo\",\n \"description\": \"An optional description\",\n \"price\": 45.2,\n \"tax\": 3.5\n}\n```\n\n...as `description` and `tax` are optional (with a default value of `None`), this JSON \"`object`\" would also be valid:\n\n```JSON\n{\n \"name\": \"Foo\",\n \"price\": 45.2\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Create your data model { #create-your-data-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L27-L57", "start_line": 27, "end_line": 57} {"id": "docs/en/docs/tutorial/body.md::Declare it as a parameter { #declare-it-as-a-parameter }::L58", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Declare it as a parameter { #declare-it-as-a-parameter }\n## Declare it as a parameter { #declare-it-as-a-parameter }\n\nTo add it to your *path operation*, declare it the same way you declared path and query parameters:\n\n{* ../../docs_src/body/tutorial001_py310.py hl[16] *}\n\n...and declare its type as the model you created, `Item`.", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Declare it as a parameter { #declare-it-as-a-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L58-L65", "start_line": 58, "end_line": 65} {"id": "docs/en/docs/tutorial/body.md::Results { #results }::L66", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Results { #results }\n## Results { #results }\n\nWith just that Python type declaration, **FastAPI** will:\n\n* Read the body of the request as JSON.\n* Convert the corresponding types (if needed).\n* Validate the data.\n * If the data is invalid, it will return a nice and clear error, indicating exactly where and what was the incorrect data.\n* Give you the received data in the parameter `item`.\n * As you declared it in the function to be of type `Item`, you will also have all the editor support (completion, etc) for all of the attributes and their types.\n* Generate [JSON Schema](https://json-schema.org) definitions for your model, you can also use them anywhere else you like if it makes sense for your project.\n* Those schemas will be part of the generated OpenAPI schema, and used by the automatic documentation UIs.", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Results { #results }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L66-L78", "start_line": 66, "end_line": 78} {"id": "docs/en/docs/tutorial/body.md::Automatic docs { #automatic-docs }::L79", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Automatic docs { #automatic-docs }\n## Automatic docs { #automatic-docs }\n\nThe JSON Schemas of your models will be part of your OpenAPI generated schema, and will be shown in the interactive API docs:\n\n\n\nAnd will also be used in the API docs inside each *path operation* that needs them:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Automatic docs { #automatic-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L79-L88", "start_line": 79, "end_line": 88} {"id": "docs/en/docs/tutorial/body.md::Editor support { #editor-support }::L89", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Editor support { #editor-support }\n## Editor support { #editor-support }\n\nIn your editor, inside your function you will get type hints and completion everywhere (this wouldn't happen if you received a `dict` instead of a Pydantic model):\n\n\n\nYou also get error checks for incorrect type operations:\n\n\n\nThis is not by chance, the whole framework was built around that design.\n\nAnd it was thoroughly tested at the design phase, before any implementation, to ensure it would work with all the editors.\n\nThere were even some changes to Pydantic itself to support this.\n\nThe previous screenshots were taken with [Visual Studio Code](https://code.visualstudio.com).\n\nBut you would get the same editor support with [PyCharm](https://www.jetbrains.com/pycharm/) and most of the other Python editors:\n\n\n\n/// tip\n\nIf you use [PyCharm](https://www.jetbrains.com/pycharm/) as your editor, you can use the [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/).\n\nIt improves editor support for Pydantic models, with:\n\n* auto-completion\n* type checks\n* refactoring\n* searching\n* inspections\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Editor support { #editor-support }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L89-L124", "start_line": 89, "end_line": 124} {"id": "docs/en/docs/tutorial/body.md::Use the model { #use-the-model }::L125", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Use the model { #use-the-model }\n## Use the model { #use-the-model }\n\nInside of the function, you can access all the attributes of the model object directly:\n\n{* ../../docs_src/body/tutorial002_py310.py *}", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Use the model { #use-the-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L125-L130", "start_line": 125, "end_line": 130} {"id": "docs/en/docs/tutorial/body.md::Request body + path parameters { #request-body-path-parameters }::L131", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Request body + path parameters { #request-body-path-parameters }\n## Request body + path parameters { #request-body-path-parameters }\n\nYou can declare path parameters and request body at the same time.\n\n**FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**.\n\n{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Request body + path parameters { #request-body-path-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L131-L139", "start_line": 131, "end_line": 139} {"id": "docs/en/docs/tutorial/body.md::Request body + path + query parameters { #request-body-path-query-parameters }::L140", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Request body + path + query parameters { #request-body-path-query-parameters }\n## Request body + path + query parameters { #request-body-path-query-parameters }\n\nYou can also declare **body**, **path** and **query** parameters, all at the same time.\n\n**FastAPI** will recognize each of them and take the data from the correct place.\n\n{* ../../docs_src/body/tutorial004_py310.py hl[16] *}\n\nThe function parameters will be recognized as follows:\n\n* If the parameter is also declared in the **path**, it will be used as a path parameter.\n* If the parameter is of a **singular type** (like `int`, `float`, `str`, `bool`, etc) it will be interpreted as a **query** parameter.\n* If the parameter is declared to be of the type of a **Pydantic model**, it will be interpreted as a request **body**.\n\n/// note\n\nFastAPI will know that the value of `q` is not required because of the default value `= None`.\n\nThe `str | None` is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`.\n\nBut adding the type annotations will allow your editor to give you better support and detect errors.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Request body + path + query parameters { #request-body-path-query-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L140-L163", "start_line": 140, "end_line": 163} {"id": "docs/en/docs/tutorial/body.md::Without Pydantic { #without-pydantic }::L164", "text": "# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Without Pydantic { #without-pydantic }\n## Without Pydantic { #without-pydantic }\n\nIf you don't want to use Pydantic models, you can also use **Body** parameters. See the docs for [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body).", "source_type": "doc", "path": "docs/en/docs/tutorial/body.md", "symbol": "Without Pydantic { #without-pydantic }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/body.md#L164-L166", "start_line": 164, "end_line": 166} {"id": "docs/en/docs/tutorial/cookie-param-models.md::Cookie Parameter Models { #cookie-parameter-models }::L1", "text": "# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Cookie Parameter Models { #cookie-parameter-models }\n# Cookie Parameter Models { #cookie-parameter-models }\n\nIf you have a group of **cookies** that are related, you can create a **Pydantic model** to declare them. 🍪\n\nThis would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎\n\n/// note\n\nThis is supported since FastAPI version `0.115.0`. 🤓\n\n///\n\n/// tip\n\nThis same technique applies to `Query`, `Cookie`, and `Header`. 😎\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-param-models.md", "symbol": "Cookie Parameter Models { #cookie-parameter-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-param-models.md#L1-L18", "start_line": 1, "end_line": 18} {"id": "docs/en/docs/tutorial/cookie-param-models.md::Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }::L19", "text": "# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }\n## Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }\n\nDeclare the **cookie** parameters that you need in a **Pydantic model**, and then declare the parameter as `Cookie`:\n\n{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}\n\n**FastAPI** will **extract** the data for **each field** from the **cookies** received in the request and give you the Pydantic model you defined.", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-param-models.md", "symbol": "Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-param-models.md#L19-L26", "start_line": 19, "end_line": 26} {"id": "docs/en/docs/tutorial/cookie-param-models.md::Check the Docs { #check-the-docs }::L27", "text": "# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Check the Docs { #check-the-docs }\n## Check the Docs { #check-the-docs }\n\nYou can see the defined cookies in the docs UI at `/docs`:\n\n
\n\n
\n\n/// note\n\nHave in mind that, as **browsers handle cookies** in special ways and behind the scenes, they **don't** easily allow **JavaScript** to touch them.\n\nIf you go to the **API docs UI** at `/docs` you will be able to see the **documentation** for cookies for your *path operations*.\n\nBut even if you **fill the data** and click \"Execute\", because the docs UI works with **JavaScript**, the cookies won't be sent, and you will see an **error** message as if you didn't write any values.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-param-models.md", "symbol": "Check the Docs { #check-the-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-param-models.md#L27-L44", "start_line": 27, "end_line": 44} {"id": "docs/en/docs/tutorial/cookie-param-models.md::Forbid Extra Cookies { #forbid-extra-cookies }::L45", "text": "# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Forbid Extra Cookies { #forbid-extra-cookies }\n## Forbid Extra Cookies { #forbid-extra-cookies }\n\nIn some special use cases (probably not very common), you might want to **restrict** the cookies that you want to receive.\n\nYour API now has the power to control its own cookie consent. 🤪🍪\n\nYou can use Pydantic's model configuration to `forbid` any `extra` fields:\n\n{* ../../docs_src/cookie_param_models/tutorial002_an_py310.py hl[10] *}\n\nIf a client tries to send some **extra cookies**, they will receive an **error** response.\n\nPoor cookie banners with all their effort to get your consent for the API to reject it. 🍪\n\nFor example, if the client tries to send a `santa_tracker` cookie with a value of `good-list-please`, the client will receive an **error** response telling them that the `santa_tracker` cookie is not allowed:\n\n```json\n{\n \"detail\": [\n {\n \"type\": \"extra_forbidden\",\n \"loc\": [\"cookie\", \"santa_tracker\"],\n \"msg\": \"Extra inputs are not permitted\",\n \"input\": \"good-list-please\",\n }\n ]\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-param-models.md", "symbol": "Forbid Extra Cookies { #forbid-extra-cookies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-param-models.md#L45-L73", "start_line": 45, "end_line": 73} {"id": "docs/en/docs/tutorial/cookie-param-models.md::Summary { #summary }::L74", "text": "# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Summary { #summary }\n## Summary { #summary }\n\nYou can use **Pydantic models** to declare **cookies** in **FastAPI**. 😎", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-param-models.md", "symbol": "Summary { #summary }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-param-models.md#L74-L76", "start_line": 74, "end_line": 76} {"id": "docs/en/docs/tutorial/cookie-params.md::Cookie Parameters { #cookie-parameters }::L1", "text": "# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Cookie Parameters { #cookie-parameters }\n# Cookie Parameters { #cookie-parameters }\n\nYou can define Cookie parameters the same way you define `Query` and `Path` parameters.", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-params.md", "symbol": "Cookie Parameters { #cookie-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-params.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/cookie-params.md::Import `Cookie` { #import-cookie }::L5", "text": "# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Import `Cookie` { #import-cookie }\n## Import `Cookie` { #import-cookie }\n\nFirst import `Cookie`:\n\n{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-params.md", "symbol": "Import `Cookie` { #import-cookie }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-params.md#L5-L10", "start_line": 5, "end_line": 10} {"id": "docs/en/docs/tutorial/cookie-params.md::Declare `Cookie` parameters { #declare-cookie-parameters }::L11", "text": "# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Declare `Cookie` parameters { #declare-cookie-parameters }\n## Declare `Cookie` parameters { #declare-cookie-parameters }\n\nThen declare the cookie parameters using the same structure as with `Path` and `Query`.\n\nYou can define the default value as well as all the extra validation or annotation parameters:\n\n{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *}\n\n/// note | Technical Details\n\n`Cookie` is a \"sister\" class of `Path` and `Query`. It also inherits from the same common `Param` class.\n\nBut remember that when you import `Query`, `Path`, `Cookie` and others from `fastapi`, those are actually functions that return special classes.\n\n///\n\n/// note\n\nTo declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters.\n\n///\n\n/// note\n\nHave in mind that, as **browsers handle cookies** in special ways and behind the scenes, they **don't** easily allow **JavaScript** to touch them.\n\nIf you go to the **API docs UI** at `/docs` you will be able to see the **documentation** for cookies for your *path operations*.\n\nBut even if you **fill the data** and click \"Execute\", because the docs UI works with **JavaScript**, the cookies won't be sent, and you will see an **error** message as if you didn't write any values.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-params.md", "symbol": "Declare `Cookie` parameters { #declare-cookie-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-params.md#L11-L42", "start_line": 11, "end_line": 42} {"id": "docs/en/docs/tutorial/cookie-params.md::Recap { #recap }::L43", "text": "# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Recap { #recap }\n## Recap { #recap }\n\nDeclare cookies with `Cookie`, using the same common pattern as `Query` and `Path`.", "source_type": "doc", "path": "docs/en/docs/tutorial/cookie-params.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cookie-params.md#L43-L45", "start_line": 43, "end_line": 45} {"id": "docs/en/docs/tutorial/cors.md::CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing }::L1", "text": "# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing }\n# CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing }\n\n[CORS or \"Cross-Origin Resource Sharing\"](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) refers to the situations when a frontend running in a browser has JavaScript code that communicates with a backend, and the backend is in a different \"origin\" than the frontend.", "source_type": "doc", "path": "docs/en/docs/tutorial/cors.md", "symbol": "CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cors.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/cors.md::Origin { #origin }::L5", "text": "# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Origin { #origin }\n## Origin { #origin }\n\nAn origin is the combination of protocol (`http`, `https`), domain (`myapp.com`, `localhost`, `localhost.tiangolo.com`), and port (`80`, `443`, `8080`).\n\nSo, all these are different origins:\n\n* `http://localhost`\n* `https://localhost`\n* `http://localhost:8080`\n\nEven if they are all in `localhost`, they use different protocols or ports, so, they are different \"origins\".", "source_type": "doc", "path": "docs/en/docs/tutorial/cors.md", "symbol": "Origin { #origin }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cors.md#L5-L16", "start_line": 5, "end_line": 16} {"id": "docs/en/docs/tutorial/cors.md::Steps { #steps }::L17", "text": "# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Steps { #steps }\n## Steps { #steps }\n\nSo, let's say you have a frontend running in your browser at `http://localhost:8080`, and its JavaScript is trying to communicate with a backend running at `http://localhost` (because we don't specify a port, the browser will assume the default port `80`).\n\nThen, the browser will send an HTTP `OPTIONS` request to the `:80`-backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the `:8080`-browser will let the JavaScript in the frontend send its request to the `:80`-backend.\n\nTo achieve this, the `:80`-backend must have a list of \"allowed origins\".\n\nIn this case, the list would have to include `http://localhost:8080` for the `:8080`-frontend to work correctly.", "source_type": "doc", "path": "docs/en/docs/tutorial/cors.md", "symbol": "Steps { #steps }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cors.md#L17-L26", "start_line": 17, "end_line": 26} {"id": "docs/en/docs/tutorial/cors.md::Wildcards { #wildcards }::L27", "text": "# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Wildcards { #wildcards }\n## Wildcards { #wildcards }\n\nIt's also possible to declare the list as `\"*\"` (a \"wildcard\") to say that all are allowed.\n\nBut that will only allow certain types of communication, excluding everything that involves credentials: Cookies, Authorization headers like those used with Bearer Tokens, etc.\n\nSo, for everything to work correctly, it's better to specify explicitly the allowed origins.", "source_type": "doc", "path": "docs/en/docs/tutorial/cors.md", "symbol": "Wildcards { #wildcards }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cors.md#L27-L34", "start_line": 27, "end_line": 34} {"id": "docs/en/docs/tutorial/cors.md::Use `CORSMiddleware` { #use-corsmiddleware }::L35", "text": "# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Use `CORSMiddleware` { #use-corsmiddleware }\n## Use `CORSMiddleware` { #use-corsmiddleware }\n\nYou can configure it in your **FastAPI** application using the `CORSMiddleware`.\n\n* Import `CORSMiddleware`.\n* Create a list of allowed origins (as strings).\n* Add it as a \"middleware\" to your **FastAPI** application.\n\nYou can also specify whether your backend allows:\n\n* Credentials (Authorization headers, Cookies, etc).\n* Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `\"*\"`.\n* Specific HTTP headers or all of them with the wildcard `\"*\"`.\n\n{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}\n\n\nThe default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context.\n\nThe following arguments are supported:\n\n* `allow_origins` - A list of origins that should be permitted to make cross-origin requests. E.g. `['https://example.org', 'https://www.example.org']`. You can use `['*']` to allow any origin.\n* `allow_origin_regex` - A regex string to match against origins that should be permitted to make cross-origin requests. e.g. `'https://.*\\.example\\.org'`.\n* `allow_methods` - A list of HTTP methods that should be allowed for cross-origin requests. Defaults to `['GET']`. You can use `['*']` to allow all standard methods.\n* `allow_headers` - A list of HTTP request headers that should be supported for cross-origin requests. Defaults to `[]`. You can use `['*']` to allow all headers. The `Accept`, `Accept-Language`, `Content-Language` and `Content-Type` headers are always allowed for [simple CORS requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests).\n* `allow_credentials` - Indicate that cookies should be supported for cross-origin requests. Defaults to `False`.\n\n None of `allow_origins`, `allow_methods` and `allow_headers` can be set to `['*']` if `allow_credentials` is set to `True`. All of them must be [explicitly specified](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#credentialed_requests_and_wildcards).\n\n* `expose_headers` - Indicate any response headers that should be made accessible to the browser. Defaults to `[]`.\n* `max_age` - Sets a maximum time in seconds for browsers to cache CORS responses. Defaults to `600`.\n\nThe middleware responds to two particular types of HTTP request...\n\n### CORS preflight requests { #cors-preflight-requests }\n\nThese are any `OPTIONS` request with `Origin` and `Access-Control-Request-Method` headers.\n\nIn this case the middleware will intercept the incoming request and respond with appropriate CORS headers, and either a `200` or `400` response for informational purposes.\n\n### Simple requests { #simple-requests }\n\nAny request with an `Origin` header. In this case the middleware will pass the request through as normal, but will include appropriate CORS headers on the response.", "source_type": "doc", "path": "docs/en/docs/tutorial/cors.md", "symbol": "Use `CORSMiddleware` { #use-corsmiddleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cors.md#L35-L78", "start_line": 35, "end_line": 78} {"id": "docs/en/docs/tutorial/cors.md::More info { #more-info }::L79", "text": "# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: More info { #more-info }\n## More info { #more-info }\n\nFor more info about CORS, check the [Mozilla CORS documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).\n\n/// note | Technical Details\n\nYou could also use `from starlette.middleware.cors import CORSMiddleware`.\n\n**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/cors.md", "symbol": "More info { #more-info }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/cors.md#L79-L89", "start_line": 79, "end_line": 89} {"id": "docs/en/docs/tutorial/debugging.md::Debugging { #debugging }::L1", "text": "# Doc: docs/en/docs/tutorial/debugging.md | Page: Debugging { #debugging } | Section: Debugging { #debugging }\n# Debugging { #debugging }\n\nYou can connect the debugger in your editor, for example with Visual Studio Code or PyCharm.", "source_type": "doc", "path": "docs/en/docs/tutorial/debugging.md", "symbol": "Debugging { #debugging }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/debugging.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/debugging.md::Call `uvicorn` { #call-uvicorn }::L5", "text": "# Doc: docs/en/docs/tutorial/debugging.md | Page: Debugging { #debugging } | Section: Call `uvicorn` { #call-uvicorn }\n## Call `uvicorn` { #call-uvicorn }\n\nIn your FastAPI application, import and run `uvicorn` directly:\n\n{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}\n\n### About `__name__ == \"__main__\"` { #about-name-main }\n\nThe main purpose of the `__name__ == \"__main__\"` is to have some code that is executed when your file is called with:\n\n
\n\n```console\n$ python myapp.py\n```\n\n
\n\nbut is not called when another file imports it, like in:\n\n```Python\nfrom myapp import app\n```\n\n#### More details { #more-details }\n\nLet's say your file is named `myapp.py`.\n\nIf you run it with:\n\n
\n\n```console\n$ python myapp.py\n```\n\n
\n\nthen the internal variable `__name__` in your file, created automatically by Python, will have as value the string `\"__main__\"`.\n\nSo, the section:\n\n```Python\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\nwill run.\n\n---\n\nThis won't happen if you import that module (file).\n\nSo, if you have another file `importer.py` with:\n\n```Python\nfrom myapp import app\n\n# Some more code\n```\n\nin that case, the automatically created variable `__name__` inside of `myapp.py` will not have the value `\"__main__\"`.\n\nSo, the line:\n\n```Python\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\nwill not be executed.\n\n/// note\n\nFor more information, check [the official Python docs](https://docs.python.org/3/library/__main__.html).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/debugging.md", "symbol": "Call `uvicorn` { #call-uvicorn }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/debugging.md#L5-L80", "start_line": 5, "end_line": 80} {"id": "docs/en/docs/tutorial/debugging.md::Run your code with your debugger { #run-your-code-with-your-debugger }::L81", "text": "# Doc: docs/en/docs/tutorial/debugging.md | Page: Debugging { #debugging } | Section: Run your code with your debugger { #run-your-code-with-your-debugger }\n## Run your code with your debugger { #run-your-code-with-your-debugger }\n\nBecause you are running the Uvicorn server directly from your code, you can call your Python program (your FastAPI application) directly from the debugger.\n\n---\n\nFor example, in Visual Studio Code, you can:\n\n* Go to the \"Debug\" panel.\n* \"Add configuration...\".\n* Select \"Python\"\n* Run the debugger with the option \"`Python: Current File (Integrated Terminal)`\".\n\nIt will then start the server with your **FastAPI** code, stop at your breakpoints, etc.\n\nHere's how it might look:\n\n\n\n---\n\nIf you use PyCharm, you can:\n\n* Open the \"Run\" menu.\n* Select the option \"Debug...\".\n* Then a context menu shows up.\n* Select the file to debug (in this case, `main.py`).\n\nIt will then start the server with your **FastAPI** code, stop at your breakpoints, etc.\n\nHere's how it might look:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/debugging.md", "symbol": "Run your code with your debugger { #run-your-code-with-your-debugger }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/debugging.md#L81-L113", "start_line": 81, "end_line": 113} {"id": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Classes as Dependencies { #classes-as-dependencies }::L1", "text": "# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Classes as Dependencies { #classes-as-dependencies }\n# Classes as Dependencies { #classes-as-dependencies }\n\nBefore diving deeper into the **Dependency Injection** system, let's upgrade the previous example.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md", "symbol": "Classes as Dependencies { #classes-as-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::A `dict` from the previous example { #a-dict-from-the-previous-example }::L5", "text": "# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: A `dict` from the previous example { #a-dict-from-the-previous-example }\n## A `dict` from the previous example { #a-dict-from-the-previous-example }\n\nIn the previous example, we were returning a `dict` from our dependency (\"dependable\"):\n\n{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}\n\nBut then we get a `dict` in the parameter `commons` of the *path operation function*.\n\nAnd we know that editors can't provide a lot of support (like completion) for `dict`s, because they can't know their keys and value types.\n\nWe can do better...", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md", "symbol": "A `dict` from the previous example { #a-dict-from-the-previous-example }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L5-L16", "start_line": 5, "end_line": 16} {"id": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::What makes a dependency { #what-makes-a-dependency }::L17", "text": "# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: What makes a dependency { #what-makes-a-dependency }\n## What makes a dependency { #what-makes-a-dependency }\n\nUp to now you have seen dependencies declared as functions.\n\nBut that's not the only way to declare dependencies (although it would probably be the more common).\n\nThe key factor is that a dependency should be a \"callable\".\n\nA \"**callable**\" in Python is anything that Python can \"call\" like a function.\n\nSo, if you have an object `something` (that might _not_ be a function) and you can \"call\" it (execute it) like:\n\n```Python\nsomething()\n```\n\nor\n\n```Python\nsomething(some_argument, some_keyword_argument=\"foo\")\n```\n\nthen it is a \"callable\".", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md", "symbol": "What makes a dependency { #what-makes-a-dependency }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L17-L40", "start_line": 17, "end_line": 40} {"id": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Classes as dependencies { #classes-as-dependencies_1 }::L41", "text": "# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Classes as dependencies { #classes-as-dependencies_1 }\n## Classes as dependencies { #classes-as-dependencies_1 }\n\nYou might notice that to create an instance of a Python class, you use that same syntax.\n\nFor example:\n\n```Python\nclass Cat:\n def __init__(self, name: str):\n self.name = name\n\n\nfluffy = Cat(name=\"Mr Fluffy\")\n```\n\nIn this case, `fluffy` is an instance of the class `Cat`.\n\nAnd to create `fluffy`, you are \"calling\" `Cat`.\n\nSo, a Python class is also a **callable**.\n\nThen, in **FastAPI**, you could use a Python class as a dependency.\n\nWhat FastAPI actually checks is that it is a \"callable\" (function, class or anything else) and the parameters defined.\n\nIf you pass a \"callable\" as a dependency in **FastAPI**, it will analyze the parameters for that \"callable\", and process them in the same way as the parameters for a *path operation function*. Including sub-dependencies.\n\nThat also applies to callables with no parameters at all. The same as it would be for *path operation functions* with no parameters.\n\nThen, we can change the dependency \"dependable\" `common_parameters` from above to the class `CommonQueryParams`:\n\n{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}\n\nPay attention to the `__init__` method used to create the instance of the class:\n\n{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}\n\n...it has the same parameters as our previous `common_parameters`:\n\n{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}\n\nThose parameters are what **FastAPI** will use to \"solve\" the dependency.\n\nIn both cases, it will have:\n\n* An optional `q` query parameter that is a `str`.\n* A `skip` query parameter that is an `int`, with a default of `0`.\n* A `limit` query parameter that is an `int`, with a default of `100`.\n\nIn both cases the data will be converted, validated, documented on the OpenAPI schema, etc.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md", "symbol": "Classes as dependencies { #classes-as-dependencies_1 }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L41-L91", "start_line": 41, "end_line": 91} {"id": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Use it { #use-it }::L92", "text": "# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Use it { #use-it }\n## Use it { #use-it }\n\nNow you can declare your dependency using this class.\n\n{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}\n\n**FastAPI** calls the `CommonQueryParams` class. This creates an \"instance\" of that class and the instance will be passed as the parameter `commons` to your function.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md", "symbol": "Use it { #use-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L92-L99", "start_line": 92, "end_line": 99} {"id": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Type annotation vs `Depends` { #type-annotation-vs-depends }::L100", "text": "# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Type annotation vs `Depends` { #type-annotation-vs-depends }\n## Type annotation vs `Depends` { #type-annotation-vs-depends }\n\nNotice how we write `CommonQueryParams` twice in the above code:\n\n//// tab | Python 3.10+\n\n```Python\ncommons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]\n```\n\n////\n\n//// tab | Python 3.10+ non-Annotated\n\n/// tip\n\nPrefer to use the `Annotated` version if possible.\n\n///\n\n```Python\ncommons: CommonQueryParams = Depends(CommonQueryParams)\n```\n\n////\n\nThe last `CommonQueryParams`, in:\n\n```Python\n... Depends(CommonQueryParams)\n```\n\n...is what **FastAPI** will actually use to know what is the dependency.\n\nIt is from this one that FastAPI will extract the declared parameters and that is what FastAPI will actually call.\n\n---\n\nIn this case, the first `CommonQueryParams`, in:\n\n//// tab | Python 3.10+\n\n```Python\ncommons: Annotated[CommonQueryParams, ...\n```\n\n////\n\n//// tab | Python 3.10+ non-Annotated\n\n/// tip\n\nPrefer to use the `Annotated` version if possible.\n\n///\n\n```Python\ncommons: CommonQueryParams ...\n```\n\n////\n\n...doesn't have any special meaning for **FastAPI**. FastAPI won't use it for data conversion, validation, etc. (as it is using the `Depends(CommonQueryParams)` for that).\n\nYou could actually write just:\n\n//// tab | Python 3.10+\n\n```Python\ncommons: Annotated[Any, Depends(CommonQueryParams)]\n```\n\n////\n\n//// tab | Python 3.10+ non-Annotated\n\n/// tip\n\nPrefer to use the `Annotated` version if possible.\n\n///\n\n```Python\ncommons = Depends(CommonQueryParams)\n```\n\n////\n\n...as in:\n\n{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}\n\nBut declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md", "symbol": "Type annotation vs `Depends` { #type-annotation-vs-depends }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L100-L195", "start_line": 100, "end_line": 195} {"id": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Shortcut { #shortcut }::L196", "text": "# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Shortcut { #shortcut }\n## Shortcut { #shortcut }\n\nBut you see that we are having some code repetition here, writing `CommonQueryParams` twice:\n\n//// tab | Python 3.10+\n\n```Python\ncommons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]\n```\n\n////\n\n//// tab | Python 3.10+ non-Annotated\n\n/// tip\n\nPrefer to use the `Annotated` version if possible.\n\n///\n\n```Python\ncommons: CommonQueryParams = Depends(CommonQueryParams)\n```\n\n////\n\n**FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will \"call\" to create an instance of the class itself.\n\nFor those specific cases, you can do the following:\n\nInstead of writing:\n\n//// tab | Python 3.10+\n\n```Python\ncommons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]\n```\n\n////\n\n//// tab | Python 3.10+ non-Annotated\n\n/// tip\n\nPrefer to use the `Annotated` version if possible.\n\n///\n\n```Python\ncommons: CommonQueryParams = Depends(CommonQueryParams)\n```\n\n////\n\n...you write:\n\n//// tab | Python 3.10+\n\n```Python\ncommons: Annotated[CommonQueryParams, Depends()]\n```\n\n////\n\n//// tab | Python 3.10+ non-Annotated\n\n/// tip\n\nPrefer to use the `Annotated` version if possible.\n\n///\n\n```Python\ncommons: CommonQueryParams = Depends()\n```\n\n////\n\nYou declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.\n\nThe same example would then look like:\n\n{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}\n\n...and **FastAPI** will know what to do.\n\n/// tip\n\nIf that seems more confusing than helpful, disregard it, you don't *need* it.\n\nIt is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/classes-as-dependencies.md", "symbol": "Shortcut { #shortcut }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md#L196-L288", "start_line": 196, "end_line": 288} {"id": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }::L1", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }\n# Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }\n\nIn some cases you don't really need the return value of a dependency inside your *path operation function*.\n\nOr the dependency doesn't return a value.\n\nBut you still need it to be executed/solved.\n\nFor those cases, instead of declaring a *path operation function* parameter with `Depends`, you can add a `list` of `dependencies` to the *path operation decorator*.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md", "symbol": "Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md#L1-L10", "start_line": 1, "end_line": 10} {"id": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }::L11", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }\n## Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }\n\nThe *path operation decorator* receives an optional argument `dependencies`.\n\nIt should be a `list` of `Depends()`:\n\n{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}\n\nThese dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.\n\n/// tip\n\nSome editors check for unused function parameters, and show them as errors.\n\nUsing these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors.\n\nIt might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary.\n\n///\n\n/// note\n\nIn this example we use invented custom headers `X-Key` and `X-Token`.\n\nBut in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md", "symbol": "Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md#L11-L38", "start_line": 11, "end_line": 38} {"id": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Dependencies errors and return values { #dependencies-errors-and-return-values }::L39", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Dependencies errors and return values { #dependencies-errors-and-return-values }\n## Dependencies errors and return values { #dependencies-errors-and-return-values }\n\nYou can use the same dependency *functions* you use normally.\n\n### Dependency requirements { #dependency-requirements }\n\nThey can declare request requirements (like headers) or other sub-dependencies:\n\n{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}\n\n### Raise exceptions { #raise-exceptions }\n\nThese dependencies can `raise` exceptions, the same as normal dependencies:\n\n{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}\n\n### Return values { #return-values }\n\nAnd they can return values or not, the values won't be used.\n\nSo, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:\n\n{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md", "symbol": "Dependencies errors and return values { #dependencies-errors-and-return-values }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md#L39-L62", "start_line": 39, "end_line": 62} {"id": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }::L63", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }\n## Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }\n\nLater, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md", "symbol": "Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md#L63-L66", "start_line": 63, "end_line": 66} {"id": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Global Dependencies { #global-dependencies }::L67", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Global Dependencies { #global-dependencies }\n## Global Dependencies { #global-dependencies }\n\nNext we will see how to add dependencies to the whole `FastAPI` application, so that they apply to each *path operation*.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md", "symbol": "Global Dependencies { #global-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md#L67-L69", "start_line": 67, "end_line": 69} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with yield { #dependencies-with-yield }::L1", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with yield { #dependencies-with-yield }\n# Dependencies with yield { #dependencies-with-yield }\n\nFastAPI supports dependencies that do some extra steps after finishing.\n\nTo do this, use `yield` instead of `return`, and write the extra steps (code) after.\n\n/// tip\n\nMake sure to use `yield` one single time per dependency.\n\n///\n\n/// note | Technical Details\n\nAny function that is valid to use with:\n\n* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) or\n* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)\n\nwould be valid to use as a **FastAPI** dependency.\n\nIn fact, FastAPI uses those two decorators internally.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Dependencies with yield { #dependencies-with-yield }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L1-L25", "start_line": 1, "end_line": 25} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::A database dependency with `yield` { #a-database-dependency-with-yield }::L26", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: A database dependency with `yield` { #a-database-dependency-with-yield }\n## A database dependency with `yield` { #a-database-dependency-with-yield }\n\nFor example, you could use this to create a database session and close it after finishing.\n\nOnly the code prior to and including the `yield` statement is executed before creating a response:\n\n{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}\n\nThe yielded value is what is injected into *path operations* and other dependencies:\n\n{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}\n\nThe code following the `yield` statement is executed after the response:\n\n{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}\n\n/// tip\n\nYou can use `async` or regular functions.\n\n**FastAPI** will do the right thing with each, the same as with normal dependencies.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "A database dependency with `yield` { #a-database-dependency-with-yield }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L26-L49", "start_line": 26, "end_line": 49} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }::L50", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }\n## A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }\n\nIf you use a `try` block in a dependency with `yield`, you'll receive any exception that was thrown when using the dependency.\n\nFor example, if some code at some point in the middle, in another dependency or in a *path operation*, made a database transaction \"rollback\" or created any other exception, you would receive the exception in your dependency.\n\nSo, you can look for that specific exception inside the dependency with `except SomeException`.\n\nIn the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not.\n\n{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L50-L61", "start_line": 50, "end_line": 61} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Sub-dependencies with `yield` { #sub-dependencies-with-yield }::L62", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Sub-dependencies with `yield` { #sub-dependencies-with-yield }\n## Sub-dependencies with `yield` { #sub-dependencies-with-yield }\n\nYou can have sub-dependencies and \"trees\" of sub-dependencies of any size and shape, and any or all of them can use `yield`.\n\n**FastAPI** will make sure that the \"exit code\" in each dependency with `yield` is run in the correct order.\n\nFor example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`:\n\n{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}\n\nAnd all of them can use `yield`.\n\nIn this case `dependency_c`, to execute its exit code, needs the value from `dependency_b` (here named `dep_b`) to still be available.\n\nAnd, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.\n\n{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}\n\nThe same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others.\n\nAnd you could have a single dependency that requires several other dependencies with `yield`, etc.\n\nYou can have any combinations of dependencies that you want.\n\n**FastAPI** will make sure everything is run in the correct order.\n\n/// note | Technical Details\n\nThis works thanks to Python's [Context Managers](https://docs.python.org/3/library/contextlib.html).\n\n**FastAPI** uses them internally to achieve this.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Sub-dependencies with `yield` { #sub-dependencies-with-yield }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L62-L95", "start_line": 62, "end_line": 95} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }::L96", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }\n## Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }\n\nYou saw that you can use dependencies with `yield` and have `try` blocks that try to execute some code and then run some exit code after `finally`.\n\nYou can also use `except` to catch the exception that was raised and do something with it.\n\nFor example, you can raise a different exception, like `HTTPException`.\n\n/// tip\n\nThis is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*.\n\nBut it's there for you if you need it. 🤓\n\n///\n\n{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}\n\nIf you want to catch exceptions and create a custom response based on that, create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers).", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L96-L115", "start_line": 96, "end_line": 115} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }::L116", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }\n## Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }\n\nIf you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python:\n\n{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}\n\nIn this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱\n\n### Always `raise` in Dependencies with `yield` and `except` { #always-raise-in-dependencies-with-yield-and-except }\n\nIf you catch an exception in a dependency with `yield`, unless you are raising another `HTTPException` or similar, **you should re-raise the original exception**.\n\nYou can re-raise the same exception using `raise`:\n\n{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}\n\nNow the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L116-L133", "start_line": 116, "end_line": 133} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }::L134", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }\n## Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }\n\nThe sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code.\n\n```mermaid\nsequenceDiagram\n\nparticipant client as Client\nparticipant handler as Exception handler\nparticipant dep as Dep with yield\nparticipant operation as Path Operation\nparticipant tasks as Background tasks\n\n Note over client,operation: Can raise exceptions, including HTTPException\n client ->> dep: Start request\n Note over dep: Run code up to yield\n opt raise Exception\n dep -->> handler: Raise Exception\n handler -->> client: HTTP error response\n end\n dep ->> operation: Run dependency, e.g. DB session\n opt raise\n operation -->> dep: Raise Exception (e.g. HTTPException)\n opt handle\n dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception\n end\n handler -->> client: HTTP error response\n end\n\n operation ->> client: Return response to client\n Note over client,operation: Response is already sent, can't change it anymore\n opt Tasks\n operation -->> tasks: Send background tasks\n end\n opt Raise other exception\n tasks -->> tasks: Handle exceptions in the background task code\n end\n```\n\n/// note\n\nOnly **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*.\n\nAfter one of those responses is sent, no other response can be sent.\n\n///\n\n/// tip\n\nIf you raise any exception in the code from the *path operation function*, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L134-L186", "start_line": 134, "end_line": 186} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Early exit and `scope` { #early-exit-and-scope }::L187", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Early exit and `scope` { #early-exit-and-scope }\n## Early exit and `scope` { #early-exit-and-scope }\n\nNormally the exit code of dependencies with `yield` is executed **after the response** is sent to the client.\n\nBut if you know that you won't need to use the dependency after returning from the *path operation function*, you can use `Depends(scope=\"function\")` to tell FastAPI that it should close the dependency after the *path operation function* returns, but **before** the **response is sent**.\n\n{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}\n\n`Depends()` receives a `scope` parameter that can be:\n\n* `\"function\"`: start the dependency before the *path operation function* that handles the request, end the dependency after the *path operation function* ends, but **before** the response is sent back to the client. So, the dependency function will be executed **around** the *path operation **function***.\n* `\"request\"`: start the dependency before the *path operation function* that handles the request (similar to when using `\"function\"`), but end **after** the response is sent back to the client. So, the dependency function will be executed **around** the **request** and response cycle.\n\nIf not specified and the dependency has `yield`, it will have a `scope` of `\"request\"` by default.\n\n### `scope` for sub-dependencies { #scope-for-sub-dependencies }\n\nWhen you declare a dependency with a `scope=\"request\"` (the default), any sub-dependency needs to also have a `scope` of `\"request\"`.\n\nBut a dependency with `scope` of `\"function\"` can have dependencies with `scope` of `\"function\"` and `scope` of `\"request\"`.\n\nThis is because any dependency needs to be able to run its exit code before the sub-dependencies, as it might need to still use them during its exit code.\n\n```mermaid\nsequenceDiagram\n\nparticipant client as Client\nparticipant dep_req as Dep scope=\"request\"\nparticipant dep_func as Dep scope=\"function\"\nparticipant operation as Path Operation\n\n client ->> dep_req: Start request\n Note over dep_req: Run code up to yield\n dep_req ->> dep_func: Pass dependency\n Note over dep_func: Run code up to yield\n dep_func ->> operation: Run path operation with dependency\n operation ->> dep_func: Return from path operation\n Note over dep_func: Run code after yield\n Note over dep_func: ✅ Dependency closed\n dep_func ->> client: Send response to client\n Note over client: Response sent\n Note over dep_req: Run code after yield\n Note over dep_req: ✅ Dependency closed\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Early exit and `scope` { #early-exit-and-scope }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L187-L231", "start_line": 187, "end_line": 231} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }::L232", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }\n## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }\n\nDependencies with `yield` have evolved over time to cover different use cases and fix some issues.\n\nIf you want to see what has changed in different versions of FastAPI, you can read more about it in the advanced guide, in [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L232-L237", "start_line": 232, "end_line": 237} {"id": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Context Managers { #context-managers }::L238", "text": "# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Context Managers { #context-managers }\n## Context Managers { #context-managers }\n\n### What are \"Context Managers\" { #what-are-context-managers }\n\n\"Context Managers\" are any of those Python objects that you can use in a `with` statement.\n\nFor example, [you can use `with` to read a file](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):\n\n```Python\nwith open(\"./somefile.txt\") as f:\n contents = f.read()\n print(contents)\n```\n\nUnderneath, the `open(\"./somefile.txt\")` creates an object that is called a \"Context Manager\".\n\nWhen the `with` block finishes, it makes sure to close the file, even if there were exceptions.\n\nWhen you create a dependency with `yield`, **FastAPI** will internally create a context manager for it, and combine it with some other related tools.\n\n### Using context managers in dependencies with `yield` { #using-context-managers-in-dependencies-with-yield }\n\n/// warning\n\nThis is, more or less, an \"advanced\" idea.\n\nIf you are just starting with **FastAPI** you might want to skip it for now.\n\n///\n\nIn Python, you can create Context Managers by [creating a class with two methods: `__enter__()` and `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).\n\nYou can also use them inside of **FastAPI** dependencies with `yield` by using\n`with` or `async with` statements inside of the dependency function:\n\n{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}\n\n/// tip\n\nAnother way to create a context manager is with:\n\n* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) or\n* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)\n\nusing them to decorate a function with a single `yield`.\n\nThat's what **FastAPI** uses internally for dependencies with `yield`.\n\nBut you don't have to use the decorators for FastAPI dependencies (and you shouldn't).\n\nFastAPI will do it for you internally.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/dependencies-with-yield.md", "symbol": "Context Managers { #context-managers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md#L238-L290", "start_line": 238, "end_line": 290} {"id": "docs/en/docs/tutorial/dependencies/global-dependencies.md::Global Dependencies { #global-dependencies }::L1", "text": "# Doc: docs/en/docs/tutorial/dependencies/global-dependencies.md | Page: Global Dependencies { #global-dependencies } | Section: Global Dependencies { #global-dependencies }\n# Global Dependencies { #global-dependencies }\n\nFor some types of applications you might want to add dependencies to the whole application.\n\nSimilar to the way you can [add `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md), you can add them to the `FastAPI` application.\n\nIn that case, they will be applied to all the *path operations* in the application:\n\n{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}\n\n\nAnd all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md) still apply, but in this case, to all of the *path operations* in the app.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/global-dependencies.md", "symbol": "Global Dependencies { #global-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/global-dependencies.md#L1-L13", "start_line": 1, "end_line": 13} {"id": "docs/en/docs/tutorial/dependencies/global-dependencies.md::Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }::L14", "text": "# Doc: docs/en/docs/tutorial/dependencies/global-dependencies.md | Page: Global Dependencies { #global-dependencies } | Section: Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }\n## Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }\n\nLater, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/global-dependencies.md", "symbol": "Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/global-dependencies.md#L14-L16", "start_line": 14, "end_line": 16} {"id": "docs/en/docs/tutorial/dependencies/index.md::Dependencies { #dependencies }::L1", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Dependencies { #dependencies }\n# Dependencies { #dependencies }\n\n**FastAPI** has a very powerful but intuitive **Dependency Injection** system.\n\nIt is designed to be very simple to use, and to make it very easy for any developer to integrate other components with **FastAPI**.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "Dependencies { #dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/tutorial/dependencies/index.md::What is \"Dependency Injection\" { #what-is-dependency-injection }::L7", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: What is \"Dependency Injection\" { #what-is-dependency-injection }\n## What is \"Dependency Injection\" { #what-is-dependency-injection }\n\n**\"Dependency Injection\"** means, in programming, that there is a way for your code (in this case, your *path operation functions*) to declare things that it requires to work and use: \"dependencies\".\n\nAnd then, that system (in this case **FastAPI**) will take care of doing whatever is needed to provide your code with those needed dependencies (\"inject\" the dependencies).\n\nThis is very useful when you need to:\n\n* Have shared logic (the same code logic again and again).\n* Share database connections.\n* Enforce security, authentication, role requirements, etc.\n* And many other things...\n\nAll these, while minimizing code repetition.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "What is \"Dependency Injection\" { #what-is-dependency-injection }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L7-L21", "start_line": 7, "end_line": 21} {"id": "docs/en/docs/tutorial/dependencies/index.md::First Steps { #first-steps }::L22", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: First Steps { #first-steps }\n## First Steps { #first-steps }\n\nLet's see a very simple example. It will be so simple that it is not very useful, for now.\n\nBut this way we can focus on how the **Dependency Injection** system works.\n\n### Create a dependency, or \"dependable\" { #create-a-dependency-or-dependable }\n\nLet's first focus on the dependency.\n\nIt is just a function that can take all the same parameters that a *path operation function* can take:\n\n{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}\n\nThat's it.\n\n**2 lines**.\n\nAnd it has the same shape and structure that all your *path operation functions* have.\n\nYou can think of it as a *path operation function* without the \"decorator\" (without the `@app.get(\"/some-path\")`).\n\nAnd it can return anything you want.\n\nIn this case, this dependency expects:\n\n* An optional query parameter `q` that is a `str`.\n* An optional query parameter `skip` that is an `int`, and by default is `0`.\n* An optional query parameter `limit` that is an `int`, and by default is `100`.\n\nAnd then it just returns a `dict` containing those values.\n\n/// note\n\nFastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.\n\nIf you have an older version, you would get errors when trying to use `Annotated`.\n\nMake sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions) to at least 0.95.1 before using `Annotated`.\n\n///\n\n### Import `Depends` { #import-depends }\n\n{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}\n\n### Declare the dependency, in the \"dependant\" { #declare-the-dependency-in-the-dependant }\n\nThe same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter:\n\n{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}\n\nAlthough you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently.\n\nYou only give `Depends` a single parameter.\n\nThis parameter must be something like a function.\n\nYou **don't call it** directly (don't add the parenthesis at the end), you just pass it as a parameter to `Depends()`.\n\nAnd that function takes parameters in the same way that *path operation functions* do.\n\n/// tip\n\nYou'll see what other \"things\", apart from functions, can be used as dependencies in the next chapter.\n\n///\n\nWhenever a new request arrives, **FastAPI** will take care of:\n\n* Calling your dependency (\"dependable\") function with the correct parameters.\n* Get the result from your function.\n* Assign that result to the parameter in your *path operation function*.\n\n```mermaid\ngraph TB\n\ncommon_parameters([\"common_parameters\"])\nread_items[\"/items/\"]\nread_users[\"/users/\"]\n\ncommon_parameters --> read_items\ncommon_parameters --> read_users\n```\n\nThis way you write shared code once and **FastAPI** takes care of calling it for your *path operations*.\n\n/// tip\n\nNotice that you don't have to create a special class and pass it somewhere to **FastAPI** to \"register\" it or anything similar.\n\nYou just pass it to `Depends` and **FastAPI** knows how to do the rest.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "First Steps { #first-steps }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L22-L116", "start_line": 22, "end_line": 116} {"id": "docs/en/docs/tutorial/dependencies/index.md::Share `Annotated` dependencies { #share-annotated-dependencies }::L117", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Share `Annotated` dependencies { #share-annotated-dependencies }\n## Share `Annotated` dependencies { #share-annotated-dependencies }\n\nIn the examples above, you see that there's a tiny bit of **code duplication**.\n\nWhen you need to use the `common_parameters()` dependency, you have to write the whole parameter with the type annotation and `Depends()`:\n\n```Python\ncommons: Annotated[dict, Depends(common_parameters)]\n```\n\nBut because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places:\n\n{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}\n\n/// tip\n\nThis is just standard Python, it's called a \"type alias\", it's actually not specific to **FastAPI**.\n\nBut because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎\n\n///\n\nThe dependencies will keep working as expected, and the **best part** is that the **type information will be preserved**, which means that your editor will be able to keep providing you with **autocompletion**, **inline errors**, etc. The same for other tools like `mypy`.\n\nThis will be especially useful when you use it in a **large code base** where you use **the same dependencies** over and over again in **many *path operations***.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "Share `Annotated` dependencies { #share-annotated-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L117-L142", "start_line": 117, "end_line": 142} {"id": "docs/en/docs/tutorial/dependencies/index.md::To `async` or not to `async` { #to-async-or-not-to-async }::L143", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: To `async` or not to `async` { #to-async-or-not-to-async }\n## To `async` or not to `async` { #to-async-or-not-to-async }\n\nAs dependencies will also be called by **FastAPI** (the same as your *path operation functions*), the same rules apply while defining your functions.\n\nYou can use `async def` or normal `def`.\n\nAnd you can declare dependencies with `async def` inside of normal `def` *path operation functions*, or `def` dependencies inside of `async def` *path operation functions*, etc.\n\nIt doesn't matter. **FastAPI** will know what to do.\n\n/// note\n\nIf you don't know, check the [Async: *\"In a hurry?\"*](../../async.md#in-a-hurry) section about `async` and `await` in the docs.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "To `async` or not to `async` { #to-async-or-not-to-async }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L143-L158", "start_line": 143, "end_line": 158} {"id": "docs/en/docs/tutorial/dependencies/index.md::Integrated with OpenAPI { #integrated-with-openapi }::L159", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Integrated with OpenAPI { #integrated-with-openapi }\n## Integrated with OpenAPI { #integrated-with-openapi }\n\nAll the request declarations, validations and requirements of your dependencies (and sub-dependencies) will be integrated in the same OpenAPI schema.\n\nSo, the interactive docs will have all the information from these dependencies too:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "Integrated with OpenAPI { #integrated-with-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L159-L166", "start_line": 159, "end_line": 166} {"id": "docs/en/docs/tutorial/dependencies/index.md::Simple usage { #simple-usage }::L167", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Simple usage { #simple-usage }\n## Simple usage { #simple-usage }\n\nIf you look at it, *path operation functions* are declared to be used whenever a *path* and *operation* matches, and then **FastAPI** takes care of calling the function with the correct parameters, extracting the data from the request.\n\nActually, all (or most) of the web frameworks work in this same way.\n\nYou never call those functions directly. They are called by your framework (in this case, **FastAPI**).\n\nWith the Dependency Injection system, you can also tell **FastAPI** that your *path operation function* also \"depends\" on something else that should be executed before your *path operation function*, and **FastAPI** will take care of executing it and \"injecting\" the results.\n\nOther common terms for this same idea of \"dependency injection\" are:\n\n* resources\n* providers\n* services\n* injectables\n* components", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "Simple usage { #simple-usage }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L167-L184", "start_line": 167, "end_line": 184} {"id": "docs/en/docs/tutorial/dependencies/index.md::**FastAPI** plug-ins { #fastapi-plug-ins }::L185", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: **FastAPI** plug-ins { #fastapi-plug-ins }\n## **FastAPI** plug-ins { #fastapi-plug-ins }\n\nIntegrations and \"plug-ins\" can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create \"plug-ins\"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*.\n\nAnd dependencies can be created in a very simple and intuitive way that allows you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*.\n\nYou will see examples of this in the next chapters, about relational and NoSQL databases, security, etc.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "**FastAPI** plug-ins { #fastapi-plug-ins }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L185-L192", "start_line": 185, "end_line": 192} {"id": "docs/en/docs/tutorial/dependencies/index.md::**FastAPI** compatibility { #fastapi-compatibility }::L193", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: **FastAPI** compatibility { #fastapi-compatibility }\n## **FastAPI** compatibility { #fastapi-compatibility }\n\nThe simplicity of the dependency injection system makes **FastAPI** compatible with:\n\n* all the relational databases\n* NoSQL databases\n* external packages\n* external APIs\n* authentication and authorization systems\n* API usage monitoring systems\n* response data injection systems\n* etc.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "**FastAPI** compatibility { #fastapi-compatibility }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L193-L205", "start_line": 193, "end_line": 205} {"id": "docs/en/docs/tutorial/dependencies/index.md::Simple and Powerful { #simple-and-powerful }::L206", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Simple and Powerful { #simple-and-powerful }\n## Simple and Powerful { #simple-and-powerful }\n\nAlthough the hierarchical dependency injection system is very simple to define and use, it's still very powerful.\n\nYou can define dependencies that in turn can define dependencies themselves.\n\nIn the end, a hierarchical tree of dependencies is built, and the **Dependency Injection** system takes care of solving all these dependencies for you (and their sub-dependencies) and providing (injecting) the results at each step.\n\nFor example, let's say you have 4 API endpoints (*path operations*):\n\n* `/items/public/`\n* `/items/private/`\n* `/users/{user_id}/activate`\n* `/items/pro/`\n\nthen you could add different permission requirements for each of them just with dependencies and sub-dependencies:\n\n```mermaid\ngraph TB\n\ncurrent_user([\"current_user\"])\nactive_user([\"active_user\"])\nadmin_user([\"admin_user\"])\npaying_user([\"paying_user\"])\n\npublic[\"/items/public/\"]\nprivate[\"/items/private/\"]\nactivate_user[\"/users/{user_id}/activate\"]\npro_items[\"/items/pro/\"]\n\ncurrent_user --> active_user\nactive_user --> admin_user\nactive_user --> paying_user\n\ncurrent_user --> public\nactive_user --> private\nadmin_user --> activate_user\npaying_user --> pro_items\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "Simple and Powerful { #simple-and-powerful }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L206-L245", "start_line": 206, "end_line": 245} {"id": "docs/en/docs/tutorial/dependencies/index.md::Integrated with **OpenAPI** { #integrated-with-openapi_1 }::L246", "text": "# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Integrated with **OpenAPI** { #integrated-with-openapi_1 }\n## Integrated with **OpenAPI** { #integrated-with-openapi_1 }\n\nAll these dependencies, while declaring their requirements, also add parameters, validations, etc. to your *path operations*.\n\n**FastAPI** will take care of adding it all to the OpenAPI schema, so that it is shown in the interactive documentation systems.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/index.md", "symbol": "Integrated with **OpenAPI** { #integrated-with-openapi_1 }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/index.md#L246-L250", "start_line": 246, "end_line": 250} {"id": "docs/en/docs/tutorial/dependencies/sub-dependencies.md::Sub-dependencies { #sub-dependencies }::L1", "text": "# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Sub-dependencies { #sub-dependencies }\n# Sub-dependencies { #sub-dependencies }\n\nYou can create dependencies that have **sub-dependencies**.\n\nThey can be as **deep** as you need them to be.\n\n**FastAPI** will take care of solving them.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/sub-dependencies.md", "symbol": "Sub-dependencies { #sub-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/sub-dependencies.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/tutorial/dependencies/sub-dependencies.md::First dependency \"dependable\" { #first-dependency-dependable }::L9", "text": "# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: First dependency \"dependable\" { #first-dependency-dependable }\n## First dependency \"dependable\" { #first-dependency-dependable }\n\nYou could create a first dependency (\"dependable\") like:\n\n{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}\n\nIt declares an optional query parameter `q` as a `str`, and then it just returns it.\n\nThis is quite simple (not very useful), but will help us focus on how the sub-dependencies work.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/sub-dependencies.md", "symbol": "First dependency \"dependable\" { #first-dependency-dependable }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/sub-dependencies.md#L9-L18", "start_line": 9, "end_line": 18} {"id": "docs/en/docs/tutorial/dependencies/sub-dependencies.md::Second dependency, \"dependable\" and \"dependant\" { #second-dependency-dependable-and-dependant }::L19", "text": "# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Second dependency, \"dependable\" and \"dependant\" { #second-dependency-dependable-and-dependant }\n## Second dependency, \"dependable\" and \"dependant\" { #second-dependency-dependable-and-dependant }\n\nThen you can create another dependency function (a \"dependable\") that at the same time declares a dependency of its own (so it is a \"dependant\" too):\n\n{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}\n\nLet's focus on the parameters declared:\n\n* Even though this function is a dependency (\"dependable\") itself, it also declares another dependency (it \"depends\" on something else).\n * It depends on the `query_extractor`, and assigns the value returned by it to the parameter `q`.\n* It also declares an optional `last_query` cookie, as a `str`.\n * If the user didn't provide any query `q`, we use the last query used, which we saved to a cookie before.", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/sub-dependencies.md", "symbol": "Second dependency, \"dependable\" and \"dependant\" { #second-dependency-dependable-and-dependant }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/sub-dependencies.md#L19-L31", "start_line": 19, "end_line": 31} {"id": "docs/en/docs/tutorial/dependencies/sub-dependencies.md::Use the dependency { #use-the-dependency }::L32", "text": "# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Use the dependency { #use-the-dependency }\n## Use the dependency { #use-the-dependency }\n\nThen we can use the dependency with:\n\n{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}\n\n/// note\n\nNotice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.\n\nBut **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it.\n\n///\n\n```mermaid\ngraph TB\n\nquery_extractor([\"query_extractor\"])\nquery_or_cookie_extractor([\"query_or_cookie_extractor\"])\n\nread_query[\"/items/\"]\n\nquery_extractor --> query_or_cookie_extractor --> read_query\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/sub-dependencies.md", "symbol": "Use the dependency { #use-the-dependency }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/sub-dependencies.md#L32-L56", "start_line": 32, "end_line": 56} {"id": "docs/en/docs/tutorial/dependencies/sub-dependencies.md::Using the same dependency multiple times { #using-the-same-dependency-multiple-times }::L57", "text": "# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Using the same dependency multiple times { #using-the-same-dependency-multiple-times }\n## Using the same dependency multiple times { #using-the-same-dependency-multiple-times }\n\nIf one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request.\n\nAnd it will save the returned value in a \"cache\" and pass it to all the \"dependants\" that need it in that specific request, instead of calling the dependency multiple times for the same request.\n\nIn an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the \"cached\" value, you can set the parameter `use_cache=False` when using `Depends`:\n\n//// tab | Python 3.10+\n\n```Python hl_lines=\"1\"\nasync def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):\n return {\"fresh_value\": fresh_value}\n```\n\n////\n\n//// tab | Python 3.10+ non-Annotated\n\n/// tip\n\nPrefer to use the `Annotated` version if possible.\n\n///\n\n```Python hl_lines=\"1\"\nasync def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):\n return {\"fresh_value\": fresh_value}\n```\n\n////", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/sub-dependencies.md", "symbol": "Using the same dependency multiple times { #using-the-same-dependency-multiple-times }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/sub-dependencies.md#L57-L88", "start_line": 57, "end_line": 88} {"id": "docs/en/docs/tutorial/dependencies/sub-dependencies.md::Recap { #recap }::L89", "text": "# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Recap { #recap }\n## Recap { #recap }\n\nApart from all the fancy words used here, the **Dependency Injection** system is quite simple.\n\nJust functions that look the same as the *path operation functions*.\n\nBut still, it is very powerful, and allows you to declare arbitrarily deeply nested dependency \"graphs\" (trees).\n\n/// tip\n\nAll this might not seem as useful with these simple examples.\n\nBut you will see how useful it is in the chapters about **security**.\n\nAnd you will also see the amounts of code it will save you.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/dependencies/sub-dependencies.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/dependencies/sub-dependencies.md#L89-L105", "start_line": 89, "end_line": 105} {"id": "docs/en/docs/tutorial/encoder.md::JSON Compatible Encoder { #json-compatible-encoder }::L1", "text": "# Doc: docs/en/docs/tutorial/encoder.md | Page: JSON Compatible Encoder { #json-compatible-encoder } | Section: JSON Compatible Encoder { #json-compatible-encoder }\n# JSON Compatible Encoder { #json-compatible-encoder }\n\nThere are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a `dict`, `list`, etc).\n\nFor example, if you need to store it in a database.\n\nFor that, **FastAPI** provides a `jsonable_encoder()` function.", "source_type": "doc", "path": "docs/en/docs/tutorial/encoder.md", "symbol": "JSON Compatible Encoder { #json-compatible-encoder }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/encoder.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/tutorial/encoder.md::Using the `jsonable_encoder` { #using-the-jsonable-encoder }::L9", "text": "# Doc: docs/en/docs/tutorial/encoder.md | Page: JSON Compatible Encoder { #json-compatible-encoder } | Section: Using the `jsonable_encoder` { #using-the-jsonable-encoder }\n## Using the `jsonable_encoder` { #using-the-jsonable-encoder }\n\nLet's imagine that you have a database `fake_db` that only receives JSON compatible data.\n\nFor example, it doesn't receive `datetime` objects, as those are not compatible with JSON.\n\nSo, a `datetime` object would have to be converted to a `str` containing the data in [ISO format](https://en.wikipedia.org/wiki/ISO_8601).\n\nThe same way, this database wouldn't receive a Pydantic model (an object with attributes), only a `dict`.\n\nYou can use `jsonable_encoder` for that.\n\nIt receives an object, like a Pydantic model, and returns a JSON compatible version:\n\n{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}\n\nIn this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`.\n\nThe result of calling it is something that can be encoded with the Python standard [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).\n\nIt doesn't return a large `str` containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a `dict`) with values and sub-values that are all compatible with JSON.\n\n/// note\n\n`jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/encoder.md", "symbol": "Using the `jsonable_encoder` { #using-the-jsonable-encoder }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/encoder.md#L9-L35", "start_line": 9, "end_line": 35} {"id": "docs/en/docs/tutorial/extra-data-types.md::Extra Data Types { #extra-data-types }::L1", "text": "# Doc: docs/en/docs/tutorial/extra-data-types.md | Page: Extra Data Types { #extra-data-types } | Section: Extra Data Types { #extra-data-types }\n# Extra Data Types { #extra-data-types }\n\nUp to now, you have been using common data types, like:\n\n* `int`\n* `float`\n* `str`\n* `bool`\n\nBut you can also use more complex data types.\n\nAnd you will still have the same features as seen up to now:\n\n* Great editor support.\n* Data conversion from incoming requests.\n* Data conversion for response data.\n* Data validation.\n* Automatic annotation and documentation.", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-data-types.md", "symbol": "Extra Data Types { #extra-data-types }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-data-types.md#L1-L19", "start_line": 1, "end_line": 19} {"id": "docs/en/docs/tutorial/extra-data-types.md::Other data types { #other-data-types }::L20", "text": "# Doc: docs/en/docs/tutorial/extra-data-types.md | Page: Extra Data Types { #extra-data-types } | Section: Other data types { #other-data-types }\n## Other data types { #other-data-types }\n\nHere are some of the additional data types you can use:\n\n* `UUID`:\n * A standard \"Universally Unique Identifier\", common as an ID in many databases and systems.\n * In requests and responses will be represented as a `str`.\n* `datetime.datetime`:\n * A Python `datetime.datetime`.\n * In requests and responses will be represented as a `str` in ISO 8601 format, like: `2008-09-15T15:53:00+05:00`.\n* `datetime.date`:\n * Python `datetime.date`.\n * In requests and responses will be represented as a `str` in ISO 8601 format, like: `2008-09-15`.\n* `datetime.time`:\n * A Python `datetime.time`.\n * In requests and responses will be represented as a `str` in ISO 8601 format, like: `14:23:55.003`.\n* `datetime.timedelta`:\n * A Python `datetime.timedelta`.\n * In requests and responses will be represented as a `float` of total seconds.\n * Pydantic also allows representing it as an \"ISO 8601 time diff encoding\", [see the docs for more info](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).\n* `frozenset`:\n * In requests and responses, treated the same as a `set`:\n * In requests, a list will be read, eliminating duplicates and converting it to a `set`.\n * In responses, the `set` will be converted to a `list`.\n * The generated schema will specify that the `set` values are unique (using JSON Schema's `uniqueItems`).\n* `bytes`:\n * Standard Python `bytes`.\n * In requests and responses will be treated as `str`.\n * The generated schema will specify that it's a `str` with `binary` \"format\".\n* `Decimal`:\n * Standard Python `Decimal`.\n * In requests and responses, handled the same as a `float`.\n* You can check all the valid Pydantic data types here: [Pydantic data types](https://docs.pydantic.dev/latest/usage/types/types/).", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-data-types.md", "symbol": "Other data types { #other-data-types }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-data-types.md#L20-L53", "start_line": 20, "end_line": 53} {"id": "docs/en/docs/tutorial/extra-data-types.md::Example { #example }::L54", "text": "# Doc: docs/en/docs/tutorial/extra-data-types.md | Page: Extra Data Types { #extra-data-types } | Section: Example { #example }\n## Example { #example }\n\nHere's an example *path operation* with parameters using some of the above types.\n\n{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}\n\nNote that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like:\n\n{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-data-types.md", "symbol": "Example { #example }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-data-types.md#L54-L62", "start_line": 54, "end_line": 62} {"id": "docs/en/docs/tutorial/extra-models.md::Extra Models { #extra-models }::L1", "text": "# Doc: docs/en/docs/tutorial/extra-models.md | Page: Extra Models { #extra-models } | Section: Extra Models { #extra-models }\n# Extra Models { #extra-models }\n\nContinuing with the previous example, it will be common to have more than one related model.\n\nThis is especially the case for user models, because:\n\n* The **input model** needs to be able to have a password.\n* The **output model** should not have a password.\n* The **database model** would probably need to have a hashed password.\n\n/// danger\n\nNever store user's plaintext passwords. Always store a \"secure hash\" that you can then verify.\n\nIf you don't know, you will learn what a \"password hash\" is in the [security chapters](security/simple-oauth2.md#password-hashing).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-models.md", "symbol": "Extra Models { #extra-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-models.md#L1-L18", "start_line": 1, "end_line": 18} {"id": "docs/en/docs/tutorial/extra-models.md::Multiple models { #multiple-models }::L19", "text": "# Doc: docs/en/docs/tutorial/extra-models.md | Page: Extra Models { #extra-models } | Section: Multiple models { #multiple-models }\n## Multiple models { #multiple-models }\n\nHere's a general idea of what the models could look like with their password fields and the places where they are used:\n\n{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}\n\n### About `**user_in.model_dump()` { #about-user-in-model-dump }\n\n#### Pydantic's `.model_dump()` { #pydantics-model-dump }\n\n`user_in` is a Pydantic model of class `UserIn`.\n\nPydantic models have a `.model_dump()` method that returns a `dict` with the model's data.\n\nSo, if we create a Pydantic object `user_in` like:\n\n```Python\nuser_in = UserIn(username=\"john\", password=\"secret\", email=\"john.doe@example.com\")\n```\n\nand then we call:\n\n```Python\nuser_dict = user_in.model_dump()\n```\n\nwe now have a `dict` with the data in the variable `user_dict` (it's a `dict` instead of a Pydantic model object).\n\nAnd if we call:\n\n```Python\nprint(user_dict)\n```\n\nwe would get a Python `dict` with:\n\n```Python\n{\n 'username': 'john',\n 'password': 'secret',\n 'email': 'john.doe@example.com',\n 'full_name': None,\n}\n```\n\n#### Unpacking a `dict` { #unpacking-a-dict }\n\nIf we take a `dict` like `user_dict` and pass it to a function (or class) with `**user_dict`, Python will \"unpack\" it. It will pass the keys and values of the `user_dict` directly as key-value arguments.\n\nSo, continuing with the `user_dict` from above, writing:\n\n```Python\nUserInDB(**user_dict)\n```\n\nwould result in something equivalent to:\n\n```Python\nUserInDB(\n username=\"john\",\n password=\"secret\",\n email=\"john.doe@example.com\",\n full_name=None,\n)\n```\n\nOr more exactly, using `user_dict` directly, with whatever contents it might have in the future:\n\n```Python\nUserInDB(\n username = user_dict[\"username\"],\n password = user_dict[\"password\"],\n email = user_dict[\"email\"],\n full_name = user_dict[\"full_name\"],\n)\n```\n\n#### A Pydantic model from the contents of another { #a-pydantic-model-from-the-contents-of-another }\n\nAs in the example above we got `user_dict` from `user_in.model_dump()`, this code:\n\n```Python\nuser_dict = user_in.model_dump()\nUserInDB(**user_dict)\n```\n\nwould be equivalent to:\n\n```Python\nUserInDB(**user_in.model_dump())\n```\n\n...because `user_in.model_dump()` is a `dict`, and then we make Python \"unpack\" it by passing it to `UserInDB` prefixed with `**`.\n\nSo, we get a Pydantic model from the data in another Pydantic model.\n\n#### Unpacking a `dict` and extra keywords { #unpacking-a-dict-and-extra-keywords }\n\nAnd then adding the extra keyword argument `hashed_password=hashed_password`, like in:\n\n```Python\nUserInDB(**user_in.model_dump(), hashed_password=hashed_password)\n```\n\n...ends up being like:\n\n```Python\nUserInDB(\n username = user_dict[\"username\"],\n password = user_dict[\"password\"],\n email = user_dict[\"email\"],\n full_name = user_dict[\"full_name\"],\n hashed_password = hashed_password,\n)\n```\n\n/// warning\n\nThe supporting additional functions `fake_password_hasher` and `fake_save_user` are just to demo a possible flow of the data, but they of course are not providing any real security.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-models.md", "symbol": "Multiple models { #multiple-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-models.md#L19-L140", "start_line": 19, "end_line": 140} {"id": "docs/en/docs/tutorial/extra-models.md::Reduce duplication { #reduce-duplication }::L141", "text": "# Doc: docs/en/docs/tutorial/extra-models.md | Page: Extra Models { #extra-models } | Section: Reduce duplication { #reduce-duplication }\n## Reduce duplication { #reduce-duplication }\n\nReducing code duplication is one of the core ideas in **FastAPI**.\n\nAs code duplication increases the chances of bugs, security issues, code desynchronization issues (when you update in one place but not in the others), etc.\n\nAnd these models are all sharing a lot of the data and duplicating attribute names and types.\n\nWe could do better.\n\nWe can declare a `UserBase` model that serves as a base for our other models. And then we can make subclasses of that model that inherit its attributes (type declarations, validation, etc).\n\nAll the data conversion, validation, documentation, etc. will still work as normally.\n\nThat way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password):\n\n{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-models.md", "symbol": "Reduce duplication { #reduce-duplication }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-models.md#L141-L158", "start_line": 141, "end_line": 158} {"id": "docs/en/docs/tutorial/extra-models.md::`Union` or `anyOf` { #union-or-anyof }::L159", "text": "# Doc: docs/en/docs/tutorial/extra-models.md | Page: Extra Models { #extra-models } | Section: `Union` or `anyOf` { #union-or-anyof }\n## `Union` or `anyOf` { #union-or-anyof }\n\nYou can declare a response to be the `Union` of two or more types, that means, that the response would be any of them.\n\nIt will be defined in OpenAPI with `anyOf`.\n\nTo do that, use the standard Python type hint [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):\n\n/// note\n\nWhen defining a [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions), include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.\n\n///\n\n{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}\n\n### `Union` in Python 3.10 { #union-in-python-3-10 }\n\nIn this example we pass `Union[PlaneItem, CarItem]` as the value of the argument `response_model`.\n\nBecause we are passing it as a **value to an argument** instead of putting it in a **type annotation**, we have to use `Union` even in Python 3.10.\n\nIf it was in a type annotation we could have used the vertical bar, as:\n\n```Python\nsome_variable: PlaneItem | CarItem\n```\n\nBut if we put that in the assignment `response_model=PlaneItem | CarItem` we would get an error, because Python would try to perform an **invalid operation** between `PlaneItem` and `CarItem` instead of interpreting that as a type annotation.", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-models.md", "symbol": "`Union` or `anyOf` { #union-or-anyof }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-models.md#L159-L188", "start_line": 159, "end_line": 188} {"id": "docs/en/docs/tutorial/extra-models.md::List of models { #list-of-models }::L189", "text": "# Doc: docs/en/docs/tutorial/extra-models.md | Page: Extra Models { #extra-models } | Section: List of models { #list-of-models }\n## List of models { #list-of-models }\n\nThe same way, you can declare responses of lists of objects.\n\nFor that, use the standard Python `list`:\n\n{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-models.md", "symbol": "List of models { #list-of-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-models.md#L189-L196", "start_line": 189, "end_line": 196} {"id": "docs/en/docs/tutorial/extra-models.md::Response with arbitrary `dict` { #response-with-arbitrary-dict }::L197", "text": "# Doc: docs/en/docs/tutorial/extra-models.md | Page: Extra Models { #extra-models } | Section: Response with arbitrary `dict` { #response-with-arbitrary-dict }\n## Response with arbitrary `dict` { #response-with-arbitrary-dict }\n\nYou can also declare a response using a plain arbitrary `dict`, declaring just the type of the keys and values, without using a Pydantic model.\n\nThis is useful if you don't know the valid field/attribute names (that would be needed for a Pydantic model) beforehand.\n\nIn this case, you can use `dict`:\n\n{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-models.md", "symbol": "Response with arbitrary `dict` { #response-with-arbitrary-dict }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-models.md#L197-L206", "start_line": 197, "end_line": 206} {"id": "docs/en/docs/tutorial/extra-models.md::Recap { #recap }::L207", "text": "# Doc: docs/en/docs/tutorial/extra-models.md | Page: Extra Models { #extra-models } | Section: Recap { #recap }\n## Recap { #recap }\n\nUse multiple Pydantic models and inherit freely for each case.\n\nYou don't need to have a single data model per entity if that entity must be able to have different \"states\". The **user** \"entity\" is an example, with states that include `password`, `password_hash`, or no password.", "source_type": "doc", "path": "docs/en/docs/tutorial/extra-models.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/extra-models.md#L207-L211", "start_line": 207, "end_line": 211} {"id": "docs/en/docs/tutorial/first-steps.md::First Steps { #first-steps }::L1", "text": "# Doc: docs/en/docs/tutorial/first-steps.md | Page: First Steps { #first-steps } | Section: First Steps { #first-steps }\n# First Steps { #first-steps }\n\nThe simplest FastAPI file could look like this:\n\n{* ../../docs_src/first_steps/tutorial001_py310.py *}\n\nCopy that to a file `main.py`.\n\nRun the live server:\n\n
\n\n```console\n$ fastapi dev\n\n FastAPI Starting development server 🚀\n\n Searching for package file structure from directories\n with __init__.py files\n Importing from /home/user/code/awesomeapp\n\n module 🐍 main.py\n\n code Importing the FastAPI app object from the module with\n the following code:\n\n from main import app\n\n app Using import string: main:app\n\n server Server started at http://127.0.0.1:8000\n server Documentation at http://127.0.0.1:8000/docs\n\n tip Running in development mode, for production use:\n fastapi run\n\n Logs:\n\n INFO Will watch for changes in these directories:\n ['/home/user/code/awesomeapp']\n INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C\n to quit)\n INFO Started reloader process [383138] using WatchFiles\n INFO Started server process [383153]\n INFO Waiting for application startup.\n INFO Application startup complete.\n```\n\n
\n\nIn the output, there's a line with something like:\n\n```hl_lines=\"4\"\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\nThat line shows the URL where your app is being served on your local machine.\n\n### Check it { #check-it }\n\nOpen your browser at [http://127.0.0.1:8000](http://127.0.0.1:8000).\n\nYou will see the JSON response as:\n\n```JSON\n{\"message\": \"Hello World\"}\n```\n\n### Interactive API docs { #interactive-api-docs }\n\nNow go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see the automatic interactive API documentation (provided by [Swagger UI](https://github.com/swagger-api/swagger-ui)):\n\n![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)\n\n### Alternative API docs { #alternative-api-docs }\n\nAnd now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).\n\nYou will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):\n\n![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)\n\n### OpenAPI { #openapi }\n\n**FastAPI** generates a \"schema\" with all your API using the **OpenAPI** standard for defining APIs.\n\n#### \"Schema\" { #schema }\n\nA \"schema\" is a definition or description of something. Not the code that implements it, but just an abstract description.\n\n#### API \"schema\" { #api-schema }\n\nIn this case, [OpenAPI](https://github.com/OAI/OpenAPI-Specification) is a specification that dictates how to define a schema of your API.\n\nThis schema definition includes your API paths, the possible parameters they take, etc.\n\n#### Data \"schema\" { #data-schema }\n\nThe term \"schema\" might also refer to the shape of some data, like a JSON content.\n\nIn that case, it would mean the JSON attributes, and data types they have, etc.\n\n#### OpenAPI and JSON Schema { #openapi-and-json-schema }\n\nOpenAPI defines an API schema for your API. And that schema includes definitions (or \"schemas\") of the data sent and received by your API using **JSON Schema**, the standard for JSON data schemas.\n\n#### Check the `openapi.json` { #check-the-openapi-json }\n\nIf you are curious about what the raw OpenAPI schema looks like, FastAPI automatically generates a JSON (schema) with the descriptions of all your API.\n\nYou can see it directly at: [http://127.0.0.1:8000/openapi.json](http://127.0.0.1:8000/openapi.json).\n\nIt will show a JSON starting with something like:\n\n```JSON\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"FastAPI\",\n \"version\": \"0.1.0\"\n },\n \"paths\": {\n \"/items/\": {\n \"get\": {\n \"responses\": {\n \"200\": {\n \"description\": \"Successful Response\",\n \"content\": {\n \"application/json\": {\n\n\n\n...\n```\n\n#### What is OpenAPI for { #what-is-openapi-for }\n\nThe OpenAPI schema is what powers the two interactive documentation systems included.\n\nAnd there are dozens of alternatives, all based on OpenAPI. You could easily add any of those alternatives to your application built with **FastAPI**.\n\nYou could also use it to generate code automatically, for clients that communicate with your API. For example, frontend, mobile or IoT applications.\n\n### Configure the app `entrypoint` in `pyproject.toml` { #configure-the-app-entrypoint-in-pyproject-toml }\n\nYou can configure where your app is located in a `pyproject.toml` file like:\n\n```toml\n[tool.fastapi]\nentrypoint = \"main:app\"\n```\n\nThat `entrypoint` will tell the `fastapi` command that it should import the app like:\n\n```python\nfrom main import app\n```\n\nIf your code was structured like:\n\n```\n.\n├── backend\n│   ├── main.py\n│   ├── __init__.py\n```\n\nThen you would set the `entrypoint` as:\n\n```toml\n[tool.fastapi]\nentrypoint = \"backend.main:app\"\n```\n\nwhich would be equivalent to:\n\n```python\nfrom backend.main import app\n```\n\n### `fastapi dev` with path or with `--entrypoint` CLI option { #fastapi-dev-with-path-or-with-entrypoint-cli-option }\n\nYou can also pass the file path to the `fastapi dev` command, and it will guess the FastAPI app object to use:\n\n```console\n$ fastapi dev main.py\n```\n\nOr, you can also pass the `--entrypoint` option to the `fastapi dev` command:\n\n```console\n$ fastapi dev --entrypoint main:app\n```\n\nBut you would have to remember to pass the correct path\\entrypoint every time you call the `fastapi` command.\n\nAdditionally, other tools might not be able to find it, for example the [VS Code Extension](../editor-support.md) or [FastAPI Cloud](https://fastapicloud.com), so it is recommended to use the `entrypoint` in `pyproject.toml`.\n\n### Deploy your app (optional) { #deploy-your-app-optional }\n\nYou can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀\n\n
\n\n```console\n$ fastapi deploy\n\nDeploying to FastAPI Cloud...\n\n✅ Deployment successful!\n\n🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev\n```\n\n
\n\nThe CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process.\n\nThat's it! Now you can access your app at that URL. ✨", "source_type": "doc", "path": "docs/en/docs/tutorial/first-steps.md", "symbol": "First Steps { #first-steps }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/first-steps.md#L1-L222", "start_line": 1, "end_line": 222} {"id": "docs/en/docs/tutorial/first-steps.md::Recap, step by step { #recap-step-by-step }::L223", "text": "# Doc: docs/en/docs/tutorial/first-steps.md | Page: First Steps { #first-steps } | Section: Recap, step by step { #recap-step-by-step }\n## Recap, step by step { #recap-step-by-step }\n\n### Step 1: import `FastAPI` { #step-1-import-fastapi }\n\n{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *}\n\n`FastAPI` is a Python class that provides all the functionality for your API.\n\n/// note | Technical Details\n\n`FastAPI` is a class that inherits directly from `Starlette`.\n\nYou can use all the [Starlette](https://www.starlette.dev/) functionality with `FastAPI` too.\n\n///\n\n### Step 2: create a `FastAPI` \"instance\" { #step-2-create-a-fastapi-instance }\n\n{* ../../docs_src/first_steps/tutorial001_py310.py hl[3] *}\n\nHere the `app` variable will be an \"instance\" of the class `FastAPI`.\n\nThis will be the main point of interaction to create all your API.\n\n### Step 3: create a *path operation* { #step-3-create-a-path-operation }\n\n#### Path { #path }\n\n\"Path\" here refers to the last part of the URL starting from the first `/`.\n\nSo, in a URL like:\n\n```\nhttps://example.com/items/foo\n```\n\n...the path would be:\n\n```\n/items/foo\n```\n\n/// note\n\nA \"path\" is also commonly called an \"endpoint\" or a \"route\".\n\n///\n\nWhile building an API, the \"path\" is the main way to separate \"concerns\" and \"resources\".\n\n#### Operation { #operation }\n\n\"Operation\" here refers to one of the HTTP \"methods\".\n\nOne of:\n\n* `POST`\n* `GET`\n* `PUT`\n* `DELETE`\n\n...and the more exotic ones:\n\n* `OPTIONS`\n* `HEAD`\n* `PATCH`\n* `TRACE`\n\nIn the HTTP protocol, you can communicate to each path using one (or more) of these \"methods\".\n\n---\n\nWhen building APIs, you normally use these specific HTTP methods to perform a specific action.\n\nNormally you use:\n\n* `POST`: to create data.\n* `GET`: to read data.\n* `PUT`: to update data.\n* `DELETE`: to delete data.\n\nSo, in OpenAPI, each of the HTTP methods is called an \"operation\".\n\nWe are going to call them \"**operations**\" too.\n\n#### Define a *path operation decorator* { #define-a-path-operation-decorator }\n\n{* ../../docs_src/first_steps/tutorial001_py310.py hl[6] *}\n\nThe `@app.get(\"/\")` tells **FastAPI** that the function right below is in charge of handling requests that go to:\n\n* the path `/`\n* using a get operation\n\n/// note | `@decorator` Info\n\nThat `@something` syntax in Python is called a \"decorator\".\n\nYou put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).\n\nA \"decorator\" takes the function below and does something with it.\n\nIn our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.\n\nIt is the \"**path operation decorator**\".\n\n///\n\nYou can also use the other operations:\n\n* `@app.post()`\n* `@app.put()`\n* `@app.delete()`\n\nAnd the more exotic ones:\n\n* `@app.options()`\n* `@app.head()`\n* `@app.patch()`\n* `@app.trace()`\n\n/// tip\n\nYou are free to use each operation (HTTP method) as you wish.\n\n**FastAPI** doesn't enforce any specific meaning.\n\nThe information here is presented as a guideline, not a requirement.\n\nFor example, when using GraphQL you normally perform all the actions using only `POST` operations.\n\n///\n\n### Step 4: define the **path operation function** { #step-4-define-the-path-operation-function }\n\nThis is our \"**path operation function**\":\n\n* **path**: is `/`.\n* **operation**: is `get`.\n* **function**: is the function below the \"decorator\" (below `@app.get(\"/\")`).\n\n{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}\n\nThis is a Python function.\n\nIt will be called by **FastAPI** whenever it receives a request to the URL \"`/`\" using a `GET` operation.\n\nIn this case, it is an `async` function.\n\n---\n\nYou could also define it as a normal function instead of `async def`:\n\n{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}\n\n/// note\n\nIf you don't know the difference, check the [Async: *\"In a hurry?\"*](../async.md#in-a-hurry).\n\n///\n\n### Step 5: return the content { #step-5-return-the-content }\n\n{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}\n\nYou can return a `dict`, `list`, singular values as `str`, `int`, etc.\n\nYou can also return Pydantic models (you'll see more about that later).\n\nThere are many other objects and models that will be automatically converted to JSON (including ORMs, etc). Try using your favorite ones, it's highly probable that they are already supported.\n\n### Step 6: Deploy it { #step-6-deploy-it }\n\nDeploy your app to **[FastAPI Cloud](https://fastapicloud.com)** with one command: `fastapi deploy`. 🎉\n\n#### About FastAPI Cloud { #about-fastapi-cloud }\n\n**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**.\n\nIt streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort.\n\nIt brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉\n\nFastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨\n\n#### Deploy to other cloud providers { #deploy-to-other-cloud-providers }\n\nFastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.\n\nFollow your cloud provider's guides to deploy FastAPI apps with them. 🤓", "source_type": "doc", "path": "docs/en/docs/tutorial/first-steps.md", "symbol": "Recap, step by step { #recap-step-by-step }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/first-steps.md#L223-L413", "start_line": 223, "end_line": 413} {"id": "docs/en/docs/tutorial/first-steps.md::Recap { #recap }::L414", "text": "# Doc: docs/en/docs/tutorial/first-steps.md | Page: First Steps { #first-steps } | Section: Recap { #recap }\n## Recap { #recap }\n\n* Import `FastAPI`.\n* Create an `app` instance.\n* Write a **path operation decorator** using decorators like `@app.get(\"/\")`.\n* Define a **path operation function**; for example, `def root(): ...`.\n* Run the development server using the command `fastapi dev`.\n* Optionally deploy your app with `fastapi deploy`.", "source_type": "doc", "path": "docs/en/docs/tutorial/first-steps.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/first-steps.md#L414-L421", "start_line": 414, "end_line": 421} {"id": "docs/en/docs/tutorial/frontend.md::Frontend { #frontend }::L1", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Frontend { #frontend }\n# Frontend { #frontend }\n\nYou can serve static frontend apps with `app.frontend()` (or `router.frontend()`).\n\nThis is useful for frontend tools that generate static files, like React with Vite, TanStack Router, Astro, Vue, Svelte, Angular, Solid, and others.\n\nWith these tools, you normally have a step that builds the frontend, with a command like:\n\n```bash\nnpm run build\n```\n\nThat would generate a directory like `./dist/` with your frontend files.\n\nYou can use `app.frontend()` to serve that directory following the conventions needed by these frontend frameworks.\n\n**FastAPI** checks *path operations* first. The frontend files are checked only if no normal route matched, so your API won't be affected.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Frontend { #frontend }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L1-L18", "start_line": 1, "end_line": 18} {"id": "docs/en/docs/tutorial/frontend.md::Serve a Frontend { #serve-a-frontend }::L19", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Serve a Frontend { #serve-a-frontend }\n## Serve a Frontend { #serve-a-frontend }\n\nAfter building your frontend, for example with `npm run build`, put the generated files in a directory, for example, `dist`.\n\nYour project structure 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\nThen serve it with `app.frontend()`:\n\n{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *}\n\nWith this, a request for `/assets/app.js` can serve `dist/assets/app.js`.\n\nIf you also have a **FastAPI** *path operation*, the *path operation* wins.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Serve a Frontend { #serve-a-frontend }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L19-L44", "start_line": 19, "end_line": 44} {"id": "docs/en/docs/tutorial/frontend.md::Client-Side Routing { #client-side-routing }::L45", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Client-Side Routing { #client-side-routing }\n## Client-Side Routing { #client-side-routing }\n\nMany frontend apps, including **single-page apps** (SPAs), use client-side routing. A path like `/dashboard/settings` might not be a real file but the framework would take care of handling it.\n\nSo, if accessing that URL directly (instead of navigating through the app), the backend should serve the frontend app from `index.html`, so that the frontend framework can then handle the client-side routing.\n\nFor that, use `fallback=\"index.html\"`:\n\n{* ../../docs_src/frontend/tutorial002_py310.py hl[5] *}\n\n**FastAPI** uses this fallback only for `GET` and `HEAD` requests that look like browser navigation. Missing files like JavaScript, CSS, and images still return `404`.\n\nRequests with other methods, like `POST` or `PUT`, to paths that only match the frontend fallback also return `404`. Regular **FastAPI** *path operations* still have higher priority than frontend routes.\n\n/// tip\n\nBy default, `fallback` has a value of `fallback=\"auto\"`. In most cases you won't need to specify `fallback`. Read below for details.\n\n///\n\nThis is what you would want with many frontend apps that use client-side routing, for example, React with TanStack Router, Vue, Angular, SvelteKit, or Solid.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Client-Side Routing { #client-side-routing }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L45-L66", "start_line": 45, "end_line": 66} {"id": "docs/en/docs/tutorial/frontend.md::Custom 404 Page { #custom-404-page }::L67", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Custom 404 Page { #custom-404-page }\n## Custom 404 Page { #custom-404-page }\n\nYou can also serve a static `404.html` page for missing frontend paths:\n\n{* ../../docs_src/frontend/tutorial003_py310.py hl[5] *}\n\nThat response keeps a status code of `404`.\n\nIn this case, **FastAPI** won't serve `index.html` for missing frontend paths. It will return the `404.html` file instead.\n\n/// tip\n\nBy default, `fallback` has a value of `fallback=\"auto\"`. With this, if a `404.html` file is found, it will be used as the fallback automatically.\n\nSo, you can normally omit the `fallback` argument.\n\n///\n\nThis is useful with frontend tools that generate static HTML files for each page, like Astro.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Custom 404 Page { #custom-404-page }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L67-L86", "start_line": 67, "end_line": 86} {"id": "docs/en/docs/tutorial/frontend.md::Fallback Auto { #fallback-auto }::L87", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Fallback Auto { #fallback-auto }\n## Fallback Auto { #fallback-auto }\n\nBy default, `app.frontend()` uses `fallback=\"auto\"`.\n\nIf there is a `404.html` file in the frontend directory, missing frontend paths serve that file with status code `404`.\n\nOtherwise, if there is an `index.html` file, missing browser navigation paths serve `index.html`, which is what many frontend apps with client-side routing expect.\n\nSo, in most cases you can use `app.frontend(\"/\", directory=\"dist\")` without specifying the `fallback` argument.\n\n{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Fallback Auto { #fallback-auto }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L87-L98", "start_line": 87, "end_line": 98} {"id": "docs/en/docs/tutorial/frontend.md::Disable Fallback { #disable-fallback }::L99", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Disable Fallback { #disable-fallback }\n## Disable Fallback { #disable-fallback }\n\nIf you don't want to serve a fallback file for missing frontend paths, use `fallback=None`:\n\n{* ../../docs_src/frontend/tutorial005_py310.py hl[5] *}\n\nThen missing frontend paths return the normal `404`.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Disable Fallback { #disable-fallback }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L99-L106", "start_line": 99, "end_line": 106} {"id": "docs/en/docs/tutorial/frontend.md::Check Directory { #check-directory }::L107", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Check Directory { #check-directory }\n## Check Directory { #check-directory }\n\nBy default, `app.frontend()` checks that the directory exists when the app is created.\n\nThis helps catch configuration errors early. For example, if the frontend build output directory is missing, **FastAPI** will raise an error on startup.\n\nIf your frontend files are created later, for example by a separate build step after the app object is created, set `check_dir=False`:\n\n{* ../../docs_src/frontend/tutorial006_py310.py hl[5] *}\n\nWith `check_dir=False`, **FastAPI** will not check the directory when the app is created. If the configured directory is still missing when a request is handled, **FastAPI** will raise an error then.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Check Directory { #check-directory }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L107-L118", "start_line": 107, "end_line": 118} {"id": "docs/en/docs/tutorial/frontend.md::Use it with `APIRouter` { #use-it-with-apirouter }::L119", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Use it with `APIRouter` { #use-it-with-apirouter }\n## Use it with `APIRouter` { #use-it-with-apirouter }\n\nYou can also add frontend files to an `APIRouter` and include it with a prefix:\n\n{* ../../docs_src/frontend/tutorial004_py310.py hl[6,7] *}\n\nIn this example, frontend paths are served under `/app`.\n\nAny regular *path operations* in the app will still take precedence, including in other routers.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Use it with `APIRouter` { #use-it-with-apirouter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L119-L128", "start_line": 119, "end_line": 128} {"id": "docs/en/docs/tutorial/frontend.md::Dependencies and Middleware { #dependencies-and-middleware }::L129", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Dependencies and Middleware { #dependencies-and-middleware }\n## Dependencies and Middleware { #dependencies-and-middleware }\n\nFrontend responses run inside the normal **FastAPI** application, so HTTP middleware applies to them.\n\nDependencies from the app, from an `APIRouter`, and from `include_router()` also apply to frontend responses. This can be useful for protecting a frontend with cookie authentication or similar.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Dependencies and Middleware { #dependencies-and-middleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L129-L134", "start_line": 129, "end_line": 134} {"id": "docs/en/docs/tutorial/frontend.md::Static Build Output Only { #static-build-output-only }::L135", "text": "# Doc: docs/en/docs/tutorial/frontend.md | Page: Frontend { #frontend } | Section: Static Build Output Only { #static-build-output-only }\n## Static Build Output Only { #static-build-output-only }\n\n`app.frontend()` serves files already generated by your frontend build.\n\nIt does not run server-side rendering. It is for frontend frameworks that generate static files, not for frameworks that need dynamic rendering on the server for each request.", "source_type": "doc", "path": "docs/en/docs/tutorial/frontend.md", "symbol": "Static Build Output Only { #static-build-output-only }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/frontend.md#L135-L139", "start_line": 135, "end_line": 139} {"id": "docs/en/docs/tutorial/handling-errors.md::Handling Errors { #handling-errors }::L1", "text": "# Doc: docs/en/docs/tutorial/handling-errors.md | Page: Handling Errors { #handling-errors } | Section: Handling Errors { #handling-errors }\n# Handling Errors { #handling-errors }\n\nThere are many situations in which you need to report an error to a client that is using your API.\n\nThis client could be a browser with a frontend, a code from someone else, an IoT device, etc.\n\nYou could need to tell the client that:\n\n* The client doesn't have enough privileges for that operation.\n* The client doesn't have access to that resource.\n* The item the client was trying to access doesn't exist.\n* etc.\n\nIn these cases, you would normally return an **HTTP status code** in the range of **400** (from 400 to 499).\n\nThis is similar to the 200 HTTP status codes (from 200 to 299). Those \"200\" status codes mean that somehow there was a \"success\" in the request.\n\nThe status codes in the 400 range mean that there was an error from the client.\n\nRemember all those **\"404 Not Found\"** errors (and jokes)?", "source_type": "doc", "path": "docs/en/docs/tutorial/handling-errors.md", "symbol": "Handling Errors { #handling-errors }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/handling-errors.md#L1-L21", "start_line": 1, "end_line": 21} {"id": "docs/en/docs/tutorial/handling-errors.md::Use `HTTPException` { #use-httpexception }::L22", "text": "# Doc: docs/en/docs/tutorial/handling-errors.md | Page: Handling Errors { #handling-errors } | Section: Use `HTTPException` { #use-httpexception }\n## Use `HTTPException` { #use-httpexception }\n\nTo return HTTP responses with errors to the client you use `HTTPException`.\n\n### Import `HTTPException` { #import-httpexception }\n\n{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}\n\n### Raise an `HTTPException` in your code { #raise-an-httpexception-in-your-code }\n\n`HTTPException` is a normal Python exception with additional data relevant for APIs.\n\nBecause it's a Python exception, you don't `return` it, you `raise` it.\n\nThis also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client.\n\nThe benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security.\n\nIn this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`:\n\n{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}\n\n### The resulting response { #the-resulting-response }\n\nIf the client requests `http://example.com/items/foo` (an `item_id` `\"foo\"`), that client will receive an HTTP status code of 200, and a JSON response of:\n\n```JSON\n{\n \"item\": \"The Foo Wrestlers\"\n}\n```\n\nBut if the client requests `http://example.com/items/bar` (a non-existent `item_id` `\"bar\"`), that client will receive an HTTP status code of 404 (the \"not found\" error), and a JSON response of:\n\n```JSON\n{\n \"detail\": \"Item not found\"\n}\n```\n\n/// tip\n\nWhen raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.\n\nYou could pass a `dict`, a `list`, etc.\n\nThey are handled automatically by **FastAPI** and converted to JSON.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/handling-errors.md", "symbol": "Use `HTTPException` { #use-httpexception }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/handling-errors.md#L22-L71", "start_line": 22, "end_line": 71} {"id": "docs/en/docs/tutorial/handling-errors.md::Add custom headers { #add-custom-headers }::L72", "text": "# Doc: docs/en/docs/tutorial/handling-errors.md | Page: Handling Errors { #handling-errors } | Section: Add custom headers { #add-custom-headers }\n## Add custom headers { #add-custom-headers }\n\nThere are some situations where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security.\n\nYou probably won't need to use it directly in your code.\n\nBut in case you needed it for an advanced scenario, you can add custom headers:\n\n{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/handling-errors.md", "symbol": "Add custom headers { #add-custom-headers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/handling-errors.md#L72-L81", "start_line": 72, "end_line": 81} {"id": "docs/en/docs/tutorial/handling-errors.md::Install custom exception handlers { #install-custom-exception-handlers }::L82", "text": "# Doc: docs/en/docs/tutorial/handling-errors.md | Page: Handling Errors { #handling-errors } | Section: Install custom exception handlers { #install-custom-exception-handlers }\n## Install custom exception handlers { #install-custom-exception-handlers }\n\nYou can add custom exception handlers with [the same exception utilities from Starlette](https://www.starlette.dev/exceptions/).\n\nLet's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`.\n\nAnd you want to handle this exception globally with FastAPI.\n\nYou could add a custom exception handler with `@app.exception_handler()`:\n\n{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}\n\nHere, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.\n\nBut it will be handled by the `unicorn_exception_handler`.\n\nSo, you will receive a clean error, with an HTTP status code of `418` and a JSON content of:\n\n```JSON\n{\"message\": \"Oops! yolo did something. There goes a rainbow...\"}\n```\n\n/// note | Technical Details\n\nYou could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/handling-errors.md", "symbol": "Install custom exception handlers { #install-custom-exception-handlers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/handling-errors.md#L82-L111", "start_line": 82, "end_line": 111} {"id": "docs/en/docs/tutorial/handling-errors.md::Override the default exception handlers { #override-the-default-exception-handlers }::L112", "text": "# Doc: docs/en/docs/tutorial/handling-errors.md | Page: Handling Errors { #handling-errors } | Section: Override the default exception handlers { #override-the-default-exception-handlers }\n## Override the default exception handlers { #override-the-default-exception-handlers }\n\n**FastAPI** has some default exception handlers.\n\nThese handlers are in charge of returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data.\n\nYou can override these exception handlers with your own.\n\n### Override request validation exceptions { #override-request-validation-exceptions }\n\nWhen a request contains invalid data, **FastAPI** internally raises a `RequestValidationError`.\n\nAnd it also includes a default exception handler for it.\n\nTo override it, import the `RequestValidationError` and use it with `@app.exception_handler(RequestValidationError)` to decorate the exception handler.\n\nThe exception handler will receive a `Request` and the exception.\n\n{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}\n\nNow, if you go to `/items/foo`, instead of getting the default JSON error with:\n\n```JSON\n{\n \"detail\": [\n {\n \"loc\": [\n \"path\",\n \"item_id\"\n ],\n \"msg\": \"value is not a valid integer\",\n \"type\": \"type_error.integer\"\n }\n ]\n}\n```\n\nyou will get a text version, with:\n\n```\nValidation errors:\nField: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer\n```\n\n### Override the `HTTPException` error handler { #override-the-httpexception-error-handler }\n\nThe same way, you can override the `HTTPException` handler.\n\nFor example, you could want to return a plain text response instead of JSON for these errors:\n\n{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}\n\n/// note | Technical Details\n\nYou could also use `from starlette.responses import PlainTextResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.\n\n///\n\n/// warning\n\nHave in mind that the `RequestValidationError` contains the information of the file name and line where the validation error happens so that you can show it in your logs with the relevant information if you want to.\n\nBut that means that if you just convert it to a string and return that information directly, you could be leaking a bit of information about your system, that's why here the code extracts and shows each error independently.\n\n///\n\n### Use the `RequestValidationError` body { #use-the-requestvalidationerror-body }\n\nThe `RequestValidationError` contains the `body` it received with invalid data.\n\nYou could use it while developing your app to log the body and debug it, return it to the user, etc.\n\n{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}\n\nNow try sending an invalid item like:\n\n```JSON\n{\n \"title\": \"towel\",\n \"size\": \"XL\"\n}\n```\n\nYou will receive a response telling you that the data is invalid containing the received body:\n\n```JSON hl_lines=\"12-15\"\n{\n \"detail\": [\n {\n \"loc\": [\n \"body\",\n \"size\"\n ],\n \"msg\": \"value is not a valid integer\",\n \"type\": \"type_error.integer\"\n }\n ],\n \"body\": {\n \"title\": \"towel\",\n \"size\": \"XL\"\n }\n}\n```\n\n#### FastAPI's `HTTPException` vs Starlette's `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }\n\n**FastAPI** has its own `HTTPException`.\n\nAnd **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class.\n\nThe only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it.\n\nSo, you can keep raising **FastAPI**'s `HTTPException` as normally in your code.\n\nBut when you register an exception handler, you should register it for Starlette's `HTTPException`.\n\nThis way, if any part of Starlette's internal code, or a Starlette extension or plug-in, raises a Starlette `HTTPException`, your handler will be able to catch and handle it.\n\nIn this example, to be able to have both `HTTPException`s in the same code, Starlette's exceptions is renamed to `StarletteHTTPException`:\n\n```Python\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\n```\n\n### Reuse **FastAPI**'s exception handlers { #reuse-fastapis-exception-handlers }\n\nIf you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`:\n\n{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}\n\nIn this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.", "source_type": "doc", "path": "docs/en/docs/tutorial/handling-errors.md", "symbol": "Override the default exception handlers { #override-the-default-exception-handlers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/handling-errors.md#L112-L244", "start_line": 112, "end_line": 244} {"id": "docs/en/docs/tutorial/header-param-models.md::Header Parameter Models { #header-parameter-models }::L1", "text": "# Doc: docs/en/docs/tutorial/header-param-models.md | Page: Header Parameter Models { #header-parameter-models } | Section: Header Parameter Models { #header-parameter-models }\n# Header Parameter Models { #header-parameter-models }\n\nIf you have a group of related **header parameters**, you can create a **Pydantic model** to declare them.\n\nThis would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎\n\n/// note\n\nThis is supported since FastAPI version `0.115.0`. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/header-param-models.md", "symbol": "Header Parameter Models { #header-parameter-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-param-models.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/tutorial/header-param-models.md::Header Parameters with a Pydantic Model { #header-parameters-with-a-pydantic-model }::L13", "text": "# Doc: docs/en/docs/tutorial/header-param-models.md | Page: Header Parameter Models { #header-parameter-models } | Section: Header Parameters with a Pydantic Model { #header-parameters-with-a-pydantic-model }\n## Header Parameters with a Pydantic Model { #header-parameters-with-a-pydantic-model }\n\nDeclare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`:\n\n{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}\n\n**FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined.", "source_type": "doc", "path": "docs/en/docs/tutorial/header-param-models.md", "symbol": "Header Parameters with a Pydantic Model { #header-parameters-with-a-pydantic-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-param-models.md#L13-L20", "start_line": 13, "end_line": 20} {"id": "docs/en/docs/tutorial/header-param-models.md::Check the Docs { #check-the-docs }::L21", "text": "# Doc: docs/en/docs/tutorial/header-param-models.md | Page: Header Parameter Models { #header-parameter-models } | Section: Check the Docs { #check-the-docs }\n## Check the Docs { #check-the-docs }\n\nYou can see the required headers in the docs UI at `/docs`:\n\n
\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/header-param-models.md", "symbol": "Check the Docs { #check-the-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-param-models.md#L21-L28", "start_line": 21, "end_line": 28} {"id": "docs/en/docs/tutorial/header-param-models.md::Forbid Extra Headers { #forbid-extra-headers }::L29", "text": "# Doc: docs/en/docs/tutorial/header-param-models.md | Page: Header Parameter Models { #header-parameter-models } | Section: Forbid Extra Headers { #forbid-extra-headers }\n## Forbid Extra Headers { #forbid-extra-headers }\n\nIn some special use cases (probably not very common), you might want to **restrict** the headers that you want to receive.\n\nYou can use Pydantic's model configuration to `forbid` any `extra` fields:\n\n{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *}\n\nIf a client tries to send some **extra headers**, they will receive an **error** response.\n\nFor example, if the client tries to send a `tool` header with a value of `plumbus`, they will receive an **error** response telling them that the header parameter `tool` is not allowed:\n\n```json\n{\n \"detail\": [\n {\n \"type\": \"extra_forbidden\",\n \"loc\": [\"header\", \"tool\"],\n \"msg\": \"Extra inputs are not permitted\",\n \"input\": \"plumbus\",\n }\n ]\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/header-param-models.md", "symbol": "Forbid Extra Headers { #forbid-extra-headers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-param-models.md#L29-L53", "start_line": 29, "end_line": 53} {"id": "docs/en/docs/tutorial/header-param-models.md::Disable Convert Underscores { #disable-convert-underscores }::L54", "text": "# Doc: docs/en/docs/tutorial/header-param-models.md | Page: Header Parameter Models { #header-parameter-models } | Section: Disable Convert Underscores { #disable-convert-underscores }\n## Disable Convert Underscores { #disable-convert-underscores }\n\nThe same way as with regular header parameters, when you have underscore characters in the parameter names, they are **automatically converted to hyphens**.\n\nFor example, if you have a header parameter `save_data` in the code, the expected HTTP header will be `save-data`, and it will show up like that in the docs.\n\nIf for some reason you need to disable this automatic conversion, you can do it as well for Pydantic models for header parameters.\n\n{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *}\n\n/// warning\n\nBefore setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/header-param-models.md", "symbol": "Disable Convert Underscores { #disable-convert-underscores }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-param-models.md#L54-L69", "start_line": 54, "end_line": 69} {"id": "docs/en/docs/tutorial/header-param-models.md::Summary { #summary }::L70", "text": "# Doc: docs/en/docs/tutorial/header-param-models.md | Page: Header Parameter Models { #header-parameter-models } | Section: Summary { #summary }\n## Summary { #summary }\n\nYou can use **Pydantic models** to declare **headers** in **FastAPI**. 😎", "source_type": "doc", "path": "docs/en/docs/tutorial/header-param-models.md", "symbol": "Summary { #summary }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-param-models.md#L70-L72", "start_line": 70, "end_line": 72} {"id": "docs/en/docs/tutorial/header-params.md::Header Parameters { #header-parameters }::L1", "text": "# Doc: docs/en/docs/tutorial/header-params.md | Page: Header Parameters { #header-parameters } | Section: Header Parameters { #header-parameters }\n# Header Parameters { #header-parameters }\n\nYou can define Header parameters the same way you define `Query`, `Path` and `Cookie` parameters.", "source_type": "doc", "path": "docs/en/docs/tutorial/header-params.md", "symbol": "Header Parameters { #header-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-params.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/header-params.md::Import `Header` { #import-header }::L5", "text": "# Doc: docs/en/docs/tutorial/header-params.md | Page: Header Parameters { #header-parameters } | Section: Import `Header` { #import-header }\n## Import `Header` { #import-header }\n\nFirst import `Header`:\n\n{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/header-params.md", "symbol": "Import `Header` { #import-header }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-params.md#L5-L10", "start_line": 5, "end_line": 10} {"id": "docs/en/docs/tutorial/header-params.md::Declare `Header` parameters { #declare-header-parameters }::L11", "text": "# Doc: docs/en/docs/tutorial/header-params.md | Page: Header Parameters { #header-parameters } | Section: Declare `Header` parameters { #declare-header-parameters }\n## Declare `Header` parameters { #declare-header-parameters }\n\nThen declare the header parameters using the same structure as with `Path`, `Query` and `Cookie`.\n\nYou can define the default value as well as all the extra validation or annotation parameters:\n\n{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *}\n\n/// note | Technical Details\n\n`Header` is a \"sister\" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class.\n\nBut remember that when you import `Query`, `Path`, `Header`, and others from `fastapi`, those are actually functions that return special classes.\n\n///\n\n/// note\n\nTo declare headers, you need to use `Header`, because otherwise the parameters would be interpreted as query parameters.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/header-params.md", "symbol": "Declare `Header` parameters { #declare-header-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-params.md#L11-L32", "start_line": 11, "end_line": 32} {"id": "docs/en/docs/tutorial/header-params.md::Automatic conversion { #automatic-conversion }::L33", "text": "# Doc: docs/en/docs/tutorial/header-params.md | Page: Header Parameters { #header-parameters } | Section: Automatic conversion { #automatic-conversion }\n## Automatic conversion { #automatic-conversion }\n\n`Header` has a little extra functionality on top of what `Path`, `Query` and `Cookie` provide.\n\nMost of the standard headers are separated by a \"hyphen\" character, also known as the \"minus symbol\" (`-`).\n\nBut a variable like `user-agent` is invalid in Python.\n\nSo, by default, `Header` will convert the parameter names characters from underscore (`_`) to hyphen (`-`) to extract and document the headers.\n\nAlso, HTTP headers are case-insensitive, so, you can declare them with standard Python style (also known as \"snake_case\").\n\nSo, you can use `user_agent` as you normally would in Python code, instead of needing to capitalize the first letters as `User_Agent` or something similar.\n\nIf for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`:\n\n{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *}\n\n/// warning\n\nBefore setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/header-params.md", "symbol": "Automatic conversion { #automatic-conversion }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-params.md#L33-L56", "start_line": 33, "end_line": 56} {"id": "docs/en/docs/tutorial/header-params.md::Duplicate headers { #duplicate-headers }::L57", "text": "# Doc: docs/en/docs/tutorial/header-params.md | Page: Header Parameters { #header-parameters } | Section: Duplicate headers { #duplicate-headers }\n## Duplicate headers { #duplicate-headers }\n\nIt is possible to receive duplicate headers. That means, the same header with multiple values.\n\nYou can define those cases using a list in the type declaration.\n\nYou will receive all the values from the duplicate header as a Python `list`.\n\nFor example, to declare a header of `X-Token` that can appear more than once, you can write:\n\n{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *}\n\nIf you communicate with that *path operation* sending two HTTP headers like:\n\n```\nX-Token: foo\nX-Token: bar\n```\n\nThe response would be like:\n\n```JSON\n{\n \"X-Token values\": [\n \"bar\",\n \"foo\"\n ]\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/header-params.md", "symbol": "Duplicate headers { #duplicate-headers }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-params.md#L57-L86", "start_line": 57, "end_line": 86} {"id": "docs/en/docs/tutorial/header-params.md::Recap { #recap }::L87", "text": "# Doc: docs/en/docs/tutorial/header-params.md | Page: Header Parameters { #header-parameters } | Section: Recap { #recap }\n## Recap { #recap }\n\nDeclare headers with `Header`, using the same common pattern as `Query`, `Path` and `Cookie`.\n\nAnd don't worry about underscores in your variables, **FastAPI** will take care of converting them.", "source_type": "doc", "path": "docs/en/docs/tutorial/header-params.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/header-params.md#L87-L91", "start_line": 87, "end_line": 91} {"id": "docs/en/docs/tutorial/index.md::Tutorial - User Guide { #tutorial-user-guide }::L1", "text": "# Doc: docs/en/docs/tutorial/index.md | Page: Tutorial - User Guide { #tutorial-user-guide } | Section: Tutorial - User Guide { #tutorial-user-guide }\n# Tutorial - User Guide { #tutorial-user-guide }\n\nThis tutorial shows you how to use **FastAPI** with most of its features, step by step.\n\nEach section gradually builds on the previous ones, but it's structured to separate topics, so that you can go directly to any specific one to solve your specific API needs.\n\nIt is also built to work as a future reference so you can come back and see exactly what you need.", "source_type": "doc", "path": "docs/en/docs/tutorial/index.md", "symbol": "Tutorial - User Guide { #tutorial-user-guide }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/index.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/tutorial/index.md::Run the code { #run-the-code }::L9", "text": "# Doc: docs/en/docs/tutorial/index.md | Page: Tutorial - User Guide { #tutorial-user-guide } | Section: Run the code { #run-the-code }\n## Run the code { #run-the-code }\n\nAll the code blocks can be copied and used directly (they are actually tested Python files).\n\nTo run any of the examples, copy the code to a file `main.py`, and start `fastapi dev`:\n\n
\n\n```console\n$ fastapi dev\n\n FastAPI Starting development server 🚀\n\n Searching for package file structure from directories\n with __init__.py files\n Importing from /home/user/code/awesomeapp\n\n module 🐍 main.py\n\n code Importing the FastAPI app object from the module with\n the following code:\n\n from main import app\n\n app Using import string: main:app\n\n server Server started at http://127.0.0.1:8000\n server Documentation at http://127.0.0.1:8000/docs\n\n tip Running in development mode, for production use:\n fastapi run\n\n Logs:\n\n INFO Will watch for changes in these directories:\n ['/home/user/code/awesomeapp']\n INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C\n to quit)\n INFO Started reloader process [383138] using WatchFiles\n INFO Started server process [383153]\n INFO Waiting for application startup.\n INFO Application startup complete.\n```\n\n
\n\nIt is **HIGHLY encouraged** that you write or copy the code, edit it and run it locally.\n\nUsing it in your editor is what really shows you the benefits of FastAPI, seeing how little code you have to write, all the type checks, autocompletion, etc.\n\n---", "source_type": "doc", "path": "docs/en/docs/tutorial/index.md", "symbol": "Run the code { #run-the-code }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/index.md#L9-L60", "start_line": 9, "end_line": 60} {"id": "docs/en/docs/tutorial/index.md::Install FastAPI { #install-fastapi }::L61", "text": "# Doc: docs/en/docs/tutorial/index.md | Page: Tutorial - User Guide { #tutorial-user-guide } | Section: Install FastAPI { #install-fastapi }\n## Install FastAPI { #install-fastapi }\n\nThe first step is to install FastAPI.\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then **install FastAPI**:\n\n
\n\n```console\n$ pip install \"fastapi[standard]\"\n\n---> 100%\n```\n\n
\n\n/// note\n\nWhen you install with `pip install \"fastapi[standard]\"` it comes with some default optional standard dependencies, including `fastapi-cloud-cli`, which allows you to deploy to [FastAPI Cloud](https://fastapicloud.com).\n\nIf you don't want to have those optional dependencies, you can instead install `pip install fastapi`.\n\nIf you want to install the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install \"fastapi[standard-no-fastapi-cloud-cli]\"`.\n\n///\n\n/// tip\n\nFastAPI has an [official extension for VS Code](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode) (and Cursor), which provides a lot of features, including a path operation explorer, path operation search, CodeLens navigation in tests (jump to definition from tests), and FastAPI Cloud deployment and logs, all from your editor.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/index.md", "symbol": "Install FastAPI { #install-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/index.md#L61-L92", "start_line": 61, "end_line": 92} {"id": "docs/en/docs/tutorial/index.md::Advanced User Guide { #advanced-user-guide }::L93", "text": "# Doc: docs/en/docs/tutorial/index.md | Page: Tutorial - User Guide { #tutorial-user-guide } | Section: Advanced User Guide { #advanced-user-guide }\n## Advanced User Guide { #advanced-user-guide }\n\nThere is also an **Advanced User Guide** that you can read later after this **Tutorial - User Guide**.\n\nThe **Advanced User Guide** builds on this one, uses the same concepts, and teaches you some extra features.\n\nBut you should first read the **Tutorial - User Guide** (what you are reading right now).\n\nIt's designed so that you can build a complete application with just the **Tutorial - User Guide**, and then extend it in different ways, depending on your needs, using some of the additional ideas from the **Advanced User Guide**.", "source_type": "doc", "path": "docs/en/docs/tutorial/index.md", "symbol": "Advanced User Guide { #advanced-user-guide }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/index.md#L93-L101", "start_line": 93, "end_line": 101} {"id": "docs/en/docs/tutorial/metadata.md::Metadata and Docs URLs { #metadata-and-docs-urls }::L1", "text": "# Doc: docs/en/docs/tutorial/metadata.md | Page: Metadata and Docs URLs { #metadata-and-docs-urls } | Section: Metadata and Docs URLs { #metadata-and-docs-urls }\n# Metadata and Docs URLs { #metadata-and-docs-urls }\n\nYou can customize several metadata configurations in your **FastAPI** application.", "source_type": "doc", "path": "docs/en/docs/tutorial/metadata.md", "symbol": "Metadata and Docs URLs { #metadata-and-docs-urls }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/metadata.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/metadata.md::Metadata for API { #metadata-for-api }::L5", "text": "# Doc: docs/en/docs/tutorial/metadata.md | Page: Metadata and Docs URLs { #metadata-and-docs-urls } | Section: Metadata for API { #metadata-for-api }\n## Metadata for API { #metadata-for-api }\n\nYou can set the following fields that are used in the OpenAPI specification and the automatic API docs UIs:\n\n| Parameter | Type | Description |\n|------------|------|-------------|\n| `title` | `str` | The title of the API. |\n| `summary` | `str` | A short summary of the API. Available since OpenAPI 3.1.0, FastAPI 0.99.0. |\n| `description` | `str` | A short description of the API. It can use Markdown. |\n| `version` | `str` | The version of the API. This is the version of your own application, not of OpenAPI. For example `2.5.0`. |\n| `terms_of_service` | `str` | A URL to the Terms of Service for the API. If provided, this has to be a URL. |\n| `contact` | `dict` | The contact information for the exposed API. It can contain several fields.
contact fields
ParameterTypeDescription
namestrThe identifying name of the contact person/organization.
urlstrThe URL pointing to the contact information. MUST be in the format of a URL.
emailstrThe email address of the contact person/organization. MUST be in the format of an email address.
|\n| `license_info` | `dict` | The license information for the exposed API. It can contain several fields.
license_info fields
ParameterTypeDescription
namestrREQUIRED (if a license_info is set). The license name used for the API.
identifierstrAn [SPDX](https://spdx.org/licenses/) license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrA URL to the license used for the API. MUST be in the format of a URL.
|\n\nYou can set them as follows:\n\n{* ../../docs_src/metadata/tutorial001_py310.py hl[3:16, 19:32] *}\n\n/// tip\n\nYou can write Markdown in the `description` field and it will be rendered in the output.\n\n///\n\nWith this configuration, the automatic API docs would look like:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/metadata.md", "symbol": "Metadata for API { #metadata-for-api }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/metadata.md#L5-L32", "start_line": 5, "end_line": 32} {"id": "docs/en/docs/tutorial/metadata.md::License identifier { #license-identifier }::L33", "text": "# Doc: docs/en/docs/tutorial/metadata.md | Page: Metadata and Docs URLs { #metadata-and-docs-urls } | Section: License identifier { #license-identifier }\n## License identifier { #license-identifier }\n\nSince OpenAPI 3.1.0 and FastAPI 0.99.0, you can also set the `license_info` with an `identifier` instead of a `url`.\n\nFor example:\n\n{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/metadata.md", "symbol": "License identifier { #license-identifier }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/metadata.md#L33-L40", "start_line": 33, "end_line": 40} {"id": "docs/en/docs/tutorial/metadata.md::Metadata for tags { #metadata-for-tags }::L41", "text": "# Doc: docs/en/docs/tutorial/metadata.md | Page: Metadata and Docs URLs { #metadata-and-docs-urls } | Section: Metadata for tags { #metadata-for-tags }\n## Metadata for tags { #metadata-for-tags }\n\nYou can also add additional metadata for the different tags used to group your path operations with the parameter `openapi_tags`.\n\nIt takes a list containing one dictionary for each tag.\n\nEach dictionary can contain:\n\n* `name` (**required**): a `str` with the same tag name you use in the `tags` parameter in your *path operations* and `APIRouter`s.\n* `description`: a `str` with a short description for the tag. It can have Markdown and will be shown in the docs UI.\n* `externalDocs`: a `dict` describing external documentation with:\n * `description`: a `str` with a short description for the external docs.\n * `url` (**required**): a `str` with the URL for the external documentation.\n\n### Create metadata for tags { #create-metadata-for-tags }\n\nLet's try that in an example with tags for `users` and `items`.\n\nCreate metadata for your tags and pass it to the `openapi_tags` parameter:\n\n{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}\n\nNotice that you can use Markdown inside of the descriptions, for example \"login\" will be shown in bold (**login**) and \"fancy\" will be shown in italics (_fancy_).\n\n/// tip\n\nYou don't have to add metadata for all the tags that you use.\n\n///\n\n### Use your tags { #use-your-tags }\n\nUse the `tags` parameter with your *path operations* (and `APIRouter`s) to assign them to different tags:\n\n{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}\n\n/// note\n\nRead more about tags in [Path Operation Configuration](path-operation-configuration.md#tags).\n\n///\n\n### Check the docs { #check-the-docs }\n\nNow, if you check the docs, they will show all the additional metadata:\n\n\n\n### Order of tags { #order-of-tags }\n\nThe order of each tag metadata dictionary also defines the order shown in the docs UI.\n\nFor example, even though `users` would go after `items` in alphabetical order, it is shown before them, because we added their metadata as the first dictionary in the list.", "source_type": "doc", "path": "docs/en/docs/tutorial/metadata.md", "symbol": "Metadata for tags { #metadata-for-tags }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/metadata.md#L41-L94", "start_line": 41, "end_line": 94} {"id": "docs/en/docs/tutorial/metadata.md::OpenAPI URL { #openapi-url }::L95", "text": "# Doc: docs/en/docs/tutorial/metadata.md | Page: Metadata and Docs URLs { #metadata-and-docs-urls } | Section: OpenAPI URL { #openapi-url }\n## OpenAPI URL { #openapi-url }\n\nBy default, the OpenAPI schema is served at `/openapi.json`.\n\nBut you can configure it with the parameter `openapi_url`.\n\nFor example, to set it to be served at `/api/v1/openapi.json`:\n\n{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}\n\nIf you want to disable the OpenAPI schema completely you can set `openapi_url=None`, that will also disable the documentation user interfaces that use it.", "source_type": "doc", "path": "docs/en/docs/tutorial/metadata.md", "symbol": "OpenAPI URL { #openapi-url }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/metadata.md#L95-L106", "start_line": 95, "end_line": 106} {"id": "docs/en/docs/tutorial/metadata.md::Docs URLs { #docs-urls }::L107", "text": "# Doc: docs/en/docs/tutorial/metadata.md | Page: Metadata and Docs URLs { #metadata-and-docs-urls } | Section: Docs URLs { #docs-urls }\n## Docs URLs { #docs-urls }\n\nYou can configure the two documentation user interfaces included:\n\n* **Swagger UI**: served at `/docs`.\n * You can set its URL with the parameter `docs_url`.\n * You can disable it by setting `docs_url=None`.\n* **ReDoc**: served at `/redoc`.\n * You can set its URL with the parameter `redoc_url`.\n * You can disable it by setting `redoc_url=None`.\n\nFor example, to set Swagger UI to be served at `/documentation` and disable ReDoc:\n\n{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/metadata.md", "symbol": "Docs URLs { #docs-urls }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/metadata.md#L107-L120", "start_line": 107, "end_line": 120} {"id": "docs/en/docs/tutorial/middleware.md::Middleware { #middleware }::L1", "text": "# Doc: docs/en/docs/tutorial/middleware.md | Page: Middleware { #middleware } | Section: Middleware { #middleware }\n# Middleware { #middleware }\n\nYou can add middleware to **FastAPI** applications.\n\nA \"middleware\" is a function that works with every **request** before it is processed by any specific *path operation*. And also with every **response** before returning it.\n\n* It takes each **request** that comes to your application.\n* It can then do something to that **request** or run any needed code.\n* Then it passes the **request** to be processed by the rest of the application (by some *path operation*).\n* It then takes the **response** generated by the application (by some *path operation*).\n* It can do something to that **response** or run any needed code.\n* Then it returns the **response**.\n\n/// note | Technical Details\n\nIf you have dependencies with `yield`, the exit code will run *after* the middleware.\n\nIf there were any background tasks (covered in the [Background Tasks](background-tasks.md) section, you will see it later), they will run *after* all the middleware.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/middleware.md", "symbol": "Middleware { #middleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/middleware.md#L1-L21", "start_line": 1, "end_line": 21} {"id": "docs/en/docs/tutorial/middleware.md::Create a middleware { #create-a-middleware }::L22", "text": "# Doc: docs/en/docs/tutorial/middleware.md | Page: Middleware { #middleware } | Section: Create a middleware { #create-a-middleware }\n## Create a middleware { #create-a-middleware }\n\nTo create a middleware you use the decorator `@app.middleware(\"http\")` on top of a function.\n\nThe middleware function receives:\n\n* The `request`.\n* A function `call_next` that will receive the `request` as a parameter.\n * This function will pass the `request` to the corresponding *path operation*.\n * Then it returns the `response` generated by the corresponding *path operation*.\n* You can then further modify the `response` before returning it.\n\n{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}\n\n/// tip\n\nKeep in mind that custom proprietary headers can be added [using the `X-` prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).\n\nBut if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md)) using the parameter `expose_headers` documented in [Starlette's CORS docs](https://www.starlette.dev/middleware/#corsmiddleware).\n\n///\n\n/// note | Technical Details\n\nYou could also use `from starlette.requests import Request`.\n\n**FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette.\n\n///\n\n### Before and after the `response` { #before-and-after-the-response }\n\nYou can add code to be run with the `request`, before any *path operation* receives it.\n\nAnd also after the `response` is generated, before returning it.\n\nFor example, you could add a custom header `X-Process-Time` containing the time in seconds that it took to process the request and generate a response:\n\n{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}\n\n/// tip\n\nHere we use [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) instead of `time.time()` because it can be more precise for these use cases. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/middleware.md", "symbol": "Create a middleware { #create-a-middleware }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/middleware.md#L22-L67", "start_line": 22, "end_line": 67} {"id": "docs/en/docs/tutorial/middleware.md::Multiple middleware execution order { #multiple-middleware-execution-order }::L68", "text": "# Doc: docs/en/docs/tutorial/middleware.md | Page: Middleware { #middleware } | Section: Multiple middleware execution order { #multiple-middleware-execution-order }\n## Multiple middleware execution order { #multiple-middleware-execution-order }\n\nWhen you add multiple middlewares using either `@app.middleware()` decorator or `app.add_middleware()` method, each new middleware wraps the application, forming a stack. The last middleware added is the *outermost*, and the first is the *innermost*.\n\nOn the request path, the *outermost* middleware runs first.\n\nOn the response path, it runs last.\n\nFor example:\n\n```Python\napp.add_middleware(MiddlewareA)\napp.add_middleware(MiddlewareB)\n```\n\nThis results in the following execution order:\n\n* **Request**: MiddlewareB → MiddlewareA → route\n\n* **Response**: route → MiddlewareA → MiddlewareB\n\nThis stacking behavior ensures that middlewares are executed in a predictable and controllable order.", "source_type": "doc", "path": "docs/en/docs/tutorial/middleware.md", "symbol": "Multiple middleware execution order { #multiple-middleware-execution-order }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/middleware.md#L68-L90", "start_line": 68, "end_line": 90} {"id": "docs/en/docs/tutorial/middleware.md::Other middlewares { #other-middlewares }::L91", "text": "# Doc: docs/en/docs/tutorial/middleware.md | Page: Middleware { #middleware } | Section: Other middlewares { #other-middlewares }\n## Other middlewares { #other-middlewares }\n\nYou can later read more about other middlewares in the [Advanced User Guide: Advanced Middleware](../advanced/middleware.md).\n\nYou will read about how to handle CORS with a middleware in the next section.", "source_type": "doc", "path": "docs/en/docs/tutorial/middleware.md", "symbol": "Other middlewares { #other-middlewares }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/middleware.md#L91-L95", "start_line": 91, "end_line": 95} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Path Operation Configuration { #path-operation-configuration }::L1", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Path Operation Configuration { #path-operation-configuration }\n# Path Operation Configuration { #path-operation-configuration }\n\nThere are several parameters that you can pass to your *path operation decorator* to configure it.\n\n/// warning\n\nNotice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Path Operation Configuration { #path-operation-configuration }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L1-L10", "start_line": 1, "end_line": 10} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Response Status Code { #response-status-code }::L11", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Response Status Code { #response-status-code }\n## Response Status Code { #response-status-code }\n\nYou can define the (HTTP) `status_code` to be used in the response of your *path operation*.\n\nYou can pass directly the `int` code, like `404`.\n\nBut if you don't remember what each number code is for, you can use the shortcut constants in `status`:\n\n{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}\n\nThat status code will be used in the response and will be added to the OpenAPI schema.\n\n/// note | Technical Details\n\nYou could also use `from starlette import status`.\n\n**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Response Status Code { #response-status-code }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L11-L30", "start_line": 11, "end_line": 30} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Tags { #tags }::L31", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Tags { #tags }\n## Tags { #tags }\n\nYou can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`):\n\n{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}\n\nThey will be added to the OpenAPI schema and used by the automatic documentation interfaces:\n\n\n\n### Tags with Enums { #tags-with-enums }\n\nIf you have a big application, you might end up accumulating **several tags**, and you would want to make sure you always use the **same tag** for related *path operations*.\n\nIn these cases, it could make sense to store the tags in an `Enum`.\n\n**FastAPI** supports that the same way as with plain strings:\n\n{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Tags { #tags }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L31-L50", "start_line": 31, "end_line": 50} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Summary and description { #summary-and-description }::L51", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Summary and description { #summary-and-description }\n## Summary and description { #summary-and-description }\n\nYou can add a `summary` and `description`:\n\n{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Summary and description { #summary-and-description }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L51-L56", "start_line": 51, "end_line": 56} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Description from docstring { #description-from-docstring }::L57", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Description from docstring { #description-from-docstring }\n## Description from docstring { #description-from-docstring }\n\nAs descriptions tend to be long and cover multiple lines, you can declare the *path operation* description in the function docstring and **FastAPI** will read it from there.\n\nYou can write [Markdown](https://en.wikipedia.org/wiki/Markdown) in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).\n\n{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}\n\nIt will be used in the interactive docs:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Description from docstring { #description-from-docstring }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L57-L68", "start_line": 57, "end_line": 68} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Response description { #response-description }::L69", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Response description { #response-description }\n## Response description { #response-description }\n\nYou can specify the response description with the parameter `response_description`:\n\n{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}\n\n/// note\n\nNotice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general.\n\n///\n\n/// tip\n\nOpenAPI specifies that each *path operation* requires a response description.\n\nSo, if you don't provide one, **FastAPI** will automatically generate one of \"Successful response\".\n\n///\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Response description { #response-description }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L69-L90", "start_line": 69, "end_line": 90} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Deprecate a *path operation* { #deprecate-a-path-operation }::L91", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Deprecate a *path operation* { #deprecate-a-path-operation }\n## Deprecate a *path operation* { #deprecate-a-path-operation }\n\nIf you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`:\n\n{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}\n\nIt will be clearly marked as deprecated in the interactive docs:\n\n\n\nCheck how deprecated and non-deprecated *path operations* look:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Deprecate a *path operation* { #deprecate-a-path-operation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L91-L104", "start_line": 91, "end_line": 104} {"id": "docs/en/docs/tutorial/path-operation-configuration.md::Recap { #recap }::L105", "text": "# Doc: docs/en/docs/tutorial/path-operation-configuration.md | Page: Path Operation Configuration { #path-operation-configuration } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can configure and add metadata for your *path operations* easily by passing parameters to the *path operation decorators*.", "source_type": "doc", "path": "docs/en/docs/tutorial/path-operation-configuration.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-operation-configuration.md#L105-L107", "start_line": 105, "end_line": 107} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations }::L1", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations }\n# Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations }\n\nIn the same way that you can declare more validations and metadata for query parameters with `Query`, you can declare the same type of validations and metadata for path parameters with `Path`.", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Import `Path` { #import-path }::L5", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Import `Path` { #import-path }\n## Import `Path` { #import-path }\n\nFirst, import `Path` from `fastapi`, and import `Annotated`:\n\n{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}\n\n/// note\n\nFastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.\n\nIf you have an older version, you would get errors when trying to use `Annotated`.\n\nMake sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions) to at least 0.95.1 before using `Annotated`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Import `Path` { #import-path }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L5-L20", "start_line": 5, "end_line": 20} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Declare metadata { #declare-metadata }::L21", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Declare metadata { #declare-metadata }\n## Declare metadata { #declare-metadata }\n\nYou can declare all the same parameters as for `Query`.\n\nFor example, to declare a `title` metadata value for the path parameter `item_id` you can type:\n\n{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}\n\n/// note\n\nA path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Declare metadata { #declare-metadata }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L21-L34", "start_line": 21, "end_line": 34} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Order the parameters as you need { #order-the-parameters-as-you-need }::L35", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Order the parameters as you need { #order-the-parameters-as-you-need }\n## Order the parameters as you need { #order-the-parameters-as-you-need }\n\n/// tip\n\nThis is probably not as important or necessary if you use `Annotated`.\n\n///\n\nLet's say that you want to declare the query parameter `q` as a required `str`.\n\nAnd you don't need to declare anything else for that parameter, so you don't really need to use `Query`.\n\nBut you still need to use `Path` for the `item_id` path parameter. And you don't want to use `Annotated` for some reason.\n\nPython will complain if you put a value with a \"default\" before a value that doesn't have a \"default\".\n\nBut you can re-order them, and have the value without a default (the query parameter `q`) first.\n\nIt doesn't matter for **FastAPI**. It will detect the parameters by their names, types and default declarations (`Query`, `Path`, etc), it doesn't care about the order.\n\nSo, you can declare your function as:\n\n{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}\n\nBut keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.\n\n{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Order the parameters as you need { #order-the-parameters-as-you-need }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L35-L62", "start_line": 35, "end_line": 62} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Order the parameters as you need, tricks { #order-the-parameters-as-you-need-tricks }::L63", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Order the parameters as you need, tricks { #order-the-parameters-as-you-need-tricks }\n## Order the parameters as you need, tricks { #order-the-parameters-as-you-need-tricks }\n\n/// tip\n\nThis is probably not as important or necessary if you use `Annotated`.\n\n///\n\nHere's a **small trick** that can be handy, but you won't need it often.\n\nIf you want to:\n\n* declare the `q` query parameter without a `Query` nor any default value\n* declare the path parameter `item_id` using `Path`\n* have them in a different order\n* not use `Annotated`\n\n...Python has a little special syntax for that.\n\nPass `*`, as the first parameter of the function.\n\nPython won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value.\n\n{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}\n\n### Better with `Annotated` { #better-with-annotated }\n\nKeep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.\n\n{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Order the parameters as you need, tricks { #order-the-parameters-as-you-need-tricks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L63-L93", "start_line": 63, "end_line": 93} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Number validations: greater than or equal { #number-validations-greater-than-or-equal }::L94", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Number validations: greater than or equal { #number-validations-greater-than-or-equal }\n## Number validations: greater than or equal { #number-validations-greater-than-or-equal }\n\nWith `Query` and `Path` (and others you'll see later) you can declare number constraints.\n\nHere, with `ge=1`, `item_id` will need to be an integer number \"`g`reater than or `e`qual\" to `1`.\n\n{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Number validations: greater than or equal { #number-validations-greater-than-or-equal }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L94-L101", "start_line": 94, "end_line": 101} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Number validations: greater than and less than or equal { #number-validations-greater-than-and-less-than-or-equal }::L102", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Number validations: greater than and less than or equal { #number-validations-greater-than-and-less-than-or-equal }\n## Number validations: greater than and less than or equal { #number-validations-greater-than-and-less-than-or-equal }\n\nThe same applies for:\n\n* `gt`: `g`reater `t`han\n* `le`: `l`ess than or `e`qual\n\n{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Number validations: greater than and less than or equal { #number-validations-greater-than-and-less-than-or-equal }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L102-L110", "start_line": 102, "end_line": 110} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Number validations: floats, greater than and less than { #number-validations-floats-greater-than-and-less-than }::L111", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Number validations: floats, greater than and less than { #number-validations-floats-greater-than-and-less-than }\n## Number validations: floats, greater than and less than { #number-validations-floats-greater-than-and-less-than }\n\nNumber validations also work for `float` values.\n\nHere's where it becomes important to be able to declare gt and not just ge. As with it you can require, for example, that a value must be greater than `0`, even if it is less than `1`.\n\nSo, `0.5` would be a valid value. But `0.0` or `0` would not.\n\nAnd the same for lt.\n\n{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Number validations: floats, greater than and less than { #number-validations-floats-greater-than-and-less-than }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L111-L122", "start_line": 111, "end_line": 122} {"id": "docs/en/docs/tutorial/path-params-numeric-validations.md::Recap { #recap }::L123", "text": "# Doc: docs/en/docs/tutorial/path-params-numeric-validations.md | Page: Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations } | Section: Recap { #recap }\n## Recap { #recap }\n\nWith `Query`, `Path` (and others you haven't seen yet) you can declare metadata and string validations in the same ways as with [Query Parameters and String Validations](query-params-str-validations.md).\n\nAnd you can also declare numeric validations:\n\n* `gt`: `g`reater `t`han\n* `ge`: `g`reater than or `e`qual\n* `lt`: `l`ess `t`han\n* `le`: `l`ess than or `e`qual\n\n/// note\n\n`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.\n\nAll of them share the same parameters for additional validation and metadata you have seen.\n\n///\n\n/// note | Technical Details\n\nWhen you import `Query`, `Path` and others from `fastapi`, they are actually functions.\n\nThat when called, return instances of classes of the same name.\n\nSo, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.\n\nThese functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.\n\nThat way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params-numeric-validations.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params-numeric-validations.md#L123-L154", "start_line": 123, "end_line": 154} {"id": "docs/en/docs/tutorial/path-params.md::Path Parameters { #path-parameters }::L1", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Path Parameters { #path-parameters }\n# Path Parameters { #path-parameters }\n\nYou can declare path \"parameters\" or \"variables\" with the same syntax used by Python format strings:\n\n{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}\n\nThe value of the path parameter `item_id` will be passed to your function as the argument `item_id`.\n\nSo, if you run this example and go to [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), you will see a response of:\n\n```JSON\n{\"item_id\":\"foo\"}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Path Parameters { #path-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L1-L14", "start_line": 1, "end_line": 14} {"id": "docs/en/docs/tutorial/path-params.md::Path parameters with types { #path-parameters-with-types }::L15", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Path parameters with types { #path-parameters-with-types }\n## Path parameters with types { #path-parameters-with-types }\n\nYou can declare the type of a path parameter in the function, using standard Python type annotations:\n\n{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}\n\nIn this case, `item_id` is declared to be an `int`.\n\n/// tip\n\nThis will give you editor support inside of your function, with error checks, completion, etc.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Path parameters with types { #path-parameters-with-types }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L15-L28", "start_line": 15, "end_line": 28} {"id": "docs/en/docs/tutorial/path-params.md::Data conversion { #data-conversion }::L29", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Data conversion { #data-conversion }\n## Data conversion { #data-conversion }\n\nIf you run this example and open your browser at [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3), you will see a response of:\n\n```JSON\n{\"item_id\":3}\n```\n\n/// tip\n\nNotice that the value your function received (and returned) is `3`, as a Python `int`, not a string `\"3\"`.\n\nSo, with that type declaration, **FastAPI** gives you automatic request \"parsing\".\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Data conversion { #data-conversion }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L29-L44", "start_line": 29, "end_line": 44} {"id": "docs/en/docs/tutorial/path-params.md::Data validation { #data-validation }::L45", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Data validation { #data-validation }\n## Data validation { #data-validation }\n\nBut if you go to the browser at [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), you will see a nice HTTP error of:\n\n```JSON\n{\n \"detail\": [\n {\n \"type\": \"int_parsing\",\n \"loc\": [\n \"path\",\n \"item_id\"\n ],\n \"msg\": \"Input should be a valid integer, unable to parse string as an integer\",\n \"input\": \"foo\"\n }\n ]\n}\n```\n\nbecause the path parameter `item_id` had a value of `\"foo\"`, which is not an `int`.\n\nThe same error would appear if you provided a `float` instead of an `int`, as in: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)\n\n/// tip\n\nSo, with the same Python type declaration, **FastAPI** gives you data validation.\n\nNotice that the error also clearly states exactly the point where the validation didn't pass.\n\nThis is incredibly helpful while developing and debugging code that interacts with your API.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Data validation { #data-validation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L45-L78", "start_line": 45, "end_line": 78} {"id": "docs/en/docs/tutorial/path-params.md::Documentation { #documentation }::L79", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Documentation { #documentation }\n## Documentation { #documentation }\n\nAnd when you open your browser at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), you will see an automatic, interactive, API documentation like:\n\n\n\n/// tip\n\nAgain, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).\n\nNotice that the path parameter is declared to be an integer.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Documentation { #documentation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L79-L92", "start_line": 79, "end_line": 92} {"id": "docs/en/docs/tutorial/path-params.md::Standards-based benefits, alternative documentation { #standards-based-benefits-alternative-documentation }::L93", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Standards-based benefits, alternative documentation { #standards-based-benefits-alternative-documentation }\n## Standards-based benefits, alternative documentation { #standards-based-benefits-alternative-documentation }\n\nAnd because the generated schema is from the [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) standard, there are many compatible tools.\n\nBecause of this, **FastAPI** itself provides an alternative API documentation (using ReDoc), which you can access at [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):\n\n\n\nThe same way, there are many compatible tools. Including code generation tools for many languages.", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Standards-based benefits, alternative documentation { #standards-based-benefits-alternative-documentation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L93-L102", "start_line": 93, "end_line": 102} {"id": "docs/en/docs/tutorial/path-params.md::Pydantic { #pydantic }::L103", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Pydantic { #pydantic }\n## Pydantic { #pydantic }\n\nAll the data validation is performed under the hood by [Pydantic](https://docs.pydantic.dev/), so you get all the benefits from it. And you know you are in good hands.\n\nYou can use the same type declarations with `str`, `float`, `bool` and many other complex data types.\n\nSeveral of these are explored in the next chapters of the tutorial.", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Pydantic { #pydantic }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L103-L110", "start_line": 103, "end_line": 110} {"id": "docs/en/docs/tutorial/path-params.md::Order matters { #order-matters }::L111", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Order matters { #order-matters }\n## Order matters { #order-matters }\n\nWhen creating *path operations*, you can find situations where you have a fixed path.\n\nLike `/users/me`, let's say that it's to get data about the current user.\n\nAnd then you can also have a path `/users/{user_id}` to get data about a specific user by some user ID.\n\nBecause *path operations* are evaluated in order, you need to make sure that the path for `/users/me` is declared before the one for `/users/{user_id}`:\n\n{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}\n\nOtherwise, the path for `/users/{user_id}` would match also for `/users/me`, \"thinking\" that it's receiving a parameter `user_id` with a value of `\"me\"`.\n\nSimilarly, you cannot redefine a path operation:\n\n{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}\n\nThe first one will always be used since the path matches first.", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Order matters { #order-matters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L111-L130", "start_line": 111, "end_line": 130} {"id": "docs/en/docs/tutorial/path-params.md::Predefined values { #predefined-values }::L131", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Predefined values { #predefined-values }\n## Predefined values { #predefined-values }\n\nIf you have a *path operation* that receives a *path parameter*, but you want the possible valid *path parameter* values to be predefined, you can use a standard Python `Enum`.\n\n### Create an `Enum` class { #create-an-enum-class }\n\nImport `Enum` and create a sub-class that inherits from `str` and from `Enum`.\n\nBy inheriting from `str` the API docs will be able to know that the values must be of type `string` and will be able to render correctly.\n\nThen create class attributes with fixed values, which will be the available valid values:\n\n{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}\n\n/// tip\n\nIf you are wondering, \"AlexNet\", \"ResNet\", and \"LeNet\" are just names of Machine Learning models.\n\n///\n\n### Declare a *path parameter* { #declare-a-path-parameter }\n\nThen create a *path parameter* with a type annotation using the enum class you created (`ModelName`):\n\n{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}\n\n### Check the docs { #check-the-docs }\n\nBecause the available values for the *path parameter* are predefined, the interactive docs can show them nicely:\n\n\n\n### Working with Python *enumerations* { #working-with-python-enumerations }\n\nThe value of the *path parameter* will be an *enumeration member*.\n\n#### Compare *enumeration members* { #compare-enumeration-members }\n\nYou can compare it with the *enumeration member* in your created enum `ModelName`:\n\n{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}\n\n#### Get the *enumeration value* { #get-the-enumeration-value }\n\nYou can get the actual value (a `str` in this case) using `model_name.value`, or in general, `your_enum_member.value`:\n\n{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}\n\n/// tip\n\nYou could also access the value `\"lenet\"` with `ModelName.lenet.value`.\n\n///\n\n#### Return *enumeration members* { #return-enumeration-members }\n\nYou can return *enum members* from your *path operation*, even nested in a JSON body (e.g. a `dict`).\n\nThey will be converted to their corresponding values (strings in this case) before returning them to the client:\n\n{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}\n\nIn your client you will get a JSON response like:\n\n```JSON\n{\n \"model_name\": \"alexnet\",\n \"message\": \"Deep Learning FTW!\"\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Predefined values { #predefined-values }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L131-L201", "start_line": 131, "end_line": 201} {"id": "docs/en/docs/tutorial/path-params.md::Path parameters containing paths { #path-parameters-containing-paths }::L202", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Path parameters containing paths { #path-parameters-containing-paths }\n## Path parameters containing paths { #path-parameters-containing-paths }\n\nLet's say you have a *path operation* with a path `/files/{file_path}`.\n\nBut you need `file_path` itself to contain a *path*, like `home/johndoe/myfile.txt`.\n\nSo, the URL for that file would be something like: `/files/home/johndoe/myfile.txt`.\n\n### OpenAPI support { #openapi-support }\n\nOpenAPI doesn't support a way to declare a *path parameter* to contain a *path* inside, as that could lead to scenarios that are difficult to test and define.\n\nNevertheless, you can still do it in **FastAPI**, using one of the internal tools from Starlette.\n\nAnd the docs would still work, although not adding any documentation telling that the parameter should contain a path.\n\n### Path convertor { #path-convertor }\n\nUsing an option directly from Starlette you can declare a *path parameter* containing a *path* using a URL like:\n\n```\n/files/{file_path:path}\n```\n\nIn this case, the name of the parameter is `file_path`, and the last part, `:path`, tells it that the parameter should match any *path*.\n\nSo, you can use it with:\n\n{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}\n\n/// tip\n\nYou might need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).\n\nIn that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Path parameters containing paths { #path-parameters-containing-paths }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L202-L239", "start_line": 202, "end_line": 239} {"id": "docs/en/docs/tutorial/path-params.md::Recap { #recap }::L240", "text": "# Doc: docs/en/docs/tutorial/path-params.md | Page: Path Parameters { #path-parameters } | Section: Recap { #recap }\n## Recap { #recap }\n\nWith **FastAPI**, by using short, intuitive and standard Python type declarations, you get:\n\n* Editor support: error checks, autocompletion, etc.\n* Data \"parsing\"\n* Data validation\n* API annotation and automatic documentation\n\nAnd you only have to declare them once.\n\nThat's probably the main visible advantage of **FastAPI** compared to alternative frameworks (apart from the raw performance).", "source_type": "doc", "path": "docs/en/docs/tutorial/path-params.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/path-params.md#L240-L251", "start_line": 240, "end_line": 251} {"id": "docs/en/docs/tutorial/query-param-models.md::Query Parameter Models { #query-parameter-models }::L1", "text": "# Doc: docs/en/docs/tutorial/query-param-models.md | Page: Query Parameter Models { #query-parameter-models } | Section: Query Parameter Models { #query-parameter-models }\n# Query Parameter Models { #query-parameter-models }\n\nIf you have a group of **query parameters** that are related, you can create a **Pydantic model** to declare them.\n\nThis would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎\n\n/// note\n\nThis is supported since FastAPI version `0.115.0`. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-param-models.md", "symbol": "Query Parameter Models { #query-parameter-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-param-models.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/tutorial/query-param-models.md::Query Parameters with a Pydantic Model { #query-parameters-with-a-pydantic-model }::L13", "text": "# Doc: docs/en/docs/tutorial/query-param-models.md | Page: Query Parameter Models { #query-parameter-models } | Section: Query Parameters with a Pydantic Model { #query-parameters-with-a-pydantic-model }\n## Query Parameters with a Pydantic Model { #query-parameters-with-a-pydantic-model }\n\nDeclare the **query parameters** that you need in a **Pydantic model**, and then declare the parameter as `Query`:\n\n{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}\n\n**FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined.", "source_type": "doc", "path": "docs/en/docs/tutorial/query-param-models.md", "symbol": "Query Parameters with a Pydantic Model { #query-parameters-with-a-pydantic-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-param-models.md#L13-L20", "start_line": 13, "end_line": 20} {"id": "docs/en/docs/tutorial/query-param-models.md::Check the Docs { #check-the-docs }::L21", "text": "# Doc: docs/en/docs/tutorial/query-param-models.md | Page: Query Parameter Models { #query-parameter-models } | Section: Check the Docs { #check-the-docs }\n## Check the Docs { #check-the-docs }\n\nYou can see the query parameters in the docs UI at `/docs`:\n\n
\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/query-param-models.md", "symbol": "Check the Docs { #check-the-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-param-models.md#L21-L28", "start_line": 21, "end_line": 28} {"id": "docs/en/docs/tutorial/query-param-models.md::Forbid Extra Query Parameters { #forbid-extra-query-parameters }::L29", "text": "# Doc: docs/en/docs/tutorial/query-param-models.md | Page: Query Parameter Models { #query-parameter-models } | Section: Forbid Extra Query Parameters { #forbid-extra-query-parameters }\n## Forbid Extra Query Parameters { #forbid-extra-query-parameters }\n\nIn some special use cases (probably not very common), you might want to **restrict** the query parameters that you want to receive.\n\nYou can use Pydantic's model configuration to `forbid` any `extra` fields:\n\n{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *}\n\nIf a client tries to send some **extra** data in the **query parameters**, they will receive an **error** response.\n\nFor example, if the client tries to send a `tool` query parameter with a value of `plumbus`, like:\n\n```http\nhttps://example.com/items/?limit=10&tool=plumbus\n```\n\nThey will receive an **error** response telling them that the query parameter `tool` is not allowed:\n\n```json\n{\n \"detail\": [\n {\n \"type\": \"extra_forbidden\",\n \"loc\": [\"query\", \"tool\"],\n \"msg\": \"Extra inputs are not permitted\",\n \"input\": \"plumbus\"\n }\n ]\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/query-param-models.md", "symbol": "Forbid Extra Query Parameters { #forbid-extra-query-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-param-models.md#L29-L59", "start_line": 29, "end_line": 59} {"id": "docs/en/docs/tutorial/query-param-models.md::Summary { #summary }::L60", "text": "# Doc: docs/en/docs/tutorial/query-param-models.md | Page: Query Parameter Models { #query-parameter-models } | Section: Summary { #summary }\n## Summary { #summary }\n\nYou can use **Pydantic models** to declare **query parameters** in **FastAPI**. 😎\n\n/// tip\n\nSpoiler alert: you can also use Pydantic models to declare cookies and headers, but you will read about that later in the tutorial. 🤫\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-param-models.md", "symbol": "Summary { #summary }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-param-models.md#L60-L68", "start_line": 60, "end_line": 68} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Query Parameters and String Validations { #query-parameters-and-string-validations }::L1", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Query Parameters and String Validations { #query-parameters-and-string-validations }\n# Query Parameters and String Validations { #query-parameters-and-string-validations }\n\n**FastAPI** allows you to declare additional information and validation for your parameters.\n\nLet's take this application as example:\n\n{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *}\n\nThe query parameter `q` is of type `str | None`, that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.\n\n/// note\n\nFastAPI will know that the value of `q` is not required because of the default value `= None`.\n\nHaving `str | None` will allow your editor to give you better support and detect errors.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Query Parameters and String Validations { #query-parameters-and-string-validations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L1-L18", "start_line": 1, "end_line": 18} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Additional validation { #additional-validation }::L19", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Additional validation { #additional-validation }\n## Additional validation { #additional-validation }\n\nWe are going to enforce that even though `q` is optional, whenever it is provided, **its length doesn't exceed 50 characters**.\n\n### Import `Query` and `Annotated` { #import-query-and-annotated }\n\nTo achieve that, first import:\n\n* `Query` from `fastapi`\n* `Annotated` from `typing`\n\n{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *}\n\n/// note\n\nFastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.\n\nIf you have an older version, you would get errors when trying to use `Annotated`.\n\nMake sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions) to at least 0.95.1 before using `Annotated`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Additional validation { #additional-validation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L19-L41", "start_line": 19, "end_line": 41} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Use `Annotated` in the type for the `q` parameter { #use-annotated-in-the-type-for-the-q-parameter }::L42", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Use `Annotated` in the type for the `q` parameter { #use-annotated-in-the-type-for-the-q-parameter }\n## Use `Annotated` in the type for the `q` parameter { #use-annotated-in-the-type-for-the-q-parameter }\n\nRemember I told you before that `Annotated` can be used to add metadata to your parameters in the [Python Types Intro](../python-types.md#type-hints-with-metadata-annotations)?\n\nNow it's the time to use it with FastAPI. 🚀\n\nWe had this type annotation:\n\n```Python\nq: str | None = None\n```\n\nWhat we will do is wrap that with `Annotated`, so it becomes:\n\n```Python\nq: Annotated[str | None] = None\n```\n\nBoth of those versions mean the same thing, `q` is a parameter that can be a `str` or `None`, and by default, it is `None`.\n\nNow let's jump to the fun stuff. 🎉", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Use `Annotated` in the type for the `q` parameter { #use-annotated-in-the-type-for-the-q-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L42-L63", "start_line": 42, "end_line": 63} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Add `Query` to `Annotated` in the `q` parameter { #add-query-to-annotated-in-the-q-parameter }::L64", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Add `Query` to `Annotated` in the `q` parameter { #add-query-to-annotated-in-the-q-parameter }\n## Add `Query` to `Annotated` in the `q` parameter { #add-query-to-annotated-in-the-q-parameter }\n\nNow that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`:\n\n{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *}\n\nNotice that the default value is still `None`, so the parameter is still optional.\n\nBut now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to have **additional validation** for this value, we want it to have maximum 50 characters. 😎\n\n/// tip\n\nHere we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`.\n\n///\n\nFastAPI will now:\n\n* **Validate** the data making sure that the max length is 50 characters\n* Show a **clear error** for the client when the data is not valid\n* **Document** the parameter in the OpenAPI schema *path operation* (so it will show up in the **automatic docs UI**)", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Add `Query` to `Annotated` in the `q` parameter { #add-query-to-annotated-in-the-q-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L64-L85", "start_line": 64, "end_line": 85} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Alternative (old): `Query` as the default value { #alternative-old-query-as-the-default-value }::L86", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Alternative (old): `Query` as the default value { #alternative-old-query-as-the-default-value }\n## Alternative (old): `Query` as the default value { #alternative-old-query-as-the-default-value }\n\nPrevious versions of FastAPI (before 0.95.0) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you.\n\n/// tip\n\nFor new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰\n\n///\n\nThis is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50:\n\n{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *}\n\nAs in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI).\n\nSo:\n\n```Python\nq: str | None = Query(default=None)\n```\n\n...makes the parameter optional, with a default value of `None`, the same as:\n\n\n```Python\nq: str | None = None\n```\n\nBut the `Query` version declares it explicitly as being a query parameter.\n\nThen, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings:\n\n```Python\nq: str | None = Query(default=None, max_length=50)\n```\n\nThis will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema *path operation*.\n\n### `Query` as the default value or in `Annotated` { #query-as-the-default-value-or-in-annotated }\n\nKeep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.\n\nInstead, use the actual default value of the function parameter. Otherwise, it would be inconsistent.\n\nFor example, this is not allowed:\n\n```Python\nq: Annotated[str, Query(default=\"rick\")] = \"morty\"\n```\n\n...because it's not clear if the default value should be `\"rick\"` or `\"morty\"`.\n\nSo, you would use (preferably):\n\n```Python\nq: Annotated[str, Query()] = \"rick\"\n```\n\n...or in older code bases you will find:\n\n```Python\nq: str = Query(default=\"rick\")\n```\n\n### Advantages of `Annotated` { #advantages-of-annotated }\n\n**Using `Annotated` is recommended** instead of the default value in function parameters, it is **better** for multiple reasons. 🤓\n\nThe **default** value of the **function parameter** is the **actual default** value, that's more intuitive with Python in general. 😌\n\nYou could **call** that same function in **other places** without FastAPI, and it would **work as expected**. If there's a **required** parameter (without a default value), your **editor** will let you know with an error, **Python** will also complain if you run it without passing the required parameter.\n\nWhen you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other places**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out.\n\nBecause `Annotated` can have more than one metadata annotation, you could now even use the same function with other tools, like [Typer](https://typer.tiangolo.com/). 🚀", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Alternative (old): `Query` as the default value { #alternative-old-query-as-the-default-value }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L86-L162", "start_line": 86, "end_line": 162} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Add more validations { #add-more-validations }::L163", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Add more validations { #add-more-validations }\n## Add more validations { #add-more-validations }\n\nYou can also add a parameter `min_length`:\n\n{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Add more validations { #add-more-validations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L163-L168", "start_line": 163, "end_line": 168} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Add regular expressions { #add-regular-expressions }::L169", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Add regular expressions { #add-regular-expressions }\n## Add regular expressions { #add-regular-expressions }\n\nYou can define a regular expression `pattern` that the parameter should match:\n\n{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}\n\nThis specific regular expression pattern checks that the received parameter value:\n\n* `^`: starts with the following characters, doesn't have characters before.\n* `fixedquery`: has the exact value `fixedquery`.\n* `$`: ends there, doesn't have any more characters after `fixedquery`.\n\nIf you feel lost with all these **\"regular expression\"** ideas, don't worry. They are a hard topic for many people. You can still do a lot of stuff without needing regular expressions yet.\n\nNow you know that whenever you need them you can use them in **FastAPI**.", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Add regular expressions { #add-regular-expressions }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L169-L184", "start_line": 169, "end_line": 184} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Default values { #default-values }::L185", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Default values { #default-values }\n## Default values { #default-values }\n\nYou can, of course, use default values other than `None`.\n\nLet's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `\"fixedquery\"`:\n\n{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *}\n\n/// note\n\nHaving a default value of any type, including `None`, makes the parameter optional (not required).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Default values { #default-values }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L185-L198", "start_line": 185, "end_line": 198} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Required parameters { #required-parameters }::L199", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Required parameters { #required-parameters }\n## Required parameters { #required-parameters }\n\nWhen we don't need to declare more validations or metadata, we can make the `q` query parameter required just by not declaring a default value, like:\n\n```Python\nq: str\n```\n\ninstead of:\n\n```Python\nq: str | None = None\n```\n\nBut we are now declaring it with `Query`, for example like:\n\n```Python\nq: Annotated[str | None, Query(min_length=3)] = None\n```\n\nSo, when you need to declare a value as required while using `Query`, you can simply not declare a default value:\n\n{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *}\n\n### Required, can be `None` { #required-can-be-none }\n\nYou can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`.\n\nTo do that, you can declare that `None` is a valid type but simply do not declare a default value:\n\n{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Required parameters { #required-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L199-L230", "start_line": 199, "end_line": 230} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Query parameter list / multiple values { #query-parameter-list-multiple-values }::L231", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Query parameter list / multiple values { #query-parameter-list-multiple-values }\n## Query parameter list / multiple values { #query-parameter-list-multiple-values }\n\nWhen you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values.\n\nFor example, to declare a query parameter `q` that can appear multiple times in the URL, you can write:\n\n{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *}\n\nThen, with a URL like:\n\n```\nhttp://localhost:8000/items/?q=foo&q=bar\n```\n\nyou would receive the multiple `q` *query parameters'* values (`foo` and `bar`) in a Python `list` inside your *path operation function*, in the *function parameter* `q`.\n\nSo, the response to that URL would be:\n\n```JSON\n{\n \"q\": [\n \"foo\",\n \"bar\"\n ]\n}\n```\n\n/// tip\n\nTo declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body.\n\n///\n\nThe interactive API docs will update accordingly, to allow multiple values:\n\n\n\n### Query parameter list / multiple values with defaults { #query-parameter-list-multiple-values-with-defaults }\n\nYou can also define a default `list` of values if none are provided:\n\n{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}\n\nIf you go to:\n\n```\nhttp://localhost:8000/items/\n```\n\nthe default of `q` will be: `[\"foo\", \"bar\"]` and your response will be:\n\n```JSON\n{\n \"q\": [\n \"foo\",\n \"bar\"\n ]\n}\n```\n\n#### Using just `list` { #using-just-list }\n\nYou can also use `list` directly instead of `list[str]`:\n\n{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}\n\n/// note\n\nKeep in mind that in this case, FastAPI won't check the contents of the list.\n\nFor example, `list[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Query parameter list / multiple values { #query-parameter-list-multiple-values }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L231-L304", "start_line": 231, "end_line": 304} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Declare more metadata { #declare-more-metadata }::L305", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Declare more metadata { #declare-more-metadata }\n## Declare more metadata { #declare-more-metadata }\n\nYou can add more information about the parameter.\n\nThat information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools.\n\n/// note\n\nKeep in mind that different tools might have different levels of OpenAPI support.\n\nSome of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development.\n\n///\n\nYou can add a `title`:\n\n{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}\n\nAnd a `description`:\n\n{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Declare more metadata { #declare-more-metadata }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L305-L326", "start_line": 305, "end_line": 326} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Alias parameters { #alias-parameters }::L327", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Alias parameters { #alias-parameters }\n## Alias parameters { #alias-parameters }\n\nImagine that you want the parameter to be `item-query`.\n\nLike in:\n\n```\nhttp://127.0.0.1:8000/items/?item-query=foobaritems\n```\n\nBut `item-query` is not a valid Python variable name.\n\nThe closest would be `item_query`.\n\nBut you still need it to be exactly `item-query`...\n\nThen you can declare an `alias`, and that alias is what will be used to find the parameter value:\n\n{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Alias parameters { #alias-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L327-L346", "start_line": 327, "end_line": 346} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Deprecating parameters { #deprecating-parameters }::L347", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Deprecating parameters { #deprecating-parameters }\n## Deprecating parameters { #deprecating-parameters }\n\nNow let's say you don't like this parameter anymore.\n\nYou have to leave it there a while because there are clients using it, but you want the docs to clearly show it as deprecated.\n\nThen pass the parameter `deprecated=True` to `Query`:\n\n{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}\n\nThe docs will show it like this:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Deprecating parameters { #deprecating-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L347-L360", "start_line": 347, "end_line": 360} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Exclude parameters from OpenAPI { #exclude-parameters-from-openapi }::L361", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Exclude parameters from OpenAPI { #exclude-parameters-from-openapi }\n## Exclude parameters from OpenAPI { #exclude-parameters-from-openapi }\n\nTo exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`:\n\n{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Exclude parameters from OpenAPI { #exclude-parameters-from-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L361-L366", "start_line": 361, "end_line": 366} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Custom Validation { #custom-validation }::L367", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Custom Validation { #custom-validation }\n## Custom Validation { #custom-validation }\n\nThere could be cases where you need to do some **custom validation** that can't be done with the parameters shown above.\n\nIn those cases, you can use a **custom validator function** that is applied after the normal validation (e.g. after validating that the value is a `str`).\n\nYou can achieve that using [Pydantic's `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) inside of `Annotated`.\n\n/// tip\n\nPydantic also has [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) and others. 🤓\n\n///\n\nFor example, this custom validator checks that the item ID starts with `isbn-` for an ISBN book number or with `imdb-` for an IMDB movie URL ID:\n\n{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}\n\n/// note\n\nThis is available with Pydantic version 2 or above. 😎\n\n///\n\n/// tip\n\nIf you need to do any type of validation that requires communicating with any **external component**, like a database or another API, you should instead use **FastAPI Dependencies**, you will learn about them later.\n\nThese custom validators are for things that can be checked with **only** the **same data** provided in the request.\n\n///\n\n### Understand that Code { #understand-that-code }\n\nThe important point is just using **`AfterValidator` with a function inside `Annotated`**. Feel free to skip this part. 🤸\n\n---\n\nBut if you're curious about this specific code example and you're still entertained, here are some extra details.\n\n#### String with `value.startswith()` { #string-with-value-startswith }\n\nDid you notice? A string using `value.startswith()` can take a tuple, and it will check each value in the tuple:\n\n{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}\n\n#### A Random Item { #a-random-item }\n\nWith `data.items()` we get an iterable object with tuples containing the key and value for each dictionary item.\n\nWe convert this iterable object into a proper `list` with `list(data.items())`.\n\nThen with `random.choice()` we can get a **random value** from the list, so, we get a tuple with `(id, name)`. It will be something like `(\"imdb-tt0371724\", \"The Hitchhiker's Guide to the Galaxy\")`.\n\nThen we **assign those two values** of the tuple to the variables `id` and `name`.\n\nSo, if the user didn't provide an item ID, they will still receive a random suggestion.\n\n...we do all this in a **single simple line**. 🤯 Don't you love Python? 🐍\n\n{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Custom Validation { #custom-validation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L367-L428", "start_line": 367, "end_line": 428} {"id": "docs/en/docs/tutorial/query-params-str-validations.md::Recap { #recap }::L429", "text": "# Doc: docs/en/docs/tutorial/query-params-str-validations.md | Page: Query Parameters and String Validations { #query-parameters-and-string-validations } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can declare additional validations and metadata for your parameters.\n\nGeneric validations and metadata:\n\n* `alias`\n* `title`\n* `description`\n* `deprecated`\n\nValidations specific for strings:\n\n* `min_length`\n* `max_length`\n* `pattern`\n\nCustom validations using `AfterValidator`.\n\nIn these examples you saw how to declare validations for `str` values.\n\nSee the next chapters to learn how to declare validations for other types, like numbers.", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params-str-validations.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params-str-validations.md#L429-L450", "start_line": 429, "end_line": 450} {"id": "docs/en/docs/tutorial/query-params.md::Query Parameters { #query-parameters }::L1", "text": "# Doc: docs/en/docs/tutorial/query-params.md | Page: Query Parameters { #query-parameters } | Section: Query Parameters { #query-parameters }\n# Query Parameters { #query-parameters }\n\nWhen you declare other function parameters that are not part of the path parameters, they are automatically interpreted as \"query\" parameters.\n\n{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}\n\nThe query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters.\n\nFor example, in the URL:\n\n```\nhttp://127.0.0.1:8000/items/?skip=0&limit=10\n```\n\n...the query parameters are:\n\n* `skip`: with a value of `0`\n* `limit`: with a value of `10`\n\nAs they are part of the URL, they are \"naturally\" strings.\n\nBut when you declare them with Python types (in the example above, as `int`), they are converted to that type and validated against it.\n\nAll the same processes that apply to path parameters also apply to query parameters:\n\n* Editor support (obviously)\n* Data \"parsing\"\n* Data validation\n* Automatic documentation", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params.md", "symbol": "Query Parameters { #query-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params.md#L1-L30", "start_line": 1, "end_line": 30} {"id": "docs/en/docs/tutorial/query-params.md::Defaults { #defaults }::L31", "text": "# Doc: docs/en/docs/tutorial/query-params.md | Page: Query Parameters { #query-parameters } | Section: Defaults { #defaults }\n## Defaults { #defaults }\n\nAs query parameters are not a fixed part of a path, they can be optional and can have default values.\n\nIn the example above they have default values of `skip=0` and `limit=10`.\n\nSo, going to the URL:\n\n```\nhttp://127.0.0.1:8000/items/\n```\n\nwould be the same as going to:\n\n```\nhttp://127.0.0.1:8000/items/?skip=0&limit=10\n```\n\nBut if you go to, for example:\n\n```\nhttp://127.0.0.1:8000/items/?skip=20\n```\n\nThe parameter values in your function will be:\n\n* `skip=20`: because you set it in the URL\n* `limit=10`: because that was the default value", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params.md", "symbol": "Defaults { #defaults }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params.md#L31-L59", "start_line": 31, "end_line": 59} {"id": "docs/en/docs/tutorial/query-params.md::Optional parameters { #optional-parameters }::L60", "text": "# Doc: docs/en/docs/tutorial/query-params.md | Page: Query Parameters { #query-parameters } | Section: Optional parameters { #optional-parameters }\n## Optional parameters { #optional-parameters }\n\nThe same way, you can declare optional query parameters, by setting their default to `None`:\n\n{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}\n\nIn this case, the function parameter `q` will be optional, and will be `None` by default.\n\n/// tip\n\nAlso notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params.md", "symbol": "Optional parameters { #optional-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params.md#L60-L73", "start_line": 60, "end_line": 73} {"id": "docs/en/docs/tutorial/query-params.md::Query parameter type conversion { #query-parameter-type-conversion }::L74", "text": "# Doc: docs/en/docs/tutorial/query-params.md | Page: Query Parameters { #query-parameters } | Section: Query parameter type conversion { #query-parameter-type-conversion }\n## Query parameter type conversion { #query-parameter-type-conversion }\n\nYou can also declare `bool` types, and they will be converted:\n\n{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}\n\nIn this case, if you go to:\n\n```\nhttp://127.0.0.1:8000/items/foo?short=1\n```\n\nor\n\n```\nhttp://127.0.0.1:8000/items/foo?short=True\n```\n\nor\n\n```\nhttp://127.0.0.1:8000/items/foo?short=true\n```\n\nor\n\n```\nhttp://127.0.0.1:8000/items/foo?short=on\n```\n\nor\n\n```\nhttp://127.0.0.1:8000/items/foo?short=yes\n```\n\nor any other case variation (uppercase, first letter in uppercase, etc), your function will see the parameter `short` with a `bool` value of `True`. Otherwise as `False`.", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params.md", "symbol": "Query parameter type conversion { #query-parameter-type-conversion }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params.md#L74-L112", "start_line": 74, "end_line": 112} {"id": "docs/en/docs/tutorial/query-params.md::Multiple path and query parameters { #multiple-path-and-query-parameters }::L113", "text": "# Doc: docs/en/docs/tutorial/query-params.md | Page: Query Parameters { #query-parameters } | Section: Multiple path and query parameters { #multiple-path-and-query-parameters }\n## Multiple path and query parameters { #multiple-path-and-query-parameters }\n\nYou can declare multiple path parameters and query parameters at the same time, **FastAPI** knows which is which.\n\nAnd you don't have to declare them in any specific order.\n\nThey will be detected by name:\n\n{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params.md", "symbol": "Multiple path and query parameters { #multiple-path-and-query-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params.md#L113-L122", "start_line": 113, "end_line": 122} {"id": "docs/en/docs/tutorial/query-params.md::Required query parameters { #required-query-parameters }::L123", "text": "# Doc: docs/en/docs/tutorial/query-params.md | Page: Query Parameters { #query-parameters } | Section: Required query parameters { #required-query-parameters }\n## Required query parameters { #required-query-parameters }\n\nWhen you declare a default value for non-path parameters (for now, we have only seen query parameters), then it is not required.\n\nIf you don't want to add a specific value but just make it optional, set the default as `None`.\n\nBut when you want to make a query parameter required, you can just not declare any default value:\n\n{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}\n\nHere the query parameter `needy` is a required query parameter of type `str`.\n\nIf you open in your browser a URL like:\n\n```\nhttp://127.0.0.1:8000/items/foo-item\n```\n\n...without adding the required parameter `needy`, you will see an error like:\n\n```JSON\n{\n \"detail\": [\n {\n \"type\": \"missing\",\n \"loc\": [\n \"query\",\n \"needy\"\n ],\n \"msg\": \"Field required\",\n \"input\": null\n }\n ]\n}\n```\n\nAs `needy` is a required parameter, you would need to set it in the URL:\n\n```\nhttp://127.0.0.1:8000/items/foo-item?needy=sooooneedy\n```\n\n...this would work:\n\n```JSON\n{\n \"item_id\": \"foo-item\",\n \"needy\": \"sooooneedy\"\n}\n```\n\nAnd of course, you can define some parameters as required, some as having a default value, and some entirely optional:\n\n{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}\n\nIn this case, there are 3 query parameters:\n\n* `needy`, a required `str`.\n* `skip`, an `int` with a default value of `0`.\n* `limit`, an optional `int`.\n\n/// tip\n\nYou could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/query-params.md", "symbol": "Required query parameters { #required-query-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/query-params.md#L123-L188", "start_line": 123, "end_line": 188} {"id": "docs/en/docs/tutorial/request-files.md::Request Files { #request-files }::L1", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: Request Files { #request-files }\n# Request Files { #request-files }\n\nYou can define files to be uploaded by the client using `File`.\n\n/// note\n\nTo receive uploaded files, first install [`python-multipart`](https://github.com/Kludex/python-multipart).\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:\n\n```console\n$ pip install python-multipart\n```\n\nThis is because uploaded files are sent as \"form data\".\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "Request Files { #request-files }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L1-L18", "start_line": 1, "end_line": 18} {"id": "docs/en/docs/tutorial/request-files.md::Import `File` { #import-file }::L19", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: Import `File` { #import-file }\n## Import `File` { #import-file }\n\nImport `File` and `UploadFile` from `fastapi`:\n\n{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "Import `File` { #import-file }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L19-L24", "start_line": 19, "end_line": 24} {"id": "docs/en/docs/tutorial/request-files.md::Define `File` Parameters { #define-file-parameters }::L25", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: Define `File` Parameters { #define-file-parameters }\n## Define `File` Parameters { #define-file-parameters }\n\nCreate file parameters the same way you would for `Body` or `Form`:\n\n{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}\n\n/// note\n\n`File` is a class that inherits directly from `Form`.\n\nBut remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.\n\n///\n\n/// tip\n\nTo declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.\n\n///\n\nThe files will be uploaded as \"form data\".\n\nIf you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`.\n\nKeep in mind that this means that the whole contents will be stored in memory. This will work well for small files.\n\nBut there are several cases in which you might benefit from using `UploadFile`.", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "Define `File` Parameters { #define-file-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L25-L52", "start_line": 25, "end_line": 52} {"id": "docs/en/docs/tutorial/request-files.md::File Parameters with `UploadFile` { #file-parameters-with-uploadfile }::L53", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: File Parameters with `UploadFile` { #file-parameters-with-uploadfile }\n## File Parameters with `UploadFile` { #file-parameters-with-uploadfile }\n\nDefine a file parameter with a type of `UploadFile`:\n\n{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}\n\nUsing `UploadFile` has several advantages over `bytes`:\n\n* You don't have to use `File()` in the default value of the parameter.\n* It uses a \"spooled\" file:\n * A file stored in memory up to a maximum size limit, and after passing this limit it will be stored on disk.\n* This means that it will work well for large files like images, videos, large binaries, etc. without consuming all the memory.\n* You can get metadata from the uploaded file.\n* It has a [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) `async` interface.\n* It exposes an actual Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) object that you can pass directly to other libraries that expect a file-like object.\n\n### `UploadFile` { #uploadfile }\n\n`UploadFile` has the following attributes:\n\n* `filename`: A `str` with the original file name that was uploaded (e.g. `myimage.jpg`).\n* `content_type`: A `str` with the content type (MIME type / media type) (e.g. `image/jpeg`).\n* `file`: A [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (a [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) object). This is the actual Python file object that you can pass directly to other functions or libraries that expect a \"file-like\" object.\n\n`UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`).\n\n* `write(data)`: Writes `data` (`str` or `bytes`) to the file.\n* `read(size)`: Reads `size` (`int`) bytes/characters of the file.\n* `seek(offset)`: Goes to the byte position `offset` (`int`) in the file.\n * E.g., `await myfile.seek(0)` would go to the start of the file.\n * This is especially useful if you run `await myfile.read()` once and then need to read the contents again.\n* `close()`: Closes the file.\n\nAs all these methods are `async` methods, you need to \"await\" them.\n\nFor example, inside of an `async` *path operation function* you can get the contents with:\n\n```Python\ncontents = await myfile.read()\n```\n\nIf you are inside of a normal `def` *path operation function*, you can access the `UploadFile.file` directly, for example:\n\n```Python\ncontents = myfile.file.read()\n```\n\n/// note | `async` Technical Details\n\nWhen you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.\n\n///\n\n/// note | Starlette Technical Details\n\n**FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "File Parameters with `UploadFile` { #file-parameters-with-uploadfile }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L53-L111", "start_line": 53, "end_line": 111} {"id": "docs/en/docs/tutorial/request-files.md::What is \"Form Data\" { #what-is-form-data }::L112", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: What is \"Form Data\" { #what-is-form-data }\n## What is \"Form Data\" { #what-is-form-data }\n\nThe way HTML forms (`
`) send the data to the server normally uses a \"special\" encoding for that data, it's different from JSON.\n\n**FastAPI** will make sure to read that data from the right place instead of JSON.\n\n/// note | Technical Details\n\nData from forms is normally encoded using the \"media type\" `application/x-www-form-urlencoded` when it doesn't include files.\n\nBut when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.\n\nIf you want to read more about these encodings and form fields, head to the [MDN web docs for `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).\n\n///\n\n/// warning\n\nYou can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.\n\nThis is not a limitation of **FastAPI**, it's part of the HTTP protocol.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "What is \"Form Data\" { #what-is-form-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L112-L135", "start_line": 112, "end_line": 135} {"id": "docs/en/docs/tutorial/request-files.md::Optional File Upload { #optional-file-upload }::L136", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: Optional File Upload { #optional-file-upload }\n## Optional File Upload { #optional-file-upload }\n\nYou can make a file optional by using standard type annotations and setting a default value of `None`:\n\n{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "Optional File Upload { #optional-file-upload }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L136-L141", "start_line": 136, "end_line": 141} {"id": "docs/en/docs/tutorial/request-files.md::`UploadFile` with Additional Metadata { #uploadfile-with-additional-metadata }::L142", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: `UploadFile` with Additional Metadata { #uploadfile-with-additional-metadata }\n## `UploadFile` with Additional Metadata { #uploadfile-with-additional-metadata }\n\nYou can also use `File()` with `UploadFile`, for example, to set additional metadata:\n\n{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "`UploadFile` with Additional Metadata { #uploadfile-with-additional-metadata }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L142-L147", "start_line": 142, "end_line": 147} {"id": "docs/en/docs/tutorial/request-files.md::Multiple File Uploads { #multiple-file-uploads }::L148", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: Multiple File Uploads { #multiple-file-uploads }\n## Multiple File Uploads { #multiple-file-uploads }\n\nIt's possible to upload several files at the same time.\n\nThey would be associated to the same \"form field\" sent using \"form data\".\n\nTo use that, declare a list of `bytes` or `UploadFile`:\n\n{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}\n\nYou will receive, as declared, a `list` of `bytes` or `UploadFile`s.\n\n/// note | Technical Details\n\nYou could also use `from starlette.responses import HTMLResponse`.\n\n**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.\n\n///\n\n### Multiple File Uploads with Additional Metadata { #multiple-file-uploads-with-additional-metadata }\n\nAnd the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`:\n\n{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "Multiple File Uploads { #multiple-file-uploads }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L148-L173", "start_line": 148, "end_line": 173} {"id": "docs/en/docs/tutorial/request-files.md::Recap { #recap }::L174", "text": "# Doc: docs/en/docs/tutorial/request-files.md | Page: Request Files { #request-files } | Section: Recap { #recap }\n## Recap { #recap }\n\nUse `File`, `bytes`, and `UploadFile` to declare files to be uploaded in the request, sent as form data.", "source_type": "doc", "path": "docs/en/docs/tutorial/request-files.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-files.md#L174-L176", "start_line": 174, "end_line": 176} {"id": "docs/en/docs/tutorial/request-form-models.md::Form Models { #form-models }::L1", "text": "# Doc: docs/en/docs/tutorial/request-form-models.md | Page: Form Models { #form-models } | Section: Form Models { #form-models }\n# Form Models { #form-models }\n\nYou can use **Pydantic models** to declare **form fields** in FastAPI.\n\n/// note\n\nTo use forms, first install [`python-multipart`](https://github.com/Kludex/python-multipart).\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:\n\n```console\n$ pip install python-multipart\n```\n\n///\n\n/// note\n\nThis is supported since FastAPI version `0.113.0`. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-form-models.md", "symbol": "Form Models { #form-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-form-models.md#L1-L22", "start_line": 1, "end_line": 22} {"id": "docs/en/docs/tutorial/request-form-models.md::Pydantic Models for Forms { #pydantic-models-for-forms }::L23", "text": "# Doc: docs/en/docs/tutorial/request-form-models.md | Page: Form Models { #form-models } | Section: Pydantic Models for Forms { #pydantic-models-for-forms }\n## Pydantic Models for Forms { #pydantic-models-for-forms }\n\nYou just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`:\n\n{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}\n\n**FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined.", "source_type": "doc", "path": "docs/en/docs/tutorial/request-form-models.md", "symbol": "Pydantic Models for Forms { #pydantic-models-for-forms }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-form-models.md#L23-L30", "start_line": 23, "end_line": 30} {"id": "docs/en/docs/tutorial/request-form-models.md::Check the Docs { #check-the-docs }::L31", "text": "# Doc: docs/en/docs/tutorial/request-form-models.md | Page: Form Models { #form-models } | Section: Check the Docs { #check-the-docs }\n## Check the Docs { #check-the-docs }\n\nYou can verify it in the docs UI at `/docs`:\n\n
\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/request-form-models.md", "symbol": "Check the Docs { #check-the-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-form-models.md#L31-L38", "start_line": 31, "end_line": 38} {"id": "docs/en/docs/tutorial/request-form-models.md::Forbid Extra Form Fields { #forbid-extra-form-fields }::L39", "text": "# Doc: docs/en/docs/tutorial/request-form-models.md | Page: Form Models { #form-models } | Section: Forbid Extra Form Fields { #forbid-extra-form-fields }\n## Forbid Extra Form Fields { #forbid-extra-form-fields }\n\nIn some special use cases (probably not very common), you might want to **restrict** the form fields to only those declared in the Pydantic model. And **forbid** any **extra** fields.\n\n/// note\n\nThis is supported since FastAPI version `0.114.0`. 🤓\n\n///\n\nYou can use Pydantic's model configuration to `forbid` any `extra` fields:\n\n{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *}\n\nIf a client tries to send some extra data, they will receive an **error** response.\n\nFor example, if the client tries to send the form fields:\n\n* `username`: `Rick`\n* `password`: `Portal Gun`\n* `extra`: `Mr. Poopybutthole`\n\nThey will receive an error response telling them that the field `extra` is not allowed:\n\n```json\n{\n \"detail\": [\n {\n \"type\": \"extra_forbidden\",\n \"loc\": [\"body\", \"extra\"],\n \"msg\": \"Extra inputs are not permitted\",\n \"input\": \"Mr. Poopybutthole\"\n }\n ]\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/request-form-models.md", "symbol": "Forbid Extra Form Fields { #forbid-extra-form-fields }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-form-models.md#L39-L75", "start_line": 39, "end_line": 75} {"id": "docs/en/docs/tutorial/request-form-models.md::Summary { #summary }::L76", "text": "# Doc: docs/en/docs/tutorial/request-form-models.md | Page: Form Models { #form-models } | Section: Summary { #summary }\n## Summary { #summary }\n\nYou can use Pydantic models to declare form fields in FastAPI. 😎", "source_type": "doc", "path": "docs/en/docs/tutorial/request-form-models.md", "symbol": "Summary { #summary }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-form-models.md#L76-L78", "start_line": 76, "end_line": 78} {"id": "docs/en/docs/tutorial/request-forms-and-files.md::Request Forms and Files { #request-forms-and-files }::L1", "text": "# Doc: docs/en/docs/tutorial/request-forms-and-files.md | Page: Request Forms and Files { #request-forms-and-files } | Section: Request Forms and Files { #request-forms-and-files }\n# Request Forms and Files { #request-forms-and-files }\n\nYou can define files and form fields at the same time using `File` and `Form`.\n\n/// note\n\nTo receive uploaded files and/or form data, first install [`python-multipart`](https://github.com/Kludex/python-multipart).\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:\n\n```console\n$ pip install python-multipart\n```\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms-and-files.md", "symbol": "Request Forms and Files { #request-forms-and-files }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms-and-files.md#L1-L16", "start_line": 1, "end_line": 16} {"id": "docs/en/docs/tutorial/request-forms-and-files.md::Import `File` and `Form` { #import-file-and-form }::L17", "text": "# Doc: docs/en/docs/tutorial/request-forms-and-files.md | Page: Request Forms and Files { #request-forms-and-files } | Section: Import `File` and `Form` { #import-file-and-form }\n## Import `File` and `Form` { #import-file-and-form }\n\n{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms-and-files.md", "symbol": "Import `File` and `Form` { #import-file-and-form }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms-and-files.md#L17-L20", "start_line": 17, "end_line": 20} {"id": "docs/en/docs/tutorial/request-forms-and-files.md::Define `File` and `Form` parameters { #define-file-and-form-parameters }::L21", "text": "# Doc: docs/en/docs/tutorial/request-forms-and-files.md | Page: Request Forms and Files { #request-forms-and-files } | Section: Define `File` and `Form` parameters { #define-file-and-form-parameters }\n## Define `File` and `Form` parameters { #define-file-and-form-parameters }\n\nCreate file and form parameters the same way you would for `Body` or `Query`:\n\n{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *}\n\nThe files and form fields will be uploaded as form data and you will receive the files and form fields.\n\nAnd you can declare some of the files as `bytes` and some as `UploadFile`.\n\n/// warning\n\nYou can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.\n\nThis is not a limitation of **FastAPI**, it's part of the HTTP protocol.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms-and-files.md", "symbol": "Define `File` and `Form` parameters { #define-file-and-form-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms-and-files.md#L21-L38", "start_line": 21, "end_line": 38} {"id": "docs/en/docs/tutorial/request-forms-and-files.md::Recap { #recap }::L39", "text": "# Doc: docs/en/docs/tutorial/request-forms-and-files.md | Page: Request Forms and Files { #request-forms-and-files } | Section: Recap { #recap }\n## Recap { #recap }\n\nUse `File` and `Form` together when you need to receive data and files in the same request.", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms-and-files.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms-and-files.md#L39-L41", "start_line": 39, "end_line": 41} {"id": "docs/en/docs/tutorial/request-forms.md::Form Data { #form-data }::L1", "text": "# Doc: docs/en/docs/tutorial/request-forms.md | Page: Form Data { #form-data } | Section: Form Data { #form-data }\n# Form Data { #form-data }\n\nWhen you need to receive form fields instead of JSON, you can use `Form`.\n\n/// note\n\nTo use forms, first install [`python-multipart`](https://github.com/Kludex/python-multipart).\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:\n\n```console\n$ pip install python-multipart\n```\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms.md", "symbol": "Form Data { #form-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms.md#L1-L16", "start_line": 1, "end_line": 16} {"id": "docs/en/docs/tutorial/request-forms.md::Import `Form` { #import-form }::L17", "text": "# Doc: docs/en/docs/tutorial/request-forms.md | Page: Form Data { #form-data } | Section: Import `Form` { #import-form }\n## Import `Form` { #import-form }\n\nImport `Form` from `fastapi`:\n\n{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms.md", "symbol": "Import `Form` { #import-form }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms.md#L17-L22", "start_line": 17, "end_line": 22} {"id": "docs/en/docs/tutorial/request-forms.md::Define `Form` parameters { #define-form-parameters }::L23", "text": "# Doc: docs/en/docs/tutorial/request-forms.md | Page: Form Data { #form-data } | Section: Define `Form` parameters { #define-form-parameters }\n## Define `Form` parameters { #define-form-parameters }\n\nCreate form parameters the same way you would for `Body` or `Query`:\n\n{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *}\n\nFor example, in one of the ways the OAuth2 specification can be used (called \"password flow\") it is required to send a `username` and `password` as form fields.\n\nThe spec requires the fields to be exactly named `username` and `password`, and to be sent as form fields, not JSON.\n\nWith `Form` you can declare the same configurations as with `Body` (and `Query`, `Path`, `Cookie`), including validation, examples, an alias (e.g. `user-name` instead of `username`), etc.\n\n/// note\n\n`Form` is a class that inherits directly from `Body`.\n\n///\n\n/// tip\n\nTo declare form bodies, you need to use `Form` explicitly, because without it the parameters would be interpreted as query parameters or body (JSON) parameters.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms.md", "symbol": "Define `Form` parameters { #define-form-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms.md#L23-L46", "start_line": 23, "end_line": 46} {"id": "docs/en/docs/tutorial/request-forms.md::About \"Form Fields\" { #about-form-fields }::L47", "text": "# Doc: docs/en/docs/tutorial/request-forms.md | Page: Form Data { #form-data } | Section: About \"Form Fields\" { #about-form-fields }\n## About \"Form Fields\" { #about-form-fields }\n\nThe way HTML forms (`
`) send the data to the server normally uses a \"special\" encoding for that data, it's different from JSON.\n\n**FastAPI** will make sure to read that data from the right place instead of JSON.\n\n/// note | Technical Details\n\nData from forms is normally encoded using the \"media type\" `application/x-www-form-urlencoded`.\n\nBut when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.\n\nIf you want to read more about these encodings and form fields, head to the [MDN web docs for `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).\n\n///\n\n/// warning\n\nYou can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.\n\nThis is not a limitation of **FastAPI**, it's part of the HTTP protocol.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms.md", "symbol": "About \"Form Fields\" { #about-form-fields }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms.md#L47-L70", "start_line": 47, "end_line": 70} {"id": "docs/en/docs/tutorial/request-forms.md::Recap { #recap }::L71", "text": "# Doc: docs/en/docs/tutorial/request-forms.md | Page: Form Data { #form-data } | Section: Recap { #recap }\n## Recap { #recap }\n\nUse `Form` to declare form data input parameters.", "source_type": "doc", "path": "docs/en/docs/tutorial/request-forms.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/request-forms.md#L71-L73", "start_line": 71, "end_line": 73} {"id": "docs/en/docs/tutorial/response-model.md::Response Model - Return Type { #response-model-return-type }::L1", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: Response Model - Return Type { #response-model-return-type }\n# Response Model - Return Type { #response-model-return-type }\n\nYou can declare the type used for the response by annotating the *path operation function* **return type**.\n\nYou can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.\n\n{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}\n\nFastAPI will use this return type to:\n\n* **Validate** the returned data.\n * If the data is invalid (e.g. you are missing a field), it means that *your* app code is broken, not returning what it should, and it will return a server error instead of returning incorrect data. This way you and your clients can be certain that they will receive the data and the data shape expected.\n* Add a **JSON Schema** for the response, in the OpenAPI *path operation*.\n * This will be used by the **automatic docs**.\n * It will also be used by automatic client code generation tools.\n* **Serialize** the returned data to JSON using Pydantic, which is written in **Rust**, so it will be **much faster**.\n\nBut most importantly:\n\n* It will **limit and filter** the output data to what is defined in the return type.\n * This is particularly important for **security**, we'll see more of that below.", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "Response Model - Return Type { #response-model-return-type }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L1-L22", "start_line": 1, "end_line": 22} {"id": "docs/en/docs/tutorial/response-model.md::`response_model` Parameter { #response-model-parameter }::L23", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: `response_model` Parameter { #response-model-parameter }\n## `response_model` Parameter { #response-model-parameter }\n\nThere are some cases where you need or want to return some data that is not exactly what the type declares.\n\nFor example, you could want to **return a dictionary** or a database object, but **declare it as a Pydantic model**. This way the Pydantic model would do all the data documentation, validation, etc. for the object that you returned (e.g. a dictionary or database object).\n\nIf you added the return type annotation, tools and editors would complain with a (correct) error telling you that your function is returning a type (e.g. a dict) that is different from what you declared (e.g. a Pydantic model).\n\nIn those cases, you can use the *path operation decorator* parameter `response_model` instead of the return type.\n\nYou can use the `response_model` parameter in any of the *path operations*:\n\n* `@app.get()`\n* `@app.post()`\n* `@app.put()`\n* `@app.delete()`\n* etc.\n\n{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}\n\n/// note\n\nNotice that `response_model` is a parameter of the \"decorator\" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.\n\n///\n\n`response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`.\n\nFastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration.\n\n/// tip\n\nIf you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.\n\nThat way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.\n\n///\n\n### `response_model` Priority { #response-model-priority }\n\nIf you declare both a return type and a `response_model`, the `response_model` will take priority and be used by FastAPI.\n\nThis way you can add correct type annotations to your functions even when you are returning a type different than the response model, to be used by the editor and tools like mypy. And still you can have FastAPI do the data validation, documentation, etc. using the `response_model`.\n\nYou can also use `response_model=None` to disable creating a response model for that *path operation*, you might need to do it if you are adding type annotations for things that are not valid Pydantic fields, you will see an example of that in one of the sections below.", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "`response_model` Parameter { #response-model-parameter }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L23-L68", "start_line": 23, "end_line": 68} {"id": "docs/en/docs/tutorial/response-model.md::Return the same input data { #return-the-same-input-data }::L69", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: Return the same input data { #return-the-same-input-data }\n## Return the same input data { #return-the-same-input-data }\n\nHere we are declaring a `UserIn` model, it will contain a plaintext password:\n\n{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}\n\n/// note\n\nTo use `EmailStr`, first install [`email-validator`](https://github.com/JoshData/python-email-validator).\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:\n\n```console\n$ pip install email-validator\n```\n\nor with:\n\n```console\n$ pip install \"pydantic[email]\"\n```\n\n///\n\nAnd we are using this model to declare our input and the same model to declare our output:\n\n{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}\n\nNow, whenever a browser is creating a user with a password, the API will return the same password in the response.\n\nIn this case, it might not be a problem, because it's the same user sending the password.\n\nBut if we use the same model for another *path operation*, we could be sending our user's passwords to every client.\n\n/// danger\n\nNever store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "Return the same input data { #return-the-same-input-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L69-L108", "start_line": 69, "end_line": 108} {"id": "docs/en/docs/tutorial/response-model.md::Add an output model { #add-an-output-model }::L109", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: Add an output model { #add-an-output-model }\n## Add an output model { #add-an-output-model }\n\nWe can instead create an input model with the plaintext password and an output model without it:\n\n{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}\n\nHere, even though our *path operation function* is returning the same input user that contains the password:\n\n{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}\n\n...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:\n\n{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}\n\nSo, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).\n\n### `response_model` or Return Type { #response-model-or-return-type }\n\nIn this case, because the two models are different, if we annotated the function return type as `UserOut`, the editor and tools would complain that we are returning an invalid type, as those are different classes.\n\nThat's why in this example we have to declare it in the `response_model` parameter.\n\n...but continue reading below to see how to overcome that.", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "Add an output model { #add-an-output-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L109-L132", "start_line": 109, "end_line": 132} {"id": "docs/en/docs/tutorial/response-model.md::Return Type and Data Filtering { #return-type-and-data-filtering }::L133", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: Return Type and Data Filtering { #return-type-and-data-filtering }\n## Return Type and Data Filtering { #return-type-and-data-filtering }\n\nLet's continue from the previous example. We wanted to **annotate the function with one type**, but we wanted to be able to return from the function something that actually includes **more data**.\n\nWe want FastAPI to keep **filtering** the data using the response model. So that even though the function returns more data, the response will only include the fields declared in the response model.\n\nIn the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type.\n\nBut in most of the cases where we need to do something like this, we want the model just to **filter/remove** some of the data as in this example.\n\nAnd in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**.\n\n{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}\n\nWith this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.\n\nHow does this work? Let's check that out. 🤓\n\n### Type Annotations and Tooling { #type-annotations-and-tooling }\n\nFirst let's see how editors, mypy and other tools would see this.\n\n`BaseUser` has the base fields. Then `UserIn` inherits from `BaseUser` and adds the `password` field, so, it will include all the fields from both models.\n\nWe annotate the function return type as `BaseUser`, but we are actually returning a `UserIn` instance.\n\nThe editor, mypy, and other tools won't complain about this because, in typing terms, `UserIn` is a subclass of `BaseUser`, which means it's a *valid* type when what is expected is anything that is a `BaseUser`.\n\n### FastAPI Data Filtering { #fastapi-data-filtering }\n\nNow, for FastAPI, it will see the return type and make sure that what you return includes **only** the fields that are declared in the type.\n\nFastAPI does several things internally with Pydantic to make sure that those same rules of class inheritance are not used for the returned data filtering, otherwise you could end up returning much more data than what you expected.\n\nThis way, you can get the best of both worlds: type annotations with **tooling support** and **data filtering**.", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "Return Type and Data Filtering { #return-type-and-data-filtering }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L133-L168", "start_line": 133, "end_line": 168} {"id": "docs/en/docs/tutorial/response-model.md::See it in the docs { #see-it-in-the-docs }::L169", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: See it in the docs { #see-it-in-the-docs }\n## See it in the docs { #see-it-in-the-docs }\n\nWhen you see the automatic docs, you can check that the input model and output model will both have their own JSON Schema:\n\n\n\nAnd both models will be used for the interactive API documentation:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "See it in the docs { #see-it-in-the-docs }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L169-L178", "start_line": 169, "end_line": 178} {"id": "docs/en/docs/tutorial/response-model.md::Other Return Type Annotations { #other-return-type-annotations }::L179", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: Other Return Type Annotations { #other-return-type-annotations }\n## Other Return Type Annotations { #other-return-type-annotations }\n\nThere might be cases where you return something that is not a valid Pydantic field and you annotate it in the function, only to get the support provided by tooling (the editor, mypy, etc).\n\n### Return a Response Directly { #return-a-response-directly }\n\nThe most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md).\n\n{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}\n\nThis simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`.\n\nAnd tools will also be happy because both `RedirectResponse` and `JSONResponse` are subclasses of `Response`, so the type annotation is correct.\n\n### Annotate a Response Subclass { #annotate-a-response-subclass }\n\nYou can also use a subclass of `Response` in the type annotation:\n\n{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}\n\nThis will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case.\n\n### Invalid Return Type Annotations { #invalid-return-type-annotations }\n\nBut when you return some other arbitrary object that is not a valid Pydantic type (e.g. a database object) and you annotate it like that in the function, FastAPI will try to create a Pydantic response model from that type annotation, and will fail.\n\nThe same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:\n\n{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}\n\n...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.\n\n### Disable Response Model { #disable-response-model }\n\nContinuing from the example above, you might not want to have the default data validation, documentation, filtering, etc. that is performed by FastAPI.\n\nBut you might want to still keep the return type annotation in the function to get the support from tools like editors and type checkers (e.g. mypy).\n\nIn this case, you can disable the response model generation by setting `response_model=None`:\n\n{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}\n\nThis will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "Other Return Type Annotations { #other-return-type-annotations }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L179-L222", "start_line": 179, "end_line": 222} {"id": "docs/en/docs/tutorial/response-model.md::Response Model encoding parameters { #response-model-encoding-parameters }::L223", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: Response Model encoding parameters { #response-model-encoding-parameters }\n## Response Model encoding parameters { #response-model-encoding-parameters }\n\nYour response model could have default values, like:\n\n{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}\n\n* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.\n* `tax: float = 10.5` has a default of `10.5`.\n* `tags: List[str] = []` has a default of an empty list: `[]`.\n\nbut you might want to omit them from the result if they were not actually stored.\n\nFor example, if you have models with many optional attributes in a NoSQL database, but you don't want to send very long JSON responses full of default values.\n\n### Use the `response_model_exclude_unset` parameter { #use-the-response-model-exclude-unset-parameter }\n\nYou can set the *path operation decorator* parameter `response_model_exclude_unset=True`:\n\n{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}\n\nand those default values won't be included in the response, only the values actually set.\n\nSo, if you send a request to that *path operation* for the item with ID `foo`, the response (not including default values) will be:\n\n```JSON\n{\n \"name\": \"Foo\",\n \"price\": 50.2\n}\n```\n\n/// note\n\nYou can also use:\n\n* `response_model_exclude_defaults=True`\n* `response_model_exclude_none=True`\n\nas described in [the Pydantic docs](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) for `exclude_defaults` and `exclude_none`.\n\n///\n\n#### Data with values for fields with defaults { #data-with-values-for-fields-with-defaults }\n\nBut if your data has values for the model's fields with default values, like the item with ID `bar`:\n\n```Python hl_lines=\"3 5\"\n{\n \"name\": \"Bar\",\n \"description\": \"The bartenders\",\n \"price\": 62,\n \"tax\": 20.2\n}\n```\n\nthey will be included in the response.\n\n#### Data with the same values as the defaults { #data-with-the-same-values-as-the-defaults }\n\nIf the data has the same values as the default ones, like the item with ID `baz`:\n\n```Python hl_lines=\"3 5-6\"\n{\n \"name\": \"Baz\",\n \"description\": None,\n \"price\": 50.2,\n \"tax\": 10.5,\n \"tags\": []\n}\n```\n\nFastAPI is smart enough (actually, Pydantic is smart enough) to realize that, even though `description`, `tax`, and `tags` have the same values as the defaults, they were set explicitly (instead of taken from the defaults).\n\nSo, they will be included in the JSON response.\n\n/// tip\n\nNotice that the default values can be anything, not only `None`.\n\nThey can be a list (`[]`), a `float` of `10.5`, etc.\n\n///\n\n### `response_model_include` and `response_model_exclude` { #response-model-include-and-response-model-exclude }\n\nYou can also use the *path operation decorator* parameters `response_model_include` and `response_model_exclude`.\n\nThey take a `set` of `str` with the name of the attributes to include (omitting the rest) or to exclude (including the rest).\n\nThis can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the output.\n\n/// tip\n\nBut it is still recommended to use the ideas above, using multiple classes, instead of these parameters.\n\nThis is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.\n\nThis also applies to `response_model_by_alias` that works similarly.\n\n///\n\n{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}\n\n/// tip\n\nThe syntax `{\"name\", \"description\"}` creates a `set` with those two values.\n\nIt is equivalent to `set([\"name\", \"description\"])`.\n\n///\n\n#### Using `list`s instead of `set`s { #using-lists-instead-of-sets }\n\nIf you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:\n\n{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "Response Model encoding parameters { #response-model-encoding-parameters }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L223-L339", "start_line": 223, "end_line": 339} {"id": "docs/en/docs/tutorial/response-model.md::Recap { #recap }::L340", "text": "# Doc: docs/en/docs/tutorial/response-model.md | Page: Response Model - Return Type { #response-model-return-type } | Section: Recap { #recap }\n## Recap { #recap }\n\nUse the *path operation decorator's* parameter `response_model` to define response models and especially to ensure private data is filtered out.\n\nUse `response_model_exclude_unset` to return only the values explicitly set.", "source_type": "doc", "path": "docs/en/docs/tutorial/response-model.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-model.md#L340-L344", "start_line": 340, "end_line": 344} {"id": "docs/en/docs/tutorial/response-status-code.md::Response Status Code { #response-status-code }::L1", "text": "# Doc: docs/en/docs/tutorial/response-status-code.md | Page: Response Status Code { #response-status-code } | Section: Response Status Code { #response-status-code }\n# Response Status Code { #response-status-code }\n\nThe same way you can specify a response model, you can also declare the HTTP status code used for the response with the parameter `status_code` in any of the *path operations*:\n\n* `@app.get()`\n* `@app.post()`\n* `@app.put()`\n* `@app.delete()`\n* etc.\n\n{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}\n\n/// note\n\nNotice that `status_code` is a parameter of the \"decorator\" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.\n\n///\n\nThe `status_code` parameter receives a number with the HTTP status code.\n\n/// note\n\n`status_code` can alternatively also receive an `IntEnum`, such as Python's [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus).\n\n///\n\nIt will:\n\n* Return that status code in the response.\n* Document it as such in the OpenAPI schema (and so, in the user interfaces):\n\n\n\n/// note\n\nSome response codes (see the next section) indicate that the response does not have a body.\n\nFastAPI knows this, and will produce OpenAPI docs that state there is no response body.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/response-status-code.md", "symbol": "Response Status Code { #response-status-code }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-status-code.md#L1-L41", "start_line": 1, "end_line": 41} {"id": "docs/en/docs/tutorial/response-status-code.md::About HTTP status codes { #about-http-status-codes }::L42", "text": "# Doc: docs/en/docs/tutorial/response-status-code.md | Page: Response Status Code { #response-status-code } | Section: About HTTP status codes { #about-http-status-codes }\n## About HTTP status codes { #about-http-status-codes }\n\n/// note\n\nIf you already know what HTTP status codes are, skip to the next section.\n\n///\n\nIn HTTP, you send a numeric status code of 3 digits as part of the response.\n\nThese status codes have an associated name to help recognize them, but the important part is the number.\n\nIn short:\n\n* `100 - 199` are for \"Information\". You rarely use them directly. Responses with these status codes cannot have a body.\n* **`200 - 299`** are for \"Successful\" responses. These are the ones you would use the most.\n * `200` is the default status code, which means everything was \"OK\".\n * Another example would be `201`, \"Created\". It is commonly used after creating a new record in the database.\n * A special case is `204`, \"No Content\". This response is used when there is no content to return to the client, and so the response must not have a body.\n* **`300 - 399`** are for \"Redirection\". Responses with these status codes may or may not have a body, except for `304`, \"Not Modified\", which must not have one.\n* **`400 - 499`** are for \"Client error\" responses. These are the second type you would probably use the most.\n * An example is `404`, for a \"Not Found\" response.\n * For generic errors from the client, you can just use `400`.\n* `500 - 599` are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes.\n\n/// tip\n\nTo know more about each status code and which code is for what, check the [MDN documentation about HTTP status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/response-status-code.md", "symbol": "About HTTP status codes { #about-http-status-codes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-status-code.md#L42-L72", "start_line": 42, "end_line": 72} {"id": "docs/en/docs/tutorial/response-status-code.md::Shortcut to remember the names { #shortcut-to-remember-the-names }::L73", "text": "# Doc: docs/en/docs/tutorial/response-status-code.md | Page: Response Status Code { #response-status-code } | Section: Shortcut to remember the names { #shortcut-to-remember-the-names }\n## Shortcut to remember the names { #shortcut-to-remember-the-names }\n\nLet's see the previous example again:\n\n{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}\n\n`201` is the status code for \"Created\".\n\nBut you don't have to memorize what each of these codes mean.\n\nYou can use the convenience variables from `fastapi.status`.\n\n{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}\n\nThey are just a convenience, they hold the same number, but that way you can use the editor's autocomplete to find them:\n\n\n\n/// note | Technical Details\n\nYou could also use `from starlette import status`.\n\n**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/response-status-code.md", "symbol": "Shortcut to remember the names { #shortcut-to-remember-the-names }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-status-code.md#L73-L98", "start_line": 73, "end_line": 98} {"id": "docs/en/docs/tutorial/response-status-code.md::Changing the default { #changing-the-default }::L99", "text": "# Doc: docs/en/docs/tutorial/response-status-code.md | Page: Response Status Code { #response-status-code } | Section: Changing the default { #changing-the-default }\n## Changing the default { #changing-the-default }\n\nLater, in the [Advanced User Guide](../advanced/response-change-status-code.md), you will see how to return a different status code than the default you are declaring here.", "source_type": "doc", "path": "docs/en/docs/tutorial/response-status-code.md", "symbol": "Changing the default { #changing-the-default }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/response-status-code.md#L99-L101", "start_line": 99, "end_line": 101} {"id": "docs/en/docs/tutorial/schema-extra-example.md::Declare Request Example Data { #declare-request-example-data }::L1", "text": "# Doc: docs/en/docs/tutorial/schema-extra-example.md | Page: Declare Request Example Data { #declare-request-example-data } | Section: Declare Request Example Data { #declare-request-example-data }\n# Declare Request Example Data { #declare-request-example-data }\n\nYou can declare examples of the data your app can receive.\n\nHere are several ways to do it.", "source_type": "doc", "path": "docs/en/docs/tutorial/schema-extra-example.md", "symbol": "Declare Request Example Data { #declare-request-example-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/schema-extra-example.md#L1-L6", "start_line": 1, "end_line": 6} {"id": "docs/en/docs/tutorial/schema-extra-example.md::Extra JSON Schema data in Pydantic models { #extra-json-schema-data-in-pydantic-models }::L7", "text": "# Doc: docs/en/docs/tutorial/schema-extra-example.md | Page: Declare Request Example Data { #declare-request-example-data } | Section: Extra JSON Schema data in Pydantic models { #extra-json-schema-data-in-pydantic-models }\n## Extra JSON Schema data in Pydantic models { #extra-json-schema-data-in-pydantic-models }\n\nYou can declare `examples` for a Pydantic model that will be added to the generated JSON Schema.\n\n{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}\n\nThat extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs.\n\nYou can use the attribute `model_config` that takes a `dict` as described in [Pydantic's docs: Configuration](https://docs.pydantic.dev/latest/api/config/).\n\nYou can set `\"json_schema_extra\"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.\n\n/// tip\n\nYou could use the same technique to extend the JSON Schema and add your own custom extra info.\n\nFor example you could use it to add metadata for a frontend user interface, etc.\n\n///\n\n/// note\n\nOpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.\n\nBefore that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓\n\nYou can read more at the end of this page.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/schema-extra-example.md", "symbol": "Extra JSON Schema data in Pydantic models { #extra-json-schema-data-in-pydantic-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/schema-extra-example.md#L7-L36", "start_line": 7, "end_line": 36} {"id": "docs/en/docs/tutorial/schema-extra-example.md::`Field` additional arguments { #field-additional-arguments }::L37", "text": "# Doc: docs/en/docs/tutorial/schema-extra-example.md | Page: Declare Request Example Data { #declare-request-example-data } | Section: `Field` additional arguments { #field-additional-arguments }\n## `Field` additional arguments { #field-additional-arguments }\n\nWhen using `Field()` with Pydantic models, you can also declare additional `examples`:\n\n{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/schema-extra-example.md", "symbol": "`Field` additional arguments { #field-additional-arguments }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/schema-extra-example.md#L37-L42", "start_line": 37, "end_line": 42} {"id": "docs/en/docs/tutorial/schema-extra-example.md::`examples` in JSON Schema - OpenAPI { #examples-in-json-schema-openapi }::L43", "text": "# Doc: docs/en/docs/tutorial/schema-extra-example.md | Page: Declare Request Example Data { #declare-request-example-data } | Section: `examples` in JSON Schema - OpenAPI { #examples-in-json-schema-openapi }\n## `examples` in JSON Schema - OpenAPI { #examples-in-json-schema-openapi }\n\nWhen using any of:\n\n* `Path()`\n* `Query()`\n* `Header()`\n* `Cookie()`\n* `Body()`\n* `Form()`\n* `File()`\n\nyou can also declare a group of `examples` with additional information that will be added to their **JSON Schemas** inside of **OpenAPI**.\n\n### `Body` with `examples` { #body-with-examples }\n\nHere we pass `examples` containing one example of the data expected in `Body()`:\n\n{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}\n\n### Example in the docs UI { #example-in-the-docs-ui }\n\nWith any of the methods above it would look like this in the `/docs`:\n\n\n\n### `Body` with multiple `examples` { #body-with-multiple-examples }\n\nYou can of course also pass multiple `examples`:\n\n{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}\n\nWhen you do this, the examples will be part of the internal **JSON Schema** for that body data.\n\nNevertheless, at the time of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data in **JSON Schema**. But read below for a workaround.\n\n### OpenAPI-specific `examples` { #openapi-specific-examples }\n\nSince before **JSON Schema** supported `examples`, OpenAPI had support for a different field also called `examples`.\n\nThis **OpenAPI-specific** `examples` goes in another section in the OpenAPI specification. It goes in the **details for each *path operation***, not inside each JSON Schema.\n\nAnd Swagger UI has supported this particular `examples` field for a while. So, you can use it to **show** different **examples in the docs UI**.\n\nThe shape of this OpenAPI-specific field `examples` is a `dict` with **multiple examples** (instead of a `list`), each with extra information that will be added to **OpenAPI** too.\n\nThis doesn't go inside of each JSON Schema contained in OpenAPI, this goes outside, in the *path operation* directly.\n\n### Using the `openapi_examples` Parameter { #using-the-openapi-examples-parameter }\n\nYou can declare the OpenAPI-specific `examples` in FastAPI with the parameter `openapi_examples` for:\n\n* `Path()`\n* `Query()`\n* `Header()`\n* `Cookie()`\n* `Body()`\n* `Form()`\n* `File()`\n\nThe keys of the `dict` identify each example, and each value is another `dict`.\n\nEach specific example `dict` in the `examples` can contain:\n\n* `summary`: Short description for the example.\n* `description`: A long description that can contain Markdown text.\n* `value`: This is the actual example shown, e.g. a `dict`.\n* `externalValue`: alternative to `value`, a URL pointing to the example. Although this might not be supported by as many tools as `value`.\n\nYou can use it like this:\n\n{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}\n\n### OpenAPI Examples in the Docs UI { #openapi-examples-in-the-docs-ui }\n\nWith `openapi_examples` added to `Body()` the `/docs` would look like:\n\n", "source_type": "doc", "path": "docs/en/docs/tutorial/schema-extra-example.md", "symbol": "`examples` in JSON Schema - OpenAPI { #examples-in-json-schema-openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/schema-extra-example.md#L43-L121", "start_line": 43, "end_line": 121} {"id": "docs/en/docs/tutorial/schema-extra-example.md::Technical Details { #technical-details }::L122", "text": "# Doc: docs/en/docs/tutorial/schema-extra-example.md | Page: Declare Request Example Data { #declare-request-example-data } | Section: Technical Details { #technical-details }\n## Technical Details { #technical-details }\n\n/// tip\n\nIf you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.\n\nThey are more relevant for older versions, before OpenAPI 3.1.0 was available.\n\nYou can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓\n\n///\n\n/// warning\n\nThese are very technical details about the standards **JSON Schema** and **OpenAPI**.\n\nIf the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.\n\n///\n\nBefore OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**.\n\nJSON Schema didn't have `examples`, so OpenAPI added its own `example` field to its own modified version.\n\nOpenAPI also added `example` and `examples` fields to other parts of the specification:\n\n* [`Parameter Object` (in the specification)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object) that was used by FastAPI's:\n * `Path()`\n * `Query()`\n * `Header()`\n * `Cookie()`\n* [`Request Body Object`, in the field `content`, on the `Media Type Object` (in the specification)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object) that was used by FastAPI's:\n * `Body()`\n * `File()`\n * `Form()`\n\n/// note\n\nThis old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.\n\n///\n\n### JSON Schema's `examples` field { #json-schemas-examples-field }\n\nBut then JSON Schema added an [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) field to a new version of the specification.\n\nAnd then the new OpenAPI 3.1.0 was based on the latest version (JSON Schema 2020-12) that included this new field `examples`.\n\nAnd now this new `examples` field takes precedence over the old single (and custom) `example` field, that is now deprecated.\n\nThis new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above).\n\n/// note\n\nEven after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).\n\nBecause of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.\n\n///\n\n### Pydantic and FastAPI `examples` { #pydantic-and-fastapi-examples }\n\nWhen you add `examples` inside a Pydantic model, using `schema_extra` or `Field(examples=[\"something\"])` that example is added to the **JSON Schema** for that Pydantic model.\n\nAnd that **JSON Schema** of the Pydantic model is included in the **OpenAPI** of your API, and then it's used in the docs UI.\n\nIn versions of FastAPI before 0.99.0 (0.99.0 and above use the newer OpenAPI 3.1.0) when you used `example` or `examples` with any of the other utilities (`Query()`, `Body()`, etc.) those examples were not added to the JSON Schema that describes that data (not even to OpenAPI's own version of JSON Schema), they were added directly to the *path operation* declaration in OpenAPI (outside the parts of OpenAPI that use JSON Schema).\n\nBut now that FastAPI 0.99.0 and above uses OpenAPI 3.1.0, that uses JSON Schema 2020-12, and Swagger UI 5.0.0 and above, everything is more consistent and the examples are included in JSON Schema.\n\n### Swagger UI and OpenAPI-specific `examples` { #swagger-ui-and-openapi-specific-examples }\n\nNow, as Swagger UI didn't support multiple JSON Schema examples (as of 2023-08-26), users didn't have a way to show multiple examples in the docs.\n\nTo solve that, FastAPI `0.103.0` **added support** for declaring the same old **OpenAPI-specific** `examples` field with the new parameter `openapi_examples`. 🤓\n\n### Summary { #summary }\n\nI used to say I didn't like history that much... and look at me now giving \"tech history\" lessons. 😅\n\nIn short, **upgrade to FastAPI 0.99.0 or above**, and things are much **simpler, consistent, and intuitive**, and you don't have to know all these historic details. 😎", "source_type": "doc", "path": "docs/en/docs/tutorial/schema-extra-example.md", "symbol": "Technical Details { #technical-details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/schema-extra-example.md#L122-L202", "start_line": 122, "end_line": 202} {"id": "docs/en/docs/tutorial/security/first-steps.md::Security - First Steps { #security-first-steps }::L1", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: Security - First Steps { #security-first-steps }\n# Security - First Steps { #security-first-steps }\n\nLet's imagine that you have your **backend** API in some domain.\n\nAnd you have a **frontend** in another domain or in a different path of the same domain (or in a mobile application).\n\nAnd you want to have a way for the frontend to authenticate with the backend, using a **username** and **password**.\n\nWe can use **OAuth2** to build that with **FastAPI**.\n\nBut let's save you the time of reading the full long specification just to find those little pieces of information you need.\n\nLet's use the tools provided by **FastAPI** to handle security.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "Security - First Steps { #security-first-steps }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L1-L14", "start_line": 1, "end_line": 14} {"id": "docs/en/docs/tutorial/security/first-steps.md::How it looks { #how-it-looks }::L15", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: How it looks { #how-it-looks }\n## How it looks { #how-it-looks }\n\nLet's first just use the code and see how it works, and then we'll come back to understand what's happening.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "How it looks { #how-it-looks }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L15-L18", "start_line": 15, "end_line": 18} {"id": "docs/en/docs/tutorial/security/first-steps.md::Create `main.py` { #create-main-py }::L19", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: Create `main.py` { #create-main-py }\n## Create `main.py` { #create-main-py }\n\nCopy the example in a file `main.py`:\n\n{* ../../docs_src/security/tutorial001_an_py310.py *}", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "Create `main.py` { #create-main-py }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L19-L24", "start_line": 19, "end_line": 24} {"id": "docs/en/docs/tutorial/security/first-steps.md::Run it { #run-it }::L25", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: Run it { #run-it }\n## Run it { #run-it }\n\n/// note\n\nThe [`python-multipart`](https://github.com/Kludex/python-multipart) package is automatically installed with **FastAPI** when you run the `pip install \"fastapi[standard]\"` command.\n\nHowever, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default.\n\nTo install it manually, make sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install it with:\n\n```console\n$ pip install python-multipart\n```\n\nThis is because **OAuth2** uses \"form data\" for sending the `username` and `password`.\n\n///\n\nRun the example with:\n\n
\n\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "Run it { #run-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L25-L54", "start_line": 25, "end_line": 54} {"id": "docs/en/docs/tutorial/security/first-steps.md::Check it { #check-it }::L55", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: Check it { #check-it }\n## Check it { #check-it }\n\nGo to the interactive docs at: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou will see something like this:\n\n\n\n/// tip | Authorize button!\n\nYou already have a shiny new \"Authorize\" button.\n\nAnd your *path operation* has a little lock in the top-right corner that you can click.\n\n///\n\nAnd if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields):\n\n\n\n/// note\n\nIt doesn't matter what you type in the form, it won't work yet. But we'll get there.\n\n///\n\nThis is of course not the frontend for the final users, but it's a great automatic tool to document interactively all your API.\n\nIt can be used by the frontend team (that can also be yourself).\n\nIt can be used by third party applications and systems.\n\nAnd it can also be used by yourself, to debug, check and test the same application.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "Check it { #check-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L55-L88", "start_line": 55, "end_line": 88} {"id": "docs/en/docs/tutorial/security/first-steps.md::The `password` flow { #the-password-flow }::L89", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: The `password` flow { #the-password-flow }\n## The `password` flow { #the-password-flow }\n\nNow let's go back a bit and understand what all that is.\n\nThe `password` \"flow\" is one of the ways (\"flows\") defined in OAuth2, to handle security and authentication.\n\nOAuth2 was designed so that the backend or API could be independent of the server that authenticates the user.\n\nBut in this case, the same **FastAPI** application will handle the API and the authentication.\n\nSo, let's review it from that simplified point of view:\n\n* The user types the `username` and `password` in the frontend, and hits `Enter`.\n* The frontend (running in the user's browser) sends that `username` and `password` to a specific URL in our API (declared with `tokenUrl=\"token\"`).\n* The API checks that `username` and `password`, and responds with a \"token\" (we haven't implemented any of this yet).\n * A \"token\" is just a string with some content that we can use later to verify this user.\n * Normally, a token is set to expire after some time.\n * So, the user will have to log in again at some point later.\n * And if the token is stolen, the risk is less. It is not like a permanent key that will work forever (in most of the cases).\n* The frontend stores that token temporarily somewhere.\n* The user clicks in the frontend to go to another section of the frontend web app.\n* The frontend needs to fetch some more data from the API.\n * But it needs authentication for that specific endpoint.\n * So, to authenticate with our API, it sends a header `Authorization` with a value of `Bearer ` plus the token.\n * If the token contains `foobar`, the content of the `Authorization` header would be: `Bearer foobar`.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "The `password` flow { #the-password-flow }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L89-L114", "start_line": 89, "end_line": 114} {"id": "docs/en/docs/tutorial/security/first-steps.md::**FastAPI**'s `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }::L115", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: **FastAPI**'s `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }\n## **FastAPI**'s `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }\n\n**FastAPI** provides several tools, at different levels of abstraction, to implement these security features.\n\nIn this example we are going to use **OAuth2**, with the **Password** flow, using a **Bearer** token. We do that using the `OAuth2PasswordBearer` class.\n\n/// note\n\nA \"bearer\" token is not the only option.\n\nBut it's the best one for our use case.\n\nAnd it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that better suits your needs.\n\nIn that case, **FastAPI** also provides you with the tools to build it.\n\n///\n\nWhen we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token.\n\n{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}\n\n/// tip\n\nHere `tokenUrl=\"token\"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.\n\nBecause we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.\n\nUsing a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md).\n\n///\n\nThis parameter doesn't create that endpoint / *path operation*, but declares that the URL `/token` will be the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems.\n\nWe will soon also create the actual path operation.\n\n/// note\n\nIf you are a very strict \"Pythonista\" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.\n\nThat's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it.\n\n///\n\nThe `oauth2_scheme` variable is an instance of `OAuth2PasswordBearer`, but it is also a \"callable\".\n\nIt could be called as:\n\n```Python\noauth2_scheme(some, parameters)\n```\n\nSo, it can be used with `Depends`.\n\n### Use it { #use-it }\n\nNow you can pass that `oauth2_scheme` in a dependency with `Depends`.\n\n{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}\n\nThis dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*.\n\n**FastAPI** will know that it can use this dependency to define a \"security scheme\" in the OpenAPI schema (and the automatic API docs).\n\n/// note | Technical Details\n\n**FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.\n\nAll the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "**FastAPI**'s `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L115-L186", "start_line": 115, "end_line": 186} {"id": "docs/en/docs/tutorial/security/first-steps.md::What it does { #what-it-does }::L187", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: What it does { #what-it-does }\n## What it does { #what-it-does }\n\nIt will go and look in the request for that `Authorization` header, check if the value is `Bearer ` plus some token, and will return the token as a `str`.\n\nIf it doesn't see an `Authorization` header, or the value doesn't have a `Bearer ` token, it will respond with a 401 status code error (`UNAUTHORIZED`) directly.\n\nYou don't even have to check if the token exists to return an error. You can be sure that if your function is executed, it will have a `str` in that token.\n\nYou can try it already in the interactive docs:\n\n\n\nWe are not verifying the validity of the token yet, but that's a start already.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "What it does { #what-it-does }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L187-L200", "start_line": 187, "end_line": 200} {"id": "docs/en/docs/tutorial/security/first-steps.md::Recap { #recap }::L201", "text": "# Doc: docs/en/docs/tutorial/security/first-steps.md | Page: Security - First Steps { #security-first-steps } | Section: Recap { #recap }\n## Recap { #recap }\n\nSo, in just 3 or 4 extra lines, you already have some primitive form of security.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/first-steps.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/first-steps.md#L201-L203", "start_line": 201, "end_line": 203} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Get Current User { #get-current-user }::L1", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Get Current User { #get-current-user }\n# Get Current User { #get-current-user }\n\nIn the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:\n\n{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}\n\nBut that is still not that useful.\n\nLet's make it give us the current user.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Get Current User { #get-current-user }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L1-L10", "start_line": 1, "end_line": 10} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Create a user model { #create-a-user-model }::L11", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Create a user model { #create-a-user-model }\n## Create a user model { #create-a-user-model }\n\nFirst, let's create a Pydantic user model.\n\nThe same way we use Pydantic to declare bodies, we can use it anywhere else:\n\n{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Create a user model { #create-a-user-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L11-L18", "start_line": 11, "end_line": 18} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Create a `get_current_user` dependency { #create-a-get-current-user-dependency }::L19", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Create a `get_current_user` dependency { #create-a-get-current-user-dependency }\n## Create a `get_current_user` dependency { #create-a-get-current-user-dependency }\n\nLet's create a dependency `get_current_user`.\n\nRemember that dependencies can have sub-dependencies?\n\n`get_current_user` will have a dependency with the same `oauth2_scheme` we created before.\n\nThe same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:\n\n{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Create a `get_current_user` dependency { #create-a-get-current-user-dependency }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L19-L30", "start_line": 19, "end_line": 30} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Get the user { #get-the-user }::L31", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Get the user { #get-the-user }\n## Get the user { #get-the-user }\n\n`get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model:\n\n{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Get the user { #get-the-user }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L31-L36", "start_line": 31, "end_line": 36} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Inject the current user { #inject-the-current-user }::L37", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Inject the current user { #inject-the-current-user }\n## Inject the current user { #inject-the-current-user }\n\nSo now we can use the same `Depends` with our `get_current_user` in the *path operation*:\n\n{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}\n\nNotice that we declare the type of `current_user` as the Pydantic model `User`.\n\nThis will help us inside of the function with all the completion and type checks.\n\n/// tip\n\nYou might remember that request bodies are also declared with Pydantic models.\n\nHere **FastAPI** won't get confused because you are using `Depends`.\n\n///\n\n/// tip\n\nThe way this dependency system is designed allows us to have different dependencies (different \"dependables\") that all return a `User` model.\n\nWe are not restricted to having only one dependency that can return that type of data.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Inject the current user { #inject-the-current-user }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L37-L62", "start_line": 37, "end_line": 62} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Other models { #other-models }::L63", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Other models { #other-models }\n## Other models { #other-models }\n\nYou can now get the current user directly in the *path operation functions* and deal with the security mechanisms at the **Dependency Injection** level, using `Depends`.\n\nAnd you can use any model or data for the security requirements (in this case, a Pydantic model `User`).\n\nBut you are not restricted to using some specific data model, class or type.\n\nDo you want to have an `id` and `email` and not have any `username` in your model? Sure. You can use these same tools.\n\nDo you want to just have a `str`? Or just a `dict`? Or a database class model instance directly? It all works the same way.\n\nYou actually don't have users that log in to your application but robots, bots, or other systems, that have just an access token? Again, it all works the same.\n\nJust use any kind of model, any kind of class, any kind of database that you need for your application. **FastAPI** has you covered with the dependency injection system.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Other models { #other-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L63-L78", "start_line": 63, "end_line": 78} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Code size { #code-size }::L79", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Code size { #code-size }\n## Code size { #code-size }\n\nThis example might seem verbose. Keep in mind that we are mixing security, data models, utility functions and *path operations* in the same file.\n\nBut here's the key point.\n\nThe security and dependency injection stuff is written once.\n\nAnd you can make it as complex as you want. And still, have it written only once, in a single place. With all the flexibility.\n\nBut you can have thousands of endpoints (*path operations*) using the same security system.\n\nAnd all of them (or any portion of them that you want) can take advantage of re-using these dependencies or any other dependencies you create.\n\nAnd all these thousands of *path operations* can be as small as 3 lines:\n\n{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Code size { #code-size }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L79-L96", "start_line": 79, "end_line": 96} {"id": "docs/en/docs/tutorial/security/get-current-user.md::Recap { #recap }::L97", "text": "# Doc: docs/en/docs/tutorial/security/get-current-user.md | Page: Get Current User { #get-current-user } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can now get the current user directly in your *path operation function*.\n\nWe are already halfway there.\n\nWe just need to add a *path operation* for the user/client to actually send the `username` and `password`.\n\nThat comes next.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/get-current-user.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/get-current-user.md#L97-L105", "start_line": 97, "end_line": 105} {"id": "docs/en/docs/tutorial/security/index.md::Security { #security }::L1", "text": "# Doc: docs/en/docs/tutorial/security/index.md | Page: Security { #security } | Section: Security { #security }\n# Security { #security }\n\nThere are many ways to handle security, authentication and authorization.\n\nAnd it normally is a complex and \"difficult\" topic.\n\nIn many frameworks and systems just handling security and authentication takes a big amount of effort and code (in many cases it can be 50% or more of all the code written).\n\n**FastAPI** provides several tools to help you deal with **Security** easily, rapidly, in a standard way, without having to study and learn all the security specifications.\n\nBut first, let's check some small concepts.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/index.md", "symbol": "Security { #security }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/index.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/tutorial/security/index.md::In a hurry? { #in-a-hurry }::L13", "text": "# Doc: docs/en/docs/tutorial/security/index.md | Page: Security { #security } | Section: In a hurry? { #in-a-hurry }\n## In a hurry? { #in-a-hurry }\n\nIf you don't care about any of these terms and you just need to add security with authentication based on username and password *right now*, skip to the next chapters.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/index.md", "symbol": "In a hurry? { #in-a-hurry }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/index.md#L13-L16", "start_line": 13, "end_line": 16} {"id": "docs/en/docs/tutorial/security/index.md::OAuth2 { #oauth2 }::L17", "text": "# Doc: docs/en/docs/tutorial/security/index.md | Page: Security { #security } | Section: OAuth2 { #oauth2 }\n## OAuth2 { #oauth2 }\n\nOAuth2 is a specification that defines several ways to handle authentication and authorization.\n\nIt is quite an extensive specification and covers several complex use cases.\n\nIt includes ways to authenticate using a \"third party\".\n\nThat's what all the systems with \"login with Facebook, Google, X (Twitter), GitHub\" use underneath.\n\n### OAuth 1 { #oauth-1 }\n\nThere was an OAuth 1, which is very different from OAuth2, and more complex, as it included direct specifications on how to encrypt the communication.\n\nIt is not very popular or used nowadays.\n\nOAuth2 doesn't specify how to encrypt the communication, it expects you to have your application served with HTTPS.\n\n/// tip\n\nIn the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/index.md", "symbol": "OAuth2 { #oauth2 }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/index.md#L17-L40", "start_line": 17, "end_line": 40} {"id": "docs/en/docs/tutorial/security/index.md::OpenID Connect { #openid-connect }::L41", "text": "# Doc: docs/en/docs/tutorial/security/index.md | Page: Security { #security } | Section: OpenID Connect { #openid-connect }\n## OpenID Connect { #openid-connect }\n\nOpenID Connect is another specification, based on **OAuth2**.\n\nIt just extends OAuth2 specifying some things that are relatively ambiguous in OAuth2, to try to make it more interoperable.\n\nFor example, Google login uses OpenID Connect (which underneath uses OAuth2).\n\nBut Facebook login doesn't support OpenID Connect. It has its own flavor of OAuth2.\n\n### OpenID (not \"OpenID Connect\") { #openid-not-openid-connect }\n\nThere was also an \"OpenID\" specification. That tried to solve the same thing as **OpenID Connect**, but was not based on OAuth2.\n\nSo, it was a complete additional system.\n\nIt is not very popular or used nowadays.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/index.md", "symbol": "OpenID Connect { #openid-connect }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/index.md#L41-L58", "start_line": 41, "end_line": 58} {"id": "docs/en/docs/tutorial/security/index.md::OpenAPI { #openapi }::L59", "text": "# Doc: docs/en/docs/tutorial/security/index.md | Page: Security { #security } | Section: OpenAPI { #openapi }\n## OpenAPI { #openapi }\n\nOpenAPI (previously known as Swagger) is the open specification for building APIs (now part of the Linux Foundation).\n\n**FastAPI** is based on **OpenAPI**.\n\nThat's what makes it possible to have multiple automatic interactive documentation interfaces, code generation, etc.\n\nOpenAPI has a way to define multiple security \"schemes\".\n\nBy using them, you can take advantage of all these standard-based tools, including these interactive documentation systems.\n\nOpenAPI defines the following security schemes:\n\n* `apiKey`: an application specific key that can come from:\n * A query parameter.\n * A header.\n * A cookie.\n* `http`: standard HTTP authentication systems, including:\n * `bearer`: a header `Authorization` with a value of `Bearer ` plus a token. This is inherited from OAuth2.\n * HTTP Basic authentication.\n * HTTP Digest, etc.\n* `oauth2`: all the OAuth2 ways to handle security (called \"flows\").\n * Several of these flows are appropriate for building an OAuth 2.0 authentication provider (like Google, Facebook, X (Twitter), GitHub, etc):\n * `implicit`\n * `clientCredentials`\n * `authorizationCode`\n * But there is one specific \"flow\" that can be perfectly used for handling authentication in the same application directly:\n * `password`: some next chapters will cover examples of this.\n* `openIdConnect`: has a way to define how to discover OAuth2 authentication data automatically.\n * This automatic discovery is what is defined in the OpenID Connect specification.\n\n\n/// tip\n\nIntegrating other authentication/authorization providers like Google, Facebook, X (Twitter), GitHub, etc. is also possible and relatively easy.\n\nThe most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/index.md", "symbol": "OpenAPI { #openapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/index.md#L59-L99", "start_line": 59, "end_line": 99} {"id": "docs/en/docs/tutorial/security/index.md::**FastAPI** utilities { #fastapi-utilities }::L100", "text": "# Doc: docs/en/docs/tutorial/security/index.md | Page: Security { #security } | Section: **FastAPI** utilities { #fastapi-utilities }\n## **FastAPI** utilities { #fastapi-utilities }\n\nFastAPI provides several tools for each of these security schemes in the `fastapi.security` module that simplify using these security mechanisms.\n\nIn the next chapters you will see how to add security to your API using those tools provided by **FastAPI**.\n\nAnd you will also see how it gets automatically integrated into the interactive documentation system.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/index.md", "symbol": "**FastAPI** utilities { #fastapi-utilities }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/index.md#L100-L106", "start_line": 100, "end_line": 106} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }::L1", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }\n# OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }\n\nNow that we have all the security flow, let's make the application actually secure, using JWT tokens and secure password hashing.\n\nThis code is something you can actually use in your application, save the password hashes in your database, etc.\n\nWe are going to start from where we left in the previous chapter and increment it.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::About JWT { #about-jwt }::L9", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: About JWT { #about-jwt }\n## About JWT { #about-jwt }\n\nJWT means \"JSON Web Tokens\".\n\nIt's a standard to codify a JSON object in a long dense string without spaces. It looks like this:\n\n```\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\n```\n\nIt is not encrypted, so, anyone could recover the information from the contents.\n\nBut it's signed. So, when you receive a token that you issued, you can verify that it was you who issued it.\n\nThat way, you can create a token with an expiration of, let's say, 1 week. And then when the user comes back the next day with the token, you know that user is still logged in to your system.\n\nAfter a week, the token will be expired and the user will not be authorized and will have to sign in again to get a new token. And if the user (or a third party) tried to modify the token to change the expiration, you would be able to discover it, because the signatures would not match.\n\nIf you want to play with JWT tokens and see how they work, check [https://jwt.io](https://jwt.io/).", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "About JWT { #about-jwt }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L9-L28", "start_line": 9, "end_line": 28} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Install `PyJWT` { #install-pyjwt }::L29", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Install `PyJWT` { #install-pyjwt }\n## Install `PyJWT` { #install-pyjwt }\n\nWe need to install `PyJWT` to generate and verify the JWT tokens in Python.\n\nMake sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install `pyjwt`:\n\n
\n\n```console\n$ pip install pyjwt\n\n---> 100%\n```\n\n
\n\n/// note\n\nIf you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`.\n\nYou can read more about it in the [PyJWT Installation docs](https://pyjwt.readthedocs.io/en/latest/installation.html).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Install `PyJWT` { #install-pyjwt }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L29-L52", "start_line": 29, "end_line": 52} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Password hashing { #password-hashing }::L53", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Password hashing { #password-hashing }\n## Password hashing { #password-hashing }\n\n\"Hashing\" means converting some content (a password in this case) into a sequence of bytes (just a string) that looks like gibberish.\n\nWhenever you pass exactly the same content (exactly the same password) you get exactly the same gibberish.\n\nBut you cannot convert from the gibberish back to the password.\n\n### Why use password hashing { #why-use-password-hashing }\n\nIf your database is stolen, the thief won't have your users' plaintext passwords, only the hashes.\n\nSo, the thief won't be able to try to use that password in another system (as many users use the same password everywhere, this would be dangerous).", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Password hashing { #password-hashing }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L53-L66", "start_line": 53, "end_line": 66} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Install `pwdlib` { #install-pwdlib }::L67", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Install `pwdlib` { #install-pwdlib }\n## Install `pwdlib` { #install-pwdlib }\n\npwdlib is a great Python package to handle password hashes.\n\nIt supports many secure hashing algorithms and utilities to work with them.\n\nThe recommended algorithm is \"Argon2\".\n\nMake sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install pwdlib with Argon2:\n\n
\n\n```console\n$ pip install \"pwdlib[argon2]\"\n\n---> 100%\n```\n\n
\n\n/// tip\n\nWith `pwdlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others.\n\nSo, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database.\n\nAnd your users would be able to login from your Django app or from your **FastAPI** app, at the same time.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Install `pwdlib` { #install-pwdlib }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L67-L96", "start_line": 67, "end_line": 96} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Hash and verify the passwords { #hash-and-verify-the-passwords }::L97", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Hash and verify the passwords { #hash-and-verify-the-passwords }\n## Hash and verify the passwords { #hash-and-verify-the-passwords }\n\nImport the tools we need from `pwdlib`.\n\nCreate a PasswordHash instance with recommended settings - it will be used for hashing and verifying passwords.\n\n/// tip\n\npwdlib also supports the bcrypt hashing algorithm but does not include legacy algorithms - for working with outdated hashes, it is recommended to use the passlib library.\n\nFor example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Argon2 or Bcrypt.\n\nAnd be compatible with all of them at the same time.\n\n///\n\nCreate a utility function to hash a password coming from the user.\n\nAnd another utility to verify if a received password matches the hash stored.\n\nAnd another one to authenticate and return a user.\n\n{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *}\n\nWhen `authenticate_user` is called with a username that doesn't exist in the database, we still run `verify_password` against a dummy hash.\n\nThis ensures the endpoint takes roughly the same amount of time to respond whether the username is valid or not, preventing **timing attacks** that could be used to enumerate existing usernames.\n\n/// note\n\nIf you check the new (fake) database `fake_users_db`, you will see what the hashed password looks like now: `\"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc\"`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Hash and verify the passwords { #hash-and-verify-the-passwords }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L97-L130", "start_line": 97, "end_line": 130} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Handle JWT tokens { #handle-jwt-tokens }::L131", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Handle JWT tokens { #handle-jwt-tokens }\n## Handle JWT tokens { #handle-jwt-tokens }\n\nImport the modules installed.\n\nCreate a random secret key that will be used to sign the JWT tokens.\n\nTo generate a secure random secret key use the command:\n\n
\n\n```console\n$ openssl rand -hex 32\n\n09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\n```\n\n
\n\nAnd copy the output to the variable `SECRET_KEY` (don't use the one in the example).\n\nCreate a variable `ALGORITHM` with the algorithm used to sign the JWT token and set it to `\"HS256\"`.\n\nCreate a variable for the expiration of the token.\n\nDefine a Pydantic Model that will be used in the token endpoint for the response.\n\nCreate a utility function to generate a new access token.\n\n{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Handle JWT tokens { #handle-jwt-tokens }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L131-L160", "start_line": 131, "end_line": 160} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Update the dependencies { #update-the-dependencies }::L161", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Update the dependencies { #update-the-dependencies }\n## Update the dependencies { #update-the-dependencies }\n\nUpdate `get_current_user` to receive the same token as before, but this time, using JWT tokens.\n\nDecode the received token, verify it, and return the current user.\n\nIf the token is invalid, return an HTTP error right away.\n\n{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Update the dependencies { #update-the-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L161-L170", "start_line": 161, "end_line": 170} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Update the `/token` *path operation* { #update-the-token-path-operation }::L171", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Update the `/token` *path operation* { #update-the-token-path-operation }\n## Update the `/token` *path operation* { #update-the-token-path-operation }\n\nCreate a `timedelta` with the expiration time of the token.\n\nCreate a real JWT access token and return it.\n\n{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *}\n\n### Technical details about the JWT \"subject\" `sub` { #technical-details-about-the-jwt-subject-sub }\n\nThe JWT specification says that there's a key `sub`, with the subject of the token.\n\nIt's optional to use it, but that's where you would put the user's identification, so we are using it here.\n\nJWT might be used for other things apart from identifying a user and allowing them to perform operations directly on your API.\n\nFor example, you could identify a \"car\" or a \"blog post\".\n\nThen you could add permissions about that entity, like \"drive\" (for the car) or \"edit\" (for the blog).\n\nAnd then, you could give that JWT token to a user (or bot), and they could use it to perform those actions (drive the car, or edit the blog post) without even needing to have an account, just with the JWT token your API generated for that.\n\nUsing these ideas, JWT can be used for way more sophisticated scenarios.\n\nIn those cases, several of those entities could have the same ID, let's say `foo` (a user `foo`, a car `foo`, and a blog post `foo`).\n\nSo, to avoid ID collisions, when creating the JWT token for the user, you could prefix the value of the `sub` key, e.g. with `username:`. So, in this example, the value of `sub` could have been: `username:johndoe`.\n\nThe important thing to keep in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Update the `/token` *path operation* { #update-the-token-path-operation }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L171-L200", "start_line": 171, "end_line": 200} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Check it { #check-it }::L201", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Check it { #check-it }\n## Check it { #check-it }\n\nRun the server and go to the docs: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\nYou'll see the user interface like:\n\n\n\nAuthorize the application the same way as before.\n\nUsing the credentials:\n\nUsername: `johndoe`\nPassword: `secret`\n\n/// tip\n\nNotice that nowhere in the code is the plaintext password \"`secret`\", we only have the hashed version.\n\n///\n\n\n\nCall the endpoint `/users/me/`, you will get the response as:\n\n```JSON\n{\n \"username\": \"johndoe\",\n \"email\": \"johndoe@example.com\",\n \"full_name\": \"John Doe\",\n \"disabled\": false\n}\n```\n\n\n\nIf you open the developer tools, you could see how the data sent only includes the token, the password is only sent in the first request to authenticate the user and get that access token, but not afterwards:\n\n\n\n/// note\n\nNotice the header `Authorization`, with a value that starts with `Bearer `.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Check it { #check-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L201-L246", "start_line": 201, "end_line": 246} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Advanced usage with `scopes` { #advanced-usage-with-scopes }::L247", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Advanced usage with `scopes` { #advanced-usage-with-scopes }\n## Advanced usage with `scopes` { #advanced-usage-with-scopes }\n\nOAuth2 has the notion of \"scopes\".\n\nYou can use them to add a specific set of permissions to a JWT token.\n\nThen you can give this token to a user directly or a third party, to interact with your API with a set of restrictions.\n\nYou can learn how to use them and how they are integrated into **FastAPI** later in the **Advanced User Guide**.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Advanced usage with `scopes` { #advanced-usage-with-scopes }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L247-L256", "start_line": 247, "end_line": 256} {"id": "docs/en/docs/tutorial/security/oauth2-jwt.md::Recap { #recap }::L257", "text": "# Doc: docs/en/docs/tutorial/security/oauth2-jwt.md | Page: OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } | Section: Recap { #recap }\n## Recap { #recap }\n\nWith what you have seen up to now, you can set up a secure **FastAPI** application using standards like OAuth2 and JWT.\n\nIn almost any framework handling the security becomes a rather complex subject quite quickly.\n\nMany packages that simplify it a lot have to make many compromises with the data model, database, and available features. And some of these packages that simplify things too much actually have security flaws underneath.\n\n---\n\n**FastAPI** doesn't make any compromise with any database, data model or tool.\n\nIt gives you all the flexibility to choose the ones that fit your project the best.\n\nAnd you can use directly many well maintained and widely used packages like `pwdlib` and `PyJWT`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages.\n\nBut it provides you the tools to simplify the process as much as possible without compromising flexibility, robustness, or security.\n\nAnd you can use and implement secure, standard protocols, like OAuth2 in a relatively simple way.\n\nYou can learn more in the **Advanced User Guide** about how to use OAuth2 \"scopes\", for a more fine-grained permission system, following these same standards. OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, X (Twitter), etc. to authorize third party applications to interact with their APIs on behalf of their users.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/oauth2-jwt.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/oauth2-jwt.md#L257-L277", "start_line": 257, "end_line": 277} {"id": "docs/en/docs/tutorial/security/simple-oauth2.md::Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer }::L1", "text": "# Doc: docs/en/docs/tutorial/security/simple-oauth2.md | Page: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer } | Section: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer }\n# Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer }\n\nNow let's build from the previous chapter and add the missing parts to have a complete security flow.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/simple-oauth2.md", "symbol": "Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/simple-oauth2.md#L1-L4", "start_line": 1, "end_line": 4} {"id": "docs/en/docs/tutorial/security/simple-oauth2.md::Get the `username` and `password` { #get-the-username-and-password }::L5", "text": "# Doc: docs/en/docs/tutorial/security/simple-oauth2.md | Page: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer } | Section: Get the `username` and `password` { #get-the-username-and-password }\n## Get the `username` and `password` { #get-the-username-and-password }\n\nWe are going to use **FastAPI** security utilities to get the `username` and `password`.\n\nOAuth2 specifies that when using the \"password flow\" (that we are using) the client/user must send `username` and `password` fields as form data.\n\nAnd the spec says that the fields have to be named like that. So `user-name` or `email` wouldn't work.\n\nBut don't worry, you can show it as you wish to your final users in the frontend.\n\nAnd your database models can use any other names you want.\n\nBut for the login *path operation*, we need to use these names to be compatible with the spec (and be able to, for example, use the integrated API documentation system).\n\nThe spec also states that the `username` and `password` must be sent as form data (so, no JSON here).\n\n### `scope` { #scope }\n\nThe spec also says that the client can send another form field \"`scope`\".\n\nThe form field name is `scope` (in singular), but it is actually a long string with \"scopes\" separated by spaces.\n\nEach \"scope\" is just a string (without spaces).\n\nThey are normally used to declare specific security permissions, for example:\n\n* `users:read` or `users:write` are common examples.\n* `instagram_basic` is used by Facebook / Instagram.\n* `https://www.googleapis.com/auth/drive` is used by Google.\n\n/// note\n\nIn OAuth2 a \"scope\" is just a string that declares a specific permission required.\n\nIt doesn't matter if it has other characters like `:` or if it is a URL.\n\nThose details are implementation specific.\n\nFor OAuth2 they are just strings.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/simple-oauth2.md", "symbol": "Get the `username` and `password` { #get-the-username-and-password }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/simple-oauth2.md#L5-L46", "start_line": 5, "end_line": 46} {"id": "docs/en/docs/tutorial/security/simple-oauth2.md::Code to get the `username` and `password` { #code-to-get-the-username-and-password }::L47", "text": "# Doc: docs/en/docs/tutorial/security/simple-oauth2.md | Page: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer } | Section: Code to get the `username` and `password` { #code-to-get-the-username-and-password }\n## Code to get the `username` and `password` { #code-to-get-the-username-and-password }\n\nNow let's use the utilities provided by **FastAPI** to handle this.\n\n### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }\n\nFirst, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`:\n\n{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}\n\n`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:\n\n* The `username`.\n* The `password`.\n* An optional `scope` field as a big string, composed of strings separated by spaces.\n* An optional `grant_type`.\n\n/// tip\n\nThe OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it.\n\nIf you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.\n\n///\n\n* An optional `client_id` (we don't need it for our example).\n* An optional `client_secret` (we don't need it for our example).\n\n/// note\n\nThe `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.\n\n`OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.\n\nBut `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.\n\nBut as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.\n\n///\n\n### Use the form data { #use-the-form-data }\n\n/// tip\n\nThe instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent.\n\nWe are not using `scopes` in this example, but the functionality is there if you need it.\n\n///\n\nNow, get the user data from the (fake) database, using the `username` from the form field.\n\nIf there is no such user, we return an error saying \"Incorrect username or password\".\n\nFor the error, we use the exception `HTTPException`:\n\n{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}\n\n### Check the password { #check-the-password }\n\nAt this point we have the user data from our database, but we haven't checked the password.\n\nLet's put that data in the Pydantic `UserInDB` model first.\n\nYou should never save plaintext passwords, so, we'll use the (fake) password hashing system.\n\nIf the passwords don't match, we return the same error.\n\n#### Password hashing { #password-hashing }\n\n\"Hashing\" means: converting some content (a password in this case) into a sequence of bytes (just a string) that looks like gibberish.\n\nWhenever you pass exactly the same content (exactly the same password) you get exactly the same gibberish.\n\nBut you cannot convert from the gibberish back to the password.\n\n##### Why use password hashing { #why-use-password-hashing }\n\nIf your database is stolen, the thief won't have your users' plaintext passwords, only the hashes.\n\nSo, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).\n\n{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}\n\n#### About `**user_dict` { #about-user-dict }\n\n`UserInDB(**user_dict)` means:\n\n*Pass the keys and values of the `user_dict` directly as key-value arguments, equivalent to:*\n\n```Python\nUserInDB(\n username = user_dict[\"username\"],\n email = user_dict[\"email\"],\n full_name = user_dict[\"full_name\"],\n disabled = user_dict[\"disabled\"],\n hashed_password = user_dict[\"hashed_password\"],\n)\n```\n\n/// note\n\nFor a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user-in-model-dump).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/simple-oauth2.md", "symbol": "Code to get the `username` and `password` { #code-to-get-the-username-and-password }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/simple-oauth2.md#L47-L152", "start_line": 47, "end_line": 152} {"id": "docs/en/docs/tutorial/security/simple-oauth2.md::Return the token { #return-the-token }::L153", "text": "# Doc: docs/en/docs/tutorial/security/simple-oauth2.md | Page: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer } | Section: Return the token { #return-the-token }\n## Return the token { #return-the-token }\n\nThe response of the `token` endpoint must be a JSON object.\n\nIt should have a `token_type`. In our case, as we are using \"Bearer\" tokens, the token type should be \"`bearer`\".\n\nAnd it should have an `access_token`, with a string containing our access token.\n\nFor this simple example, we are going to just be completely insecure and return the same `username` as the token.\n\n/// tip\n\nIn the next chapter, you will see a real secure implementation, with password hashing and JWT tokens.\n\nBut for now, let's focus on the specific details we need.\n\n///\n\n{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}\n\n/// tip\n\nBy the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.\n\nThis is something that you have to do yourself in your code, and make sure you use those JSON keys.\n\nIt's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications.\n\nFor the rest, **FastAPI** handles it for you.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/simple-oauth2.md", "symbol": "Return the token { #return-the-token }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/simple-oauth2.md#L153-L184", "start_line": 153, "end_line": 184} {"id": "docs/en/docs/tutorial/security/simple-oauth2.md::Update the dependencies { #update-the-dependencies }::L185", "text": "# Doc: docs/en/docs/tutorial/security/simple-oauth2.md | Page: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer } | Section: Update the dependencies { #update-the-dependencies }\n## Update the dependencies { #update-the-dependencies }\n\nNow we are going to update our dependencies.\n\nWe want to get the `current_user` *only* if this user is active.\n\nSo, we create an additional dependency `get_current_active_user` that in turn uses `get_current_user` as a dependency.\n\nBoth of these dependencies will just return an HTTP error if the user doesn't exist, or is inactive.\n\nSo, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:\n\n{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}\n\n/// note\n\nThe additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.\n\nAny HTTP (error) status code 401 \"UNAUTHORIZED\" is supposed to also return a `WWW-Authenticate` header.\n\nIn the case of bearer tokens (our case), the value of that header should be `Bearer`.\n\nYou can actually skip that extra header and it would still work.\n\nBut it's provided here to be compliant with the specifications.\n\nAlso, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future.\n\nThat's the benefit of standards...\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/security/simple-oauth2.md", "symbol": "Update the dependencies { #update-the-dependencies }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/simple-oauth2.md#L185-L216", "start_line": 185, "end_line": 216} {"id": "docs/en/docs/tutorial/security/simple-oauth2.md::See it in action { #see-it-in-action }::L217", "text": "# Doc: docs/en/docs/tutorial/security/simple-oauth2.md | Page: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer } | Section: See it in action { #see-it-in-action }\n## See it in action { #see-it-in-action }\n\nOpen the interactive docs: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).\n\n### Authenticate { #authenticate }\n\nClick the \"Authorize\" button.\n\nUse the credentials:\n\nUser: `johndoe`\n\nPassword: `secret`\n\n\n\nAfter authenticating in the system, you will see it like:\n\n\n\n### Get your own user data { #get-your-own-user-data }\n\nNow use the operation `GET` with the path `/users/me`.\n\nYou will get your user's data, like:\n\n```JSON\n{\n \"username\": \"johndoe\",\n \"email\": \"johndoe@example.com\",\n \"full_name\": \"John Doe\",\n \"disabled\": false,\n \"hashed_password\": \"fakehashedsecret\"\n}\n```\n\n\n\nIf you click the lock icon and logout, and then try the same operation again, you will get an HTTP 401 error of:\n\n```JSON\n{\n \"detail\": \"Not authenticated\"\n}\n```\n\n### Inactive user { #inactive-user }\n\nNow try with an inactive user, authenticate with:\n\nUser: `alice`\n\nPassword: `secret2`\n\nAnd try to use the operation `GET` with the path `/users/me`.\n\nYou will get an \"Inactive user\" error, like:\n\n```JSON\n{\n \"detail\": \"Inactive user\"\n}\n```", "source_type": "doc", "path": "docs/en/docs/tutorial/security/simple-oauth2.md", "symbol": "See it in action { #see-it-in-action }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/simple-oauth2.md#L217-L280", "start_line": 217, "end_line": 280} {"id": "docs/en/docs/tutorial/security/simple-oauth2.md::Recap { #recap }::L281", "text": "# Doc: docs/en/docs/tutorial/security/simple-oauth2.md | Page: Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou now have the tools to implement a complete security system based on `username` and `password` for your API.\n\nUsing these tools, you can make the security system compatible with any database and with any user or data model.\n\nThe only detail missing is that it is not actually \"secure\" yet.\n\nIn the next chapter you'll see how to use a secure password hashing library and JWT tokens.", "source_type": "doc", "path": "docs/en/docs/tutorial/security/simple-oauth2.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/security/simple-oauth2.md#L281-L289", "start_line": 281, "end_line": 289} {"id": "docs/en/docs/tutorial/server-sent-events.md::Server-Sent Events (SSE) { #server-sent-events-sse }::L1", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: Server-Sent Events (SSE) { #server-sent-events-sse }\n# Server-Sent Events (SSE) { #server-sent-events-sse }\n\nYou can stream data to the client using **Server-Sent Events** (SSE).\n\nThis is similar to [Stream JSON Lines](stream-json-lines.md), but uses the `text/event-stream` format, which is supported natively by browsers with the [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).\n\n/// note\n\nAdded in FastAPI 0.135.0.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "Server-Sent Events (SSE) { #server-sent-events-sse }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/tutorial/server-sent-events.md::What are Server-Sent Events? { #what-are-server-sent-events }::L13", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: What are Server-Sent Events? { #what-are-server-sent-events }\n## What are Server-Sent Events? { #what-are-server-sent-events }\n\nSSE is a standard for streaming data from the server to the client over HTTP.\n\nEach event is a small text block with \"fields\" like `data`, `event`, `id`, and `retry`, separated by blank lines.\n\nIt looks like this:\n\n```\ndata: {\"name\": \"Portal Gun\", \"price\": 999.99}\n\ndata: {\"name\": \"Plumbus\", \"price\": 32.99}\n\n```\n\nSSE is commonly used for AI chat streaming, live notifications, logs and observability, and other cases where the server pushes updates to the client.\n\n/// tip\n\nIf you want to stream binary data, for example video or audio, check the advanced guide: [Stream Data](../advanced/stream-data.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "What are Server-Sent Events? { #what-are-server-sent-events }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L13-L35", "start_line": 13, "end_line": 35} {"id": "docs/en/docs/tutorial/server-sent-events.md::Stream SSE with FastAPI { #stream-sse-with-fastapi }::L36", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: Stream SSE with FastAPI { #stream-sse-with-fastapi }\n## Stream SSE with FastAPI { #stream-sse-with-fastapi }\n\nTo stream SSE with FastAPI, use `yield` in your *path operation function* and set `response_class=EventSourceResponse`.\n\nImport `EventSourceResponse` from `fastapi.sse`:\n\n{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}\n\nEach yielded item is encoded as JSON and sent in the `data:` field of an SSE event.\n\nIf you declare the return type as `AsyncIterable[Item]`, FastAPI will use it to **validate**, **document**, and **serialize** the data using Pydantic.\n\n{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}\n\n/// tip\n\nAs Pydantic will serialize it in the **Rust** side, you will get much higher **performance** than if you don't declare a return type.\n\n///\n\n### Non-async *path operation functions* { #non-async-path-operation-functions }\n\nYou can also use regular `def` functions (without `async`), and use `yield` the same way.\n\nFastAPI will make sure it's run correctly so that it doesn't block the event loop.\n\nAs in this case the function is not async, the right return type would be `Iterable[Item]`:\n\n{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}\n\n### No Return Type { #no-return-type }\n\nYou can also omit the return type. FastAPI will use the [`jsonable_encoder`](./encoder.md) to convert the data and send it.\n\n{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "Stream SSE with FastAPI { #stream-sse-with-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L36-L71", "start_line": 36, "end_line": 71} {"id": "docs/en/docs/tutorial/server-sent-events.md::`ServerSentEvent` { #serversentevent }::L72", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: `ServerSentEvent` { #serversentevent }\n## `ServerSentEvent` { #serversentevent }\n\nIf you need to set SSE fields like `event`, `id`, `retry`, or `comment`, you can yield `ServerSentEvent` objects instead of plain data.\n\nImport `ServerSentEvent` from `fastapi.sse`:\n\n{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}\n\nThe `data` field is always encoded as JSON. You can pass any value that can be serialized as JSON, including Pydantic models.", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "`ServerSentEvent` { #serversentevent }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L72-L81", "start_line": 72, "end_line": 81} {"id": "docs/en/docs/tutorial/server-sent-events.md::Raw Data { #raw-data }::L82", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: Raw Data { #raw-data }\n## Raw Data { #raw-data }\n\nIf you need to send data **without** JSON encoding, use `raw_data` instead of `data`.\n\nThis is useful for sending pre-formatted text, log lines, or special \"sentinel\" values like `[DONE]`.\n\n{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}\n\n/// note\n\n`data` and `raw_data` are mutually exclusive. You can only set one of them on each `ServerSentEvent`.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "Raw Data { #raw-data }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L82-L95", "start_line": 82, "end_line": 95} {"id": "docs/en/docs/tutorial/server-sent-events.md::Resuming with `Last-Event-ID` { #resuming-with-last-event-id }::L96", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: Resuming with `Last-Event-ID` { #resuming-with-last-event-id }\n## Resuming with `Last-Event-ID` { #resuming-with-last-event-id }\n\nWhen a browser reconnects after a connection drop, it sends the last received `id` in the `Last-Event-ID` header.\n\nYou can read it as a header parameter and use it to resume the stream from where the client left off:\n\n{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "Resuming with `Last-Event-ID` { #resuming-with-last-event-id }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L96-L103", "start_line": 96, "end_line": 103} {"id": "docs/en/docs/tutorial/server-sent-events.md::SSE with POST { #sse-with-post }::L104", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: SSE with POST { #sse-with-post }\n## SSE with POST { #sse-with-post }\n\nSSE works with **any HTTP method**, not just `GET`.\n\nThis is useful for protocols like [MCP](https://modelcontextprotocol.io) that stream SSE over `POST`:\n\n{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "SSE with POST { #sse-with-post }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L104-L111", "start_line": 104, "end_line": 111} {"id": "docs/en/docs/tutorial/server-sent-events.md::Technical Details { #technical-details }::L112", "text": "# Doc: docs/en/docs/tutorial/server-sent-events.md | Page: Server-Sent Events (SSE) { #server-sent-events-sse } | Section: Technical Details { #technical-details }\n## Technical Details { #technical-details }\n\nFastAPI implements some SSE best practices out of the box.\n\n* Send a **\"keep alive\" `ping` comment** every 15 seconds when there hasn't been any message, to prevent some proxies from closing the connection, as suggested in the [HTML specification: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes).\n* Set the `Cache-Control: no-cache` header to **prevent caching** of the stream.\n* Set a special header `X-Accel-Buffering: no` to **prevent buffering** in some proxies like Nginx.\n\nYou don't have to do anything about it, it works out of the box. 🤓", "source_type": "doc", "path": "docs/en/docs/tutorial/server-sent-events.md", "symbol": "Technical Details { #technical-details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/server-sent-events.md#L112-L120", "start_line": 112, "end_line": 120} {"id": "docs/en/docs/tutorial/sql-databases.md::SQL (Relational) Databases { #sql-relational-databases }::L1", "text": "# Doc: docs/en/docs/tutorial/sql-databases.md | Page: SQL (Relational) Databases { #sql-relational-databases } | Section: SQL (Relational) Databases { #sql-relational-databases }\n# SQL (Relational) Databases { #sql-relational-databases }\n\n**FastAPI** doesn't require you to use a SQL (relational) database. But you can use **any database** that you want.\n\nHere we'll see an example using [SQLModel](https://sqlmodel.tiangolo.com/).\n\n**SQLModel** is built on top of [SQLAlchemy](https://www.sqlalchemy.org/) and Pydantic. It was made by the same author of **FastAPI** to be the perfect match for FastAPI applications that need to use **SQL databases**.\n\n/// tip\n\nYou could use any other SQL or NoSQL database library you want (in some cases called \"ORMs\"), FastAPI doesn't force you to use anything. 😎\n\n///\n\nAs SQLModel is based on SQLAlchemy, you can easily use **any database supported** by SQLAlchemy (which makes them also supported by SQLModel), like:\n\n* PostgreSQL\n* MySQL\n* SQLite\n* Oracle\n* Microsoft SQL Server, etc.\n\nIn this example, we'll use **SQLite**, because it uses a single file and Python has integrated support. So, you can copy this example and run it as is.\n\nLater, for your production application, you might want to use a database server like **PostgreSQL**.\n\n/// tip\n\nThere is an official project generator with **FastAPI** and **PostgreSQL** including a frontend and more tools: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)\n\n///\n\nThis is a very simple and short tutorial, if you want to learn about databases in general, about SQL, or more advanced features, go to the [SQLModel docs](https://sqlmodel.tiangolo.com/).", "source_type": "doc", "path": "docs/en/docs/tutorial/sql-databases.md", "symbol": "SQL (Relational) Databases { #sql-relational-databases }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/sql-databases.md#L1-L34", "start_line": 1, "end_line": 34} {"id": "docs/en/docs/tutorial/sql-databases.md::Install `SQLModel` { #install-sqlmodel }::L35", "text": "# Doc: docs/en/docs/tutorial/sql-databases.md | Page: SQL (Relational) Databases { #sql-relational-databases } | Section: Install `SQLModel` { #install-sqlmodel }\n## Install `SQLModel` { #install-sqlmodel }\n\nFirst, make sure you create your [virtual environment](../virtual-environments.md), activate it, and then install `sqlmodel`:\n\n
\n\n```console\n$ pip install sqlmodel\n---> 100%\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/sql-databases.md", "symbol": "Install `SQLModel` { #install-sqlmodel }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/sql-databases.md#L35-L47", "start_line": 35, "end_line": 47} {"id": "docs/en/docs/tutorial/sql-databases.md::Create the App with a Single Model { #create-the-app-with-a-single-model }::L48", "text": "# Doc: docs/en/docs/tutorial/sql-databases.md | Page: SQL (Relational) Databases { #sql-relational-databases } | Section: Create the App with a Single Model { #create-the-app-with-a-single-model }\n## Create the App with a Single Model { #create-the-app-with-a-single-model }\n\nWe'll create the simplest first version of the app with a single **SQLModel** model first.\n\nLater we'll improve it increasing security and versatility with **multiple models** below. 🤓\n\n### Create Models { #create-models }\n\nImport `SQLModel` and create a database model:\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *}\n\nThe `Hero` class is very similar to a Pydantic model (in fact, underneath, it actually *is a Pydantic model*).\n\nThere are a few differences:\n\n* `table=True` tells SQLModel that this is a *table model*, it should represent a **table** in the SQL database, it's not just a *data model* (as would be any other regular Pydantic class).\n\n* `Field(primary_key=True)` tells SQLModel that the `id` is the **primary key** in the SQL database (you can learn more about SQL primary keys in the SQLModel docs).\n\n **Note:** We use `int | None` for the primary key field so that in Python code we can *create an object without an `id`* (`id=None`), assuming the database will *generate it when saving*. SQLModel understands that the database will provide the `id` and *defines the column as a non-null `INTEGER`* in the database schema. See [SQLModel docs on primary keys](https://sqlmodel.tiangolo.com/tutorial/create-db-and-table/#primary-key-id) for details.\n\n* `Field(index=True)` tells SQLModel that it should create a **SQL index** for this column, that would allow faster lookups in the database when reading data filtered by this column.\n\n SQLModel will know that something declared as `str` will be a SQL column of type `TEXT` (or `VARCHAR`, depending on the database).\n\n### Create an Engine { #create-an-engine }\n\nA SQLModel `engine` (underneath it's actually a SQLAlchemy `engine`) is what **holds the connections** to the database.\n\nYou would have **one single `engine` object** for all your code to connect to the same database.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *}\n\nUsing `check_same_thread=False` allows FastAPI to use the same SQLite database in different threads. This is necessary as **one single request** could use **more than one thread** (for example in dependencies).\n\nDon't worry, with the way the code is structured, we'll make sure we use **a single SQLModel *session* per request** later, this is actually what the `check_same_thread` is trying to achieve.\n\n### Create the Tables { #create-the-tables }\n\nWe then add a function that uses `SQLModel.metadata.create_all(engine)` to **create the tables** for all the *table models*.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *}\n\n### Create a Session Dependency { #create-a-session-dependency }\n\nA **`Session`** is what stores the **objects in memory** and keeps track of any changes needed in the data, then it **uses the `engine`** to communicate with the database.\n\nWe will create a FastAPI **dependency** with `yield` that will provide a new `Session` for each request. This is what ensures that we use a single session per request. 🤓\n\nThen we create an `Annotated` dependency `SessionDep` to simplify the rest of the code that will use this dependency.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *}\n\n### Create Database Tables on Startup { #create-database-tables-on-startup }\n\nWe will create the database tables when the application starts.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *}\n\nHere we create the tables on an application startup event.\n\nFor production you would probably use a migration script that runs before you start your app. 🤓\n\n/// tip\n\nSQLModel will have migration utilities wrapping Alembic, but for now, you can use [Alembic](https://alembic.sqlalchemy.org/en/latest/) directly.\n\n///\n\n### Create a Hero { #create-a-hero }\n\nBecause each SQLModel model is also a Pydantic model, you can use it in the same **type annotations** that you could use Pydantic models.\n\nFor example, if you declare a parameter of type `Hero`, it will be read from the **JSON body**.\n\nThe same way, you can declare it as the function's **return type**, and then the shape of the data will show up in the automatic API docs UI.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *}\n\nHere we use the `SessionDep` dependency (a `Session`) to add the new `Hero` to the `Session` instance, commit the changes to the database, refresh the data in the `hero`, and then return it.\n\n### Read Heroes { #read-heroes }\n\nWe can **read** `Hero`s from the database using a `select()`. We can include a `limit` and `offset` to paginate the results.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *}\n\n### Read One Hero { #read-one-hero }\n\nWe can **read** a single `Hero`.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *}\n\n### Delete a Hero { #delete-a-hero }\n\nWe can also **delete** a `Hero`.\n\n{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *}\n\n### Run the App { #run-the-app }\n\nYou can run the app:\n\n
\n\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nThen go to the `/docs` UI, you will see that **FastAPI** is using these **models** to **document** the API, and it will use them to **serialize** and **validate** the data too.\n\n
\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/sql-databases.md", "symbol": "Create the App with a Single Model { #create-the-app-with-a-single-model }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/sql-databases.md#L48-L167", "start_line": 48, "end_line": 167} {"id": "docs/en/docs/tutorial/sql-databases.md::Update the App with Multiple Models { #update-the-app-with-multiple-models }::L168", "text": "# Doc: docs/en/docs/tutorial/sql-databases.md | Page: SQL (Relational) Databases { #sql-relational-databases } | Section: Update the App with Multiple Models { #update-the-app-with-multiple-models }\n## Update the App with Multiple Models { #update-the-app-with-multiple-models }\n\nNow let's **refactor** this app a bit to increase **security** and **versatility**.\n\nIf you check the previous app, in the UI you can see that, up to now, it lets the client decide the `id` of the `Hero` to create. 😱\n\nWe shouldn't let that happen, they could overwrite an `id` we already have assigned in the DB. Deciding the `id` should be done by the **backend** or the **database**, **not by the client**.\n\nAdditionally, we create a `secret_name` for the hero, but so far, we are returning it everywhere, that's not very **secret**... 😅\n\nWe'll fix these things by adding a few **extra models**. Here's where SQLModel will shine. ✨\n\n### Create Multiple Models { #create-multiple-models }\n\nIn **SQLModel**, any model class that has `table=True` is a **table model**.\n\nAnd any model class that doesn't have `table=True` is a **data model**, these ones are actually just Pydantic models (with a couple of small extra features). 🤓\n\nWith SQLModel, we can use **inheritance** to **avoid duplicating** all the fields in all the cases.\n\n#### `HeroBase` - the base class { #herobase-the-base-class }\n\nLet's start with a `HeroBase` model that has all the **fields that are shared** by all the models:\n\n* `name`\n* `age`\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *}\n\n#### `Hero` - the *table model* { #hero-the-table-model }\n\nThen let's create `Hero`, the actual *table model*, with the **extra fields** that are not always in the other models:\n\n* `id`\n* `secret_name`\n\nBecause `Hero` inherits from `HeroBase`, it **also** has the **fields** declared in `HeroBase`, so all the fields for `Hero` are:\n\n* `id`\n* `name`\n* `age`\n* `secret_name`\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *}\n\n#### `HeroPublic` - the public *data model* { #heropublic-the-public-data-model }\n\nNext, we create a `HeroPublic` model, this is the one that will be **returned** to the clients of the API.\n\nIt has the same fields as `HeroBase`, so it won't include `secret_name`.\n\nFinally, the identity of our heroes is protected! 🥷\n\nIt also re-declares `id: int`. By doing this, we are making a **contract** with the API clients, so that they can always expect the `id` to be there and to be an `int` (it will never be `None`).\n\n/// tip\n\nHaving the return model ensure that a value is always available and always `int` (not `None`) is very useful for the API clients, they can write much simpler code having this certainty.\n\nAlso, **automatically generated clients** will have simpler interfaces, so that the developers communicating with your API can have a much better time working with your API. 😎\n\n///\n\nAll the fields in `HeroPublic` are the same as in `HeroBase`, with `id` declared as `int` (not `None`):\n\n* `id`\n* `name`\n* `age`\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *}\n\n#### `HeroCreate` - the *data model* to create a hero { #herocreate-the-data-model-to-create-a-hero }\n\nNow we create a `HeroCreate` model, this is the one that will **validate** the data from the clients.\n\nIt has the same fields as `HeroBase`, and it also has `secret_name`.\n\nNow, when the clients **create a new hero**, they will send the `secret_name`, it will be stored in the database, but those secret names won't be returned in the API to the clients.\n\n/// tip\n\nThis is how you would handle **passwords**. Receive them, but don't return them in the API.\n\nYou would also **hash** the values of the passwords before storing them, **never store them in plain text**.\n\n///\n\nThe fields of `HeroCreate` are:\n\n* `name`\n* `age`\n* `secret_name`\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *}\n\n#### `HeroUpdate` - the *data model* to update a hero { #heroupdate-the-data-model-to-update-a-hero }\n\nWe didn't have a way to **update a hero** in the previous version of the app, but now with **multiple models**, we can do it. 🎉\n\nThe `HeroUpdate` *data model* is somewhat special, it has **all the same fields** that would be needed to create a new hero, but all the fields are **optional** (they all have a default value). This way, when you update a hero, you can send just the fields that you want to update.\n\nBecause all the **fields actually change** (the type now includes `None` and they now have a default value of `None`), we need to **re-declare** them.\n\nWe don't really need to inherit from `HeroBase` because we are re-declaring all the fields. I'll leave it inheriting just for consistency, but this is not necessary. It's more a matter of personal taste. 🤷\n\nThe fields of `HeroUpdate` are:\n\n* `name`\n* `age`\n* `secret_name`\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *}\n\n### Create with `HeroCreate` and return a `HeroPublic` { #create-with-herocreate-and-return-a-heropublic }\n\nNow that we have **multiple models**, we can update the parts of the app that use them.\n\nWe receive in the request a `HeroCreate` *data model*, and from it, we create a `Hero` *table model*.\n\nThis new *table model* `Hero` will have the fields sent by the client, and will also have an `id` generated by the database.\n\nThen we return the same *table model* `Hero` as is from the function. But as we declare the `response_model` with the `HeroPublic` *data model*, **FastAPI** will use `HeroPublic` to validate and serialize the data.\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *}\n\n/// tip\n\nNow we use `response_model=HeroPublic` instead of the **return type annotation** `-> HeroPublic` because the value that we are returning is actually *not* a `HeroPublic`.\n\nIf we had declared `-> HeroPublic`, your editor and linter would complain (rightfully so) that you are returning a `Hero` instead of a `HeroPublic`.\n\nBy declaring it in `response_model` we are telling **FastAPI** to do its thing, without interfering with the type annotations and the help from your editor and other tools.\n\n///\n\n### Read Heroes with `HeroPublic` { #read-heroes-with-heropublic }\n\nWe can do the same as before to **read** `Hero`s, again, we use `response_model=list[HeroPublic]` to ensure that the data is validated and serialized correctly.\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *}\n\n### Read One Hero with `HeroPublic` { #read-one-hero-with-heropublic }\n\nWe can **read** a single hero:\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *}\n\n### Update a Hero with `HeroUpdate` { #update-a-hero-with-heroupdate }\n\nWe can **update a hero**. For this we use an HTTP `PATCH` operation.\n\nAnd in the code, we get a `dict` with all the data sent by the client, **only the data sent by the client**, excluding any values that would be there just for being the default values. To do it we use `exclude_unset=True`. This is the main trick. 🪄\n\nThen we use `hero_db.sqlmodel_update(hero_data)` to update the `hero_db` with the data from `hero_data`.\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *}\n\n### Delete a Hero Again { #delete-a-hero-again }\n\n**Deleting** a hero stays pretty much the same.\n\nWe won't satisfy the desire to refactor everything in this one. 😅\n\n{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *}\n\n### Run the App Again { #run-the-app-again }\n\nYou can run the app again:\n\n
\n\n```console\n$ fastapi dev\n\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\n
\n\nIf you go to the `/docs` API UI, you will see that it is now updated, and it won't expect to receive the `id` from the client when creating a hero, etc.\n\n
\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/sql-databases.md", "symbol": "Update the App with Multiple Models { #update-the-app-with-multiple-models }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/sql-databases.md#L168-L352", "start_line": 168, "end_line": 352} {"id": "docs/en/docs/tutorial/sql-databases.md::Recap { #recap }::L353", "text": "# Doc: docs/en/docs/tutorial/sql-databases.md | Page: SQL (Relational) Databases { #sql-relational-databases } | Section: Recap { #recap }\n## Recap { #recap }\n\nYou can use [**SQLModel**](https://sqlmodel.tiangolo.com/) to interact with a SQL database and simplify the code with *data models* and *table models*.\n\nYou can learn a lot more at the **SQLModel** docs, there's a longer mini [tutorial on using SQLModel with **FastAPI**](https://sqlmodel.tiangolo.com/tutorial/fastapi/). 🚀", "source_type": "doc", "path": "docs/en/docs/tutorial/sql-databases.md", "symbol": "Recap { #recap }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/sql-databases.md#L353-L357", "start_line": 353, "end_line": 357} {"id": "docs/en/docs/tutorial/static-files.md::Static Files { #static-files }::L1", "text": "# Doc: docs/en/docs/tutorial/static-files.md | Page: Static Files { #static-files } | Section: Static Files { #static-files }\n# Static Files { #static-files }\n\nYou can serve static files automatically from a directory using `StaticFiles`.\n\n/// tip\n\nIf you need to host a frontend, use `app.frontend()` instead, read about it in [Frontend](frontend.md).\n\n`app.frontend()` uses `StaticFiles` underneath, with several additional advantages for frontends, like handling client-side routing.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/static-files.md", "symbol": "Static Files { #static-files }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/static-files.md#L1-L12", "start_line": 1, "end_line": 12} {"id": "docs/en/docs/tutorial/static-files.md::Use `StaticFiles` { #use-staticfiles }::L13", "text": "# Doc: docs/en/docs/tutorial/static-files.md | Page: Static Files { #static-files } | Section: Use `StaticFiles` { #use-staticfiles }\n## Use `StaticFiles` { #use-staticfiles }\n\n* Import `StaticFiles`.\n* \"Mount\" a `StaticFiles()` instance in a specific path.\n\n{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *}\n\n/// note | Technical Details\n\nYou could also use `from starlette.staticfiles import StaticFiles`.\n\n**FastAPI** provides the same `starlette.staticfiles` as `fastapi.staticfiles` just as a convenience for you, the developer. But it actually comes directly from Starlette.\n\n///\n\n### What is \"Mounting\" { #what-is-mounting }\n\n\"Mounting\" means adding a complete \"independent\" application in a specific path, that then takes care of handling all the sub-paths.\n\nThis is different from using an `APIRouter` as a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application, etc.\n\nYou can read more about this in the [Advanced User Guide](../advanced/index.md).", "source_type": "doc", "path": "docs/en/docs/tutorial/static-files.md", "symbol": "Use `StaticFiles` { #use-staticfiles }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/static-files.md#L13-L35", "start_line": 13, "end_line": 35} {"id": "docs/en/docs/tutorial/static-files.md::Details { #details }::L36", "text": "# Doc: docs/en/docs/tutorial/static-files.md | Page: Static Files { #static-files } | Section: Details { #details }\n## Details { #details }\n\nThe first `\"/static\"` refers to the sub-path this \"sub-application\" will be \"mounted\" on. So, any path that starts with `\"/static\"` will be handled by it.\n\nThe `directory=\"static\"` refers to the name of the directory that contains your static files.\n\nThe `name=\"static\"` gives it a name that can be used internally by **FastAPI**.\n\nAll these parameters can be different than \"`static`\", adjust them to the needs and specific details of your own application.", "source_type": "doc", "path": "docs/en/docs/tutorial/static-files.md", "symbol": "Details { #details }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/static-files.md#L36-L45", "start_line": 36, "end_line": 45} {"id": "docs/en/docs/tutorial/static-files.md::More info { #more-info }::L46", "text": "# Doc: docs/en/docs/tutorial/static-files.md | Page: Static Files { #static-files } | Section: More info { #more-info }\n## More info { #more-info }\n\nFor more details and options check [Starlette's docs about Static Files](https://www.starlette.dev/staticfiles/).", "source_type": "doc", "path": "docs/en/docs/tutorial/static-files.md", "symbol": "More info { #more-info }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/static-files.md#L46-L48", "start_line": 46, "end_line": 48} {"id": "docs/en/docs/tutorial/stream-json-lines.md::Stream JSON Lines { #stream-json-lines }::L1", "text": "# Doc: docs/en/docs/tutorial/stream-json-lines.md | Page: Stream JSON Lines { #stream-json-lines } | Section: Stream JSON Lines { #stream-json-lines }\n# Stream JSON Lines { #stream-json-lines }\n\nYou could have a sequence of data that you would like to send in a \"**stream**\", you could do it with **JSON Lines**.\n\n/// note\n\nAdded in FastAPI 0.134.0.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/stream-json-lines.md", "symbol": "Stream JSON Lines { #stream-json-lines }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/stream-json-lines.md#L1-L10", "start_line": 1, "end_line": 10} {"id": "docs/en/docs/tutorial/stream-json-lines.md::What is a Stream? { #what-is-a-stream }::L11", "text": "# Doc: docs/en/docs/tutorial/stream-json-lines.md | Page: Stream JSON Lines { #stream-json-lines } | Section: What is a Stream? { #what-is-a-stream }\n## What is a Stream? { #what-is-a-stream }\n\n\"**Streaming**\" data means that your app will start sending data items to the client without waiting for the entire sequence of items to be ready.\n\nSo, it will send the first item, the client will receive and start processing it, and you might still be producing the next item.\n\n```mermaid\nsequenceDiagram\n participant App\n participant Client\n\n App->>App: Produce Item 1\n App->>Client: Send Item 1\n App->>App: Produce Item 2\n Client->>Client: Process Item 1\n App->>Client: Send Item 2\n App->>App: Produce Item 3\n Client->>Client: Process Item 2\n App->>Client: Send Item 3\n Client->>Client: Process Item 3\n Note over App: Keeps producing...\n Note over Client: Keeps consuming...\n```\n\nIt could even be an infinite stream, where you keep sending data.", "source_type": "doc", "path": "docs/en/docs/tutorial/stream-json-lines.md", "symbol": "What is a Stream? { #what-is-a-stream }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/stream-json-lines.md#L11-L36", "start_line": 11, "end_line": 36} {"id": "docs/en/docs/tutorial/stream-json-lines.md::JSON Lines { #json-lines }::L37", "text": "# Doc: docs/en/docs/tutorial/stream-json-lines.md | Page: Stream JSON Lines { #stream-json-lines } | Section: JSON Lines { #json-lines }\n## JSON Lines { #json-lines }\n\nIn these cases, it's common to send \"**JSON Lines**\", which is a format where you send one JSON object per line.\n\nA response would have a content type of `application/jsonl` (instead of `application/json`) and the body would be something like:\n\n```json\n{\"name\": \"Plumbus\", \"description\": \"A multi-purpose household device.\"}\n{\"name\": \"Portal Gun\", \"description\": \"A portal opening device.\"}\n{\"name\": \"Meeseeks Box\", \"description\": \"A box that summons a Meeseeks.\"}\n```\n\nIt's very similar to a JSON array (equivalent of a Python list), but instead of being wrapped in `[]` and having `,` between the items, it has **one JSON object per line**, they are separated by a new line character.\n\n/// note\n\nThe important point is that your app will be able to produce each line in turn, while the client consumes the previous lines.\n\n///\n\n/// note | Technical Details\n\nBecause each JSON object will be separated by a new line, they can't contain literal new line characters in their content, but they can contain escaped new lines (`\\n`), which is part of the JSON standard.\n\nBut normally you won't have to worry about it, it's done automatically, continue reading. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/stream-json-lines.md", "symbol": "JSON Lines { #json-lines }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/stream-json-lines.md#L37-L64", "start_line": 37, "end_line": 64} {"id": "docs/en/docs/tutorial/stream-json-lines.md::Use Cases { #use-cases }::L65", "text": "# Doc: docs/en/docs/tutorial/stream-json-lines.md | Page: Stream JSON Lines { #stream-json-lines } | Section: Use Cases { #use-cases }\n## Use Cases { #use-cases }\n\nYou could use this to stream data from an **AI LLM** service, from **logs** or **telemetry**, or from other types of data that can be structured in **JSON** items.\n\n/// tip\n\nIf you want to stream binary data, for example video or audio, check the advanced guide: [Stream Data](../advanced/stream-data.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/stream-json-lines.md", "symbol": "Use Cases { #use-cases }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/stream-json-lines.md#L65-L74", "start_line": 65, "end_line": 74} {"id": "docs/en/docs/tutorial/stream-json-lines.md::Stream JSON Lines with FastAPI { #stream-json-lines-with-fastapi }::L75", "text": "# Doc: docs/en/docs/tutorial/stream-json-lines.md | Page: Stream JSON Lines { #stream-json-lines } | Section: Stream JSON Lines with FastAPI { #stream-json-lines-with-fastapi }\n## Stream JSON Lines with FastAPI { #stream-json-lines-with-fastapi }\n\nTo stream JSON Lines with FastAPI you can, instead of using `return` in your *path operation function*, use `yield` to produce each item in turn.\n\n{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[1:24] hl[24] *}\n\nIf each JSON item you want to send back is of type `Item` (a Pydantic model) and it's an async function, you can declare the return type as `AsyncIterable[Item]`:\n\n{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[1:24] hl[9:11,22] *}\n\nIf you declare the return type, FastAPI will use it to **validate** the data, **document** it in OpenAPI, **filter** it, and **serialize** it using Pydantic.\n\n/// tip\n\nAs Pydantic will serialize it in the **Rust** side, you will get much higher **performance** than if you don't declare a return type.\n\n///\n\n### Non-async *path operation functions* { #non-async-path-operation-functions }\n\nYou can also use regular `def` functions (without `async`), and use `yield` the same way.\n\nFastAPI will make sure it's run correctly so that it doesn't block the event loop.\n\nAs in this case the function is not async, the right return type would be `Iterable[Item]`:\n\n{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[27:30] hl[28] *}\n\n### No Return Type { #no-return-type }\n\nYou can also omit the return type. FastAPI will then use the [`jsonable_encoder`](./encoder.md) to convert the data to something that can be serialized to JSON and then send it as JSON Lines.\n\n{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[33:36] hl[34] *}", "source_type": "doc", "path": "docs/en/docs/tutorial/stream-json-lines.md", "symbol": "Stream JSON Lines with FastAPI { #stream-json-lines-with-fastapi }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/stream-json-lines.md#L75-L108", "start_line": 75, "end_line": 108} {"id": "docs/en/docs/tutorial/stream-json-lines.md::Server-Sent Events (SSE) { #server-sent-events-sse }::L109", "text": "# Doc: docs/en/docs/tutorial/stream-json-lines.md | Page: Stream JSON Lines { #stream-json-lines } | Section: Server-Sent Events (SSE) { #server-sent-events-sse }\n## Server-Sent Events (SSE) { #server-sent-events-sse }\n\nFastAPI also has first-class support for Server-Sent Events (SSE), which are quite similar but with a couple of extra details. You can learn about them in the next chapter: [Server-Sent Events (SSE)](server-sent-events.md). 🤓", "source_type": "doc", "path": "docs/en/docs/tutorial/stream-json-lines.md", "symbol": "Server-Sent Events (SSE) { #server-sent-events-sse }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/stream-json-lines.md#L109-L111", "start_line": 109, "end_line": 111} {"id": "docs/en/docs/tutorial/testing.md::Testing { #testing }::L1", "text": "# Doc: docs/en/docs/tutorial/testing.md | Page: Testing { #testing } | Section: Testing { #testing }\n# Testing { #testing }\n\nThanks to [Starlette](https://www.starlette.dev/testclient/), testing **FastAPI** applications is easy and enjoyable.\n\nIt is based on [HTTPX](https://www.python-httpx.org), which in turn is designed based on Requests, so it's very familiar and intuitive.\n\nWith it, you can use [pytest](https://docs.pytest.org/) directly with **FastAPI**.", "source_type": "doc", "path": "docs/en/docs/tutorial/testing.md", "symbol": "Testing { #testing }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/testing.md#L1-L8", "start_line": 1, "end_line": 8} {"id": "docs/en/docs/tutorial/testing.md::Using `TestClient` { #using-testclient }::L9", "text": "# Doc: docs/en/docs/tutorial/testing.md | Page: Testing { #testing } | Section: Using `TestClient` { #using-testclient }\n## Using `TestClient` { #using-testclient }\n\n/// note\n\nTo use `TestClient`, first install [`httpx`](https://www.python-httpx.org).\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:\n\n```console\n$ pip install httpx\n```\n\n///\n\nImport `TestClient`.\n\nCreate a `TestClient` by passing your **FastAPI** application to it.\n\nCreate functions with a name that starts with `test_` (this is a standard `pytest` convention).\n\nUse the `TestClient` object the same way as you do with `httpx`.\n\nWrite simple `assert` statements with the standard Python expressions that you need to check (again, standard `pytest`).\n\n{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *}\n\n/// tip\n\nNotice that the testing functions are normal `def`, not `async def`.\n\nAnd the calls to the client are also normal calls, not using `await`.\n\nThis allows you to use `pytest` directly without complications.\n\n///\n\n/// note | Technical Details\n\nYou could also use `from starlette.testclient import TestClient`.\n\n**FastAPI** provides the same `starlette.testclient` as `fastapi.testclient` just as a convenience for you, the developer. But it comes directly from Starlette.\n\n///\n\n/// tip\n\nIf you want to call `async` functions in your tests apart from sending requests to your FastAPI application (e.g. asynchronous database functions), have a look at the [Async Tests](../advanced/async-tests.md) in the advanced tutorial.\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/testing.md", "symbol": "Using `TestClient` { #using-testclient }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/testing.md#L9-L58", "start_line": 9, "end_line": 58} {"id": "docs/en/docs/tutorial/testing.md::Separating tests { #separating-tests }::L59", "text": "# Doc: docs/en/docs/tutorial/testing.md | Page: Testing { #testing } | Section: Separating tests { #separating-tests }\n## Separating tests { #separating-tests }\n\nIn a real application, you probably would have your tests in a different file.\n\nAnd your **FastAPI** application might also be composed of several files/modules, etc.\n\n### **FastAPI** app file { #fastapi-app-file }\n\nLet's say you have a file structure as described in [Bigger Applications](bigger-applications.md):\n\n```\n.\n├── app\n│   ├── __init__.py\n│   └── main.py\n```\n\nIn the file `main.py` you have your **FastAPI** app:\n\n\n{* ../../docs_src/app_testing/app_a_py310/main.py *}\n\n### Testing file { #testing-file }\n\nThen you could have a file `test_main.py` with your tests. It could live on the same Python package (the same directory with a `__init__.py` file):\n\n``` hl_lines=\"5\"\n.\n├── app\n│   ├── __init__.py\n│   ├── main.py\n│   └── test_main.py\n```\n\nBecause this file is in the same package, you can use relative imports to import the object `app` from the `main` module (`main.py`):\n\n{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *}\n\n\n...and have the code for the tests just like before.", "source_type": "doc", "path": "docs/en/docs/tutorial/testing.md", "symbol": "Separating tests { #separating-tests }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/testing.md#L59-L99", "start_line": 59, "end_line": 99} {"id": "docs/en/docs/tutorial/testing.md::Testing: extended example { #testing-extended-example }::L100", "text": "# Doc: docs/en/docs/tutorial/testing.md | Page: Testing { #testing } | Section: Testing: extended example { #testing-extended-example }\n## Testing: extended example { #testing-extended-example }\n\nNow let's extend this example and add more details to see how to test different parts.\n\n### Extended **FastAPI** app file { #extended-fastapi-app-file }\n\nLet's continue with the same file structure as before:\n\n```\n.\n├── app\n│   ├── __init__.py\n│   ├── main.py\n│   └── test_main.py\n```\n\nLet's say that now the file `main.py` with your **FastAPI** app has some other **path operations**.\n\nIt has a `GET` operation that could return an error.\n\nIt has a `POST` operation that could return several errors.\n\nBoth *path operations* require an `X-Token` header.\n\n{* ../../docs_src/app_testing/app_b_an_py310/main.py *}\n\n### Extended testing file { #extended-testing-file }\n\nYou could then update `test_main.py` with the extended tests:\n\n{* ../../docs_src/app_testing/app_b_an_py310/test_main.py *}\n\n\nWhenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `httpx`, or even how to do it with `requests`, as HTTPX's design is based on Requests' design.\n\nThen you just do the same in your tests.\n\nE.g.:\n\n* To pass a *path* or *query* parameter, add it to the URL itself.\n* To pass a JSON body, pass a Python object (e.g. a `dict`) to the parameter `json`.\n* If you need to send *Form Data* instead of JSON, use the `data` parameter instead.\n* To pass *headers*, use a `dict` in the `headers` parameter.\n* For *cookies*, a `dict` in the `cookies` parameter.\n\nFor more information about how to pass data to the backend (using `httpx` or the `TestClient`) check the [HTTPX documentation](https://www.python-httpx.org).\n\n/// note\n\nNote that the `TestClient` receives data that can be converted to JSON, not Pydantic models.\n\nIf you have a Pydantic model in your test and you want to send its data to the application during testing, you can use the `jsonable_encoder` described in [JSON Compatible Encoder](encoder.md).\n\n///", "source_type": "doc", "path": "docs/en/docs/tutorial/testing.md", "symbol": "Testing: extended example { #testing-extended-example }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/testing.md#L100-L154", "start_line": 100, "end_line": 154} {"id": "docs/en/docs/tutorial/testing.md::Run it { #run-it }::L155", "text": "# Doc: docs/en/docs/tutorial/testing.md | Page: Testing { #testing } | Section: Run it { #run-it }\n## Run it { #run-it }\n\nAfter that, you just need to install `pytest`.\n\nMake sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:\n\n
\n\n```console\n$ pip install pytest\n\n---> 100%\n```\n\n
\n\nIt will detect the files and tests automatically, execute them, and report the results back to you.\n\nRun the tests with:\n\n
\n\n```console\n$ pytest\n\n================ test session starts ================\nplatform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1\nrootdir: /home/user/code/superawesome-cli/app\nplugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1\ncollected 6 items\n\n---> 100%\n\ntest_main.py ...... [100%]\n\n================= 1 passed in 0.03s =================\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/tutorial/testing.md", "symbol": "Run it { #run-it }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/tutorial/testing.md#L155-L193", "start_line": 155, "end_line": 193} {"id": "docs/en/docs/virtual-environments.md::Virtual Environments { #virtual-environments }::L1", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Virtual Environments { #virtual-environments }\n# Virtual Environments { #virtual-environments }\n\nWhen you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project.\n\n/// note\n\nIf you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓\n\n///\n\n/// tip\n\nA **virtual environment** is different than an **environment variable**.\n\nAn **environment variable** is a variable in the system that can be used by programs.\n\nA **virtual environment** is a directory with some files in it.\n\n///\n\n/// note\n\nThis page will teach you how to use **virtual environments** and how they work.\n\nIf you are ready to adopt a **tool that manages everything** for you (including installing Python), try [uv](https://github.com/astral-sh/uv).\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Virtual Environments { #virtual-environments }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L1-L28", "start_line": 1, "end_line": 28} {"id": "docs/en/docs/virtual-environments.md::Create a Project { #create-a-project }::L29", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Create a Project { #create-a-project }\n## Create a Project { #create-a-project }\n\nFirst, create a directory for your project.\n\nWhat I normally do is that I create a directory named `code` inside my home/user directory.\n\nAnd inside of that I create one directory per project.\n\n
\n\n```console\n// Go to the home directory\n$ cd\n// Create a directory for all your code projects\n$ mkdir code\n// Enter into that code directory\n$ cd code\n// Create a directory for this project\n$ mkdir awesome-project\n// Enter into that project directory\n$ cd awesome-project\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Create a Project { #create-a-project }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L29-L53", "start_line": 29, "end_line": 53} {"id": "docs/en/docs/virtual-environments.md::Create a Virtual Environment { #create-a-virtual-environment }::L54", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Create a Virtual Environment { #create-a-virtual-environment }\n## Create a Virtual Environment { #create-a-virtual-environment }\n\nWhen you start working on a Python project **for the first time**, create a virtual environment **inside your project**.\n\n/// tip\n\nYou only need to do this **once per project**, not every time you work.\n\n///\n\n//// tab | `venv`\n\nTo create a virtual environment, you can use the `venv` module that comes with Python.\n\n
\n\n```console\n$ python -m venv .venv\n```\n\n
\n\n/// details | What that command means\n\n* `python`: use the program called `python`\n* `-m`: call a module as a script, we'll tell it which module next\n* `venv`: use the module called `venv` that normally comes installed with Python\n* `.venv`: create the virtual environment in the new directory `.venv`\n\n///\n\n////\n\n//// tab | `uv`\n\nIf you have [`uv`](https://github.com/astral-sh/uv) installed, you can use it to create a virtual environment.\n\n
\n\n```console\n$ uv venv\n```\n\n
\n\n/// tip\n\nBy default, `uv` will create a virtual environment in a directory called `.venv`.\n\nBut you could customize it by passing an additional argument with the directory name.\n\n///\n\n////\n\nThat command creates a new virtual environment in a directory called `.venv`.\n\n/// details | `.venv` or other name\n\nYou could create the virtual environment in a different directory, but there's a convention of calling it `.venv`.\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Create a Virtual Environment { #create-a-virtual-environment }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L54-L116", "start_line": 54, "end_line": 116} {"id": "docs/en/docs/virtual-environments.md::Activate the Virtual Environment { #activate-the-virtual-environment }::L117", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Activate the Virtual Environment { #activate-the-virtual-environment }\n## Activate the Virtual Environment { #activate-the-virtual-environment }\n\nActivate the new virtual environment so that any Python command you run or package you install uses it.\n\n/// tip\n\nDo this **every time** you start a **new terminal session** to work on the project.\n\n///\n\n//// tab | Linux, macOS\n\n
\n\n```console\n$ source .venv/bin/activate\n```\n\n
\n\n////\n\n//// tab | Windows PowerShell\n\n
\n\n```console\n$ .venv\\Scripts\\Activate.ps1\n```\n\n
\n\n////\n\n//// tab | Windows Bash\n\nOr if you use Bash for Windows (e.g. [Git Bash](https://gitforwindows.org/)):\n\n
\n\n```console\n$ source .venv/Scripts/activate\n```\n\n
\n\n////\n\n/// tip\n\nEvery time you install a **new package** in that environment, **activate** the environment again.\n\nThis makes sure that if you use a **terminal (CLI) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need.\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Activate the Virtual Environment { #activate-the-virtual-environment }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L117-L172", "start_line": 117, "end_line": 172} {"id": "docs/en/docs/virtual-environments.md::Check the Virtual Environment is Active { #check-the-virtual-environment-is-active }::L173", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Check the Virtual Environment is Active { #check-the-virtual-environment-is-active }\n## Check the Virtual Environment is Active { #check-the-virtual-environment-is-active }\n\nCheck that the virtual environment is active (the previous command worked).\n\n/// tip\n\nThis is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended.\n\n///\n\n//// tab | Linux, macOS, Windows Bash\n\n
\n\n```console\n$ which python\n\n/home/user/code/awesome-project/.venv/bin/python\n```\n\n
\n\nIf it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉\n\n////\n\n//// tab | Windows PowerShell\n\n
\n\n```console\n$ Get-Command python\n\nC:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n```\n\n
\n\nIf it shows the `python` binary at `.venv\\Scripts\\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉\n\n////", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Check the Virtual Environment is Active { #check-the-virtual-environment-is-active }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L173-L214", "start_line": 173, "end_line": 214} {"id": "docs/en/docs/virtual-environments.md::Upgrade `pip` { #upgrade-pip }::L215", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Upgrade `pip` { #upgrade-pip }\n## Upgrade `pip` { #upgrade-pip }\n\n/// tip\n\nIf you use [`uv`](https://github.com/astral-sh/uv) you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎\n\n///\n\nIf you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version.\n\nMany exotic errors while installing a package are solved by just upgrading `pip` first.\n\n/// tip\n\nYou would normally do this **once**, right after you create the virtual environment.\n\n///\n\nMake sure the virtual environment is active (with the command above) and then run:\n\n
\n\n```console\n$ python -m pip install --upgrade pip\n\n---> 100%\n```\n\n
\n\n/// tip\n\nSometimes, you might get a **`No module named pip`** error when trying to upgrade pip.\n\nIf this happens, install and upgrade pip using the command below:\n\n
\n\n```console\n$ python -m ensurepip --upgrade\n\n---> 100%\n```\n\n
\n\nThis command will install pip if it is not already installed and also ensure that the installed version of pip is at least as recent as the one available in `ensurepip`.\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Upgrade `pip` { #upgrade-pip }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L215-L264", "start_line": 215, "end_line": 264} {"id": "docs/en/docs/virtual-environments.md::Add `.gitignore` { #add-gitignore }::L265", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Add `.gitignore` { #add-gitignore }\n## Add `.gitignore` { #add-gitignore }\n\nIf you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git.\n\n/// tip\n\nIf you used [`uv`](https://github.com/astral-sh/uv) to create the virtual environment, it already did this for you, you can skip this step. 😎\n\n///\n\n/// tip\n\nDo this **once**, right after you create the virtual environment.\n\n///\n\n
\n\n```console\n$ echo \"*\" > .venv/.gitignore\n```\n\n
\n\n/// details | What that command means\n\n* `echo \"*\"`: will \"print\" the text `*` in the terminal (the next part changes that a bit)\n* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>`\n* `.gitignore`: the name of the file where the text should be written\n\nAnd `*` for Git means \"everything\". So, it will ignore everything in the `.venv` directory.\n\nThat command will create a file `.gitignore` with the content:\n\n```gitignore\n*\n```\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Add `.gitignore` { #add-gitignore }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L265-L304", "start_line": 265, "end_line": 304} {"id": "docs/en/docs/virtual-environments.md::Install Packages { #install-packages }::L305", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Install Packages { #install-packages }\n## Install Packages { #install-packages }\n\nAfter activating the environment, you can install packages in it.\n\n/// tip\n\nDo this **once** when installing or upgrading the packages your project needs.\n\nIf you need to upgrade a version or add a new package you would **do this again**.\n\n///\n\n### Install Packages Directly { #install-packages-directly }\n\nIf you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly.\n\n/// tip\n\nIt's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`).\n\n///\n\n//// tab | `pip`\n\n
\n\n```console\n$ pip install \"fastapi[standard]\"\n\n---> 100%\n```\n\n
\n\n////\n\n//// tab | `uv`\n\nIf you have [`uv`](https://github.com/astral-sh/uv):\n\n
\n\n```console\n$ uv pip install \"fastapi[standard]\"\n---> 100%\n```\n\n
\n\n////\n\n### Install from `requirements.txt` { #install-from-requirements-txt }\n\nIf you have a `requirements.txt`, you can now use it to install its packages.\n\n//// tab | `pip`\n\n
\n\n```console\n$ pip install -r requirements.txt\n---> 100%\n```\n\n
\n\n////\n\n//// tab | `uv`\n\nIf you have [`uv`](https://github.com/astral-sh/uv):\n\n
\n\n```console\n$ uv pip install -r requirements.txt\n---> 100%\n```\n\n
\n\n////\n\n/// details | `requirements.txt`\n\nA `requirements.txt` with some packages could look like:\n\n```requirements.txt\nfastapi[standard]==0.113.0\npydantic==2.8.0\n```\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Install Packages { #install-packages }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L305-L398", "start_line": 305, "end_line": 398} {"id": "docs/en/docs/virtual-environments.md::Run Your Program { #run-your-program }::L399", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Run Your Program { #run-your-program }\n## Run Your Program { #run-your-program }\n\nAfter you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there.\n\n
\n\n```console\n$ python main.py\n\nHello World\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Run Your Program { #run-your-program }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L399-L412", "start_line": 399, "end_line": 412} {"id": "docs/en/docs/virtual-environments.md::Configure Your Editor { #configure-your-editor }::L413", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Configure Your Editor { #configure-your-editor }\n## Configure Your Editor { #configure-your-editor }\n\nYou would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors.\n\nFor example:\n\n* [VS Code](https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment)\n* [PyCharm](https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html)\n\n/// tip\n\nYou normally have to do this only **once**, when you create the virtual environment.\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Configure Your Editor { #configure-your-editor }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L413-L427", "start_line": 413, "end_line": 427} {"id": "docs/en/docs/virtual-environments.md::Deactivate the Virtual Environment { #deactivate-the-virtual-environment }::L428", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Deactivate the Virtual Environment { #deactivate-the-virtual-environment }\n## Deactivate the Virtual Environment { #deactivate-the-virtual-environment }\n\nOnce you are done working on your project you can **deactivate** the virtual environment.\n\n
\n\n```console\n$ deactivate\n```\n\n
\n\nThis way, when you run `python` it won't try to run it from that virtual environment with the packages installed there.", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Deactivate the Virtual Environment { #deactivate-the-virtual-environment }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L428-L441", "start_line": 428, "end_line": 441} {"id": "docs/en/docs/virtual-environments.md::Ready to Work { #ready-to-work }::L442", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Ready to Work { #ready-to-work }\n## Ready to Work { #ready-to-work }\n\nNow you're ready to start working on your project.\n\n\n\n/// tip\n\nDo you want to understand what all that above is?\n\nContinue reading. 👇🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Ready to Work { #ready-to-work }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L442-L455", "start_line": 442, "end_line": 455} {"id": "docs/en/docs/virtual-environments.md::Why Virtual Environments { #why-virtual-environments }::L456", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Why Virtual Environments { #why-virtual-environments }\n## Why Virtual Environments { #why-virtual-environments }\n\nTo work with FastAPI you need to install [Python](https://www.python.org/).\n\nAfter that, you would need to **install** FastAPI and any other **packages** you want to use.\n\nTo install packages you would normally use the `pip` command that comes with Python (or similar alternatives).\n\nNevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python).\n\n### The Problem { #the-problem }\n\nSo, what's the problem with installing packages in the global Python environment?\n\nAt some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱\n\nFor example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`.\n\n```mermaid\nflowchart LR\n stone(philosophers-stone) -->|requires| harry-1[harry v1]\n```\n\nThen, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**.\n\n```mermaid\nflowchart LR\n azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]\n```\n\nBut now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install.\n\nIf you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with:\n\n
\n\n```console\n$ pip install \"harry==1\"\n```\n\n
\n\nAnd then you would end up with `harry` version `1` installed in your global Python environment.\n\n```mermaid\nflowchart LR\n subgraph global[global env]\n harry-1[harry v1]\n end\n subgraph stone-project[philosophers-stone project]\n stone(philosophers-stone) -->|requires| harry-1\n end\n```\n\nBut then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`).\n\n
\n\n```console\n$ pip install \"harry==3\"\n```\n\n
\n\nAnd then you would end up with `harry` version `3` installed in your global Python environment.\n\nAnd if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`.\n\n```mermaid\nflowchart LR\n subgraph global[global env]\n harry-1[harry v1]\n style harry-1 fill:#ccc,stroke-dasharray: 5 5\n harry-3[harry v3]\n end\n subgraph stone-project[philosophers-stone project]\n stone(philosophers-stone) -.-x|⛔️| harry-1\n end\n subgraph azkaban-project[prisoner-of-azkaban project]\n azkaban(prisoner-of-azkaban) --> |requires| harry-3\n end\n```\n\n/// tip\n\nIt's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly.\n\n///\n\nNow, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working.\n\nAlso, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system.", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Why Virtual Environments { #why-virtual-environments }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L456-L548", "start_line": 456, "end_line": 548} {"id": "docs/en/docs/virtual-environments.md::Where are Packages Installed { #where-are-packages-installed }::L549", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Where are Packages Installed { #where-are-packages-installed }\n## Where are Packages Installed { #where-are-packages-installed }\n\nWhen you install Python, it creates some directories with some files on your computer.\n\nSome of these directories are the ones in charge of having all the packages you install.\n\nWhen you run:\n\n
\n\n```console\n// Don't run this now, it's just an example 🤓\n$ pip install \"fastapi[standard]\"\n---> 100%\n```\n\n
\n\nThat will download a compressed file with the FastAPI code, normally from [PyPI](https://pypi.org/project/fastapi/).\n\nIt will also **download** files for other packages that FastAPI depends on.\n\nThen it will **extract** all those files and put them in a directory on your computer.\n\nBy default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**.", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Where are Packages Installed { #where-are-packages-installed }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L549-L574", "start_line": 549, "end_line": 574} {"id": "docs/en/docs/virtual-environments.md::What are Virtual Environments { #what-are-virtual-environments }::L575", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: What are Virtual Environments { #what-are-virtual-environments }\n## What are Virtual Environments { #what-are-virtual-environments }\n\nThe solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on.\n\nA virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project.\n\nThis way, each project will have its own virtual environment (`.venv` directory) with its own packages.\n\n```mermaid\nflowchart TB\n subgraph stone-project[philosophers-stone project]\n stone(philosophers-stone) --->|requires| harry-1\n subgraph venv1[.venv]\n harry-1[harry v1]\n end\n end\n subgraph azkaban-project[prisoner-of-azkaban project]\n azkaban(prisoner-of-azkaban) --->|requires| harry-3\n subgraph venv2[.venv]\n harry-3[harry v3]\n end\n end\n stone-project ~~~ azkaban-project\n```", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "What are Virtual Environments { #what-are-virtual-environments }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L575-L599", "start_line": 575, "end_line": 599} {"id": "docs/en/docs/virtual-environments.md::What Does Activating a Virtual Environment Mean { #what-does-activating-a-virtual-environment-mean }::L600", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: What Does Activating a Virtual Environment Mean { #what-does-activating-a-virtual-environment-mean }\n## What Does Activating a Virtual Environment Mean { #what-does-activating-a-virtual-environment-mean }\n\nWhen you activate a virtual environment, for example with:\n\n//// tab | Linux, macOS\n\n
\n\n```console\n$ source .venv/bin/activate\n```\n\n
\n\n////\n\n//// tab | Windows PowerShell\n\n
\n\n```console\n$ .venv\\Scripts\\Activate.ps1\n```\n\n
\n\n////\n\n//// tab | Windows Bash\n\nOr if you use Bash for Windows (e.g. [Git Bash](https://gitforwindows.org/)):\n\n
\n\n```console\n$ source .venv/Scripts/activate\n```\n\n
\n\n////\n\nThat command will create or modify some [environment variables](environment-variables.md) that will be available for the next commands.\n\nOne of those variables is the `PATH` variable.\n\n/// tip\n\nYou can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable) section.\n\n///\n\nActivating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\\Scripts` (on Windows) to the `PATH` environment variable.\n\nLet's say that before activating the environment, the `PATH` variable looked like this:\n\n//// tab | Linux, macOS\n\n```plaintext\n/usr/bin:/bin:/usr/sbin:/sbin\n```\n\nThat means that the system would look for programs in:\n\n* `/usr/bin`\n* `/bin`\n* `/usr/sbin`\n* `/sbin`\n\n////\n\n//// tab | Windows\n\n```plaintext\nC:\\Windows\\System32\n```\n\nThat means that the system would look for programs in:\n\n* `C:\\Windows\\System32`\n\n////\n\nAfter activating the virtual environment, the `PATH` variable would look something like this:\n\n//// tab | Linux, macOS\n\n```plaintext\n/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin\n```\n\nThat means that the system will now start looking first for programs in:\n\n```plaintext\n/home/user/code/awesome-project/.venv/bin\n```\n\nbefore looking in the other directories.\n\nSo, when you type `python` in the terminal, the system will find the Python program in\n\n```plaintext\n/home/user/code/awesome-project/.venv/bin/python\n```\n\nand use that one.\n\n////\n\n//// tab | Windows\n\n```plaintext\nC:\\Users\\user\\code\\awesome-project\\.venv\\Scripts;C:\\Windows\\System32\n```\n\nThat means that the system will now start looking first for programs in:\n\n```plaintext\nC:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\n```\n\nbefore looking in the other directories.\n\nSo, when you type `python` in the terminal, the system will find the Python program in\n\n```plaintext\nC:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n```\n\nand use that one.\n\n////\n\nAn important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment).\n\nActivating a virtual environment also changes a couple of other things, but this is one of the most important things it does.", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "What Does Activating a Virtual Environment Mean { #what-does-activating-a-virtual-environment-mean }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L600-L736", "start_line": 600, "end_line": 736} {"id": "docs/en/docs/virtual-environments.md::Checking a Virtual Environment { #checking-a-virtual-environment }::L737", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Checking a Virtual Environment { #checking-a-virtual-environment }\n## Checking a Virtual Environment { #checking-a-virtual-environment }\n\nWhen you check if a virtual environment is active, for example with:\n\n//// tab | Linux, macOS, Windows Bash\n\n
\n\n```console\n$ which python\n\n/home/user/code/awesome-project/.venv/bin/python\n```\n\n
\n\n////\n\n//// tab | Windows PowerShell\n\n
\n\n```console\n$ Get-Command python\n\nC:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n```\n\n
\n\n////\n\nThat means that the `python` program that will be used is the one **in the virtual environment**.\n\nYou use `which` in Linux and macOS and `Get-Command` in Windows PowerShell.\n\nThe way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program.\n\nThe most important part is that when you call `python`, that is the exact \"`python`\" that will be executed.\n\nSo, you can confirm if you are in the correct virtual environment.\n\n/// tip\n\nIt's easy to activate one virtual environment, get one Python, and then **go to another project**.\n\nAnd the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project.\n\nIt's useful being able to check what `python` is being used. 🤓\n\n///", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Checking a Virtual Environment { #checking-a-virtual-environment }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L737-L788", "start_line": 737, "end_line": 788} {"id": "docs/en/docs/virtual-environments.md::Why Deactivate a Virtual Environment { #why-deactivate-a-virtual-environment }::L789", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Why Deactivate a Virtual Environment { #why-deactivate-a-virtual-environment }\n## Why Deactivate a Virtual Environment { #why-deactivate-a-virtual-environment }\n\nFor example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment.\n\nAnd then you want to work on **another project** `prisoner-of-azkaban`.\n\nYou go to that project:\n\n
\n\n```console\n$ cd ~/code/prisoner-of-azkaban\n```\n\n
\n\nIf you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`.\n\n
\n\n```console\n$ cd ~/code/prisoner-of-azkaban\n\n$ python main.py\n\n// Error importing sirius, it's not installed 😱\nTraceback (most recent call last):\n File \"main.py\", line 1, in \n import sirius\n```\n\n
\n\nBut if you deactivate the virtual environment and activate the new one for `prisoner-of-azkaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`.\n\n
\n\n```console\n$ cd ~/code/prisoner-of-azkaban\n\n// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎\n$ deactivate\n\n// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀\n$ source .venv/bin/activate\n\n// Now when you run python, it will find the package sirius installed in this virtual environment ✨\n$ python main.py\n\nI solemnly swear 🐺\n```\n\n
", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Why Deactivate a Virtual Environment { #why-deactivate-a-virtual-environment }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L789-L842", "start_line": 789, "end_line": 842} {"id": "docs/en/docs/virtual-environments.md::Alternatives { #alternatives }::L843", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Alternatives { #alternatives }\n## Alternatives { #alternatives }\n\nThis is a simple guide to get you started and teach you how everything works **underneath**.\n\nThere are many **alternatives** to managing virtual environments, package dependencies (requirements), projects.\n\nOnce you are ready and want to use a tool to **manage the entire project**, package dependencies, virtual environments, etc. I would suggest you try [uv](https://github.com/astral-sh/uv).\n\n`uv` can do a lot of things, it can:\n\n* **Install Python** for you, including different versions\n* Manage the **virtual environment** for your projects\n* Install **packages**\n* Manage package **dependencies and versions** for your project\n* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking**\n* And many other things", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Alternatives { #alternatives }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L843-L859", "start_line": 843, "end_line": 859} {"id": "docs/en/docs/virtual-environments.md::Conclusion { #conclusion }::L860", "text": "# Doc: docs/en/docs/virtual-environments.md | Page: Virtual Environments { #virtual-environments } | Section: Conclusion { #conclusion }\n## Conclusion { #conclusion }\n\nIf you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓\n\nKnowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎", "source_type": "doc", "path": "docs/en/docs/virtual-environments.md", "symbol": "Conclusion { #conclusion }", "url": "https://github.com/fastapi/fastapi/blob/master/docs/en/docs/virtual-environments.md#L860-L864", "start_line": 860, "end_line": 864} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::FastAPI::L1", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: FastAPI\n---\nname: fastapi\ndescription: FastAPI best practices and conventions. Use when working with FastAPI APIs, Pydantic models, dependencies, streaming responses including Server-Sent Events (SSE), and serving frontend apps. Keeps FastAPI code clean and up to date with the latest features and patterns.\n---\n\n# FastAPI\n\nOfficial FastAPI skill to write code with best practices, keeping up to date with new versions and features.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "FastAPI", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L1-L9", "start_line": 1, "end_line": 9} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Quick Reference::L10", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Quick Reference\n## Quick Reference\n\n* Serve frontend apps: use `app.frontend()` or `router.frontend()` for built frontend assets; see [Serve Frontend Apps](#serve-frontend-apps).\n* Server-Sent Events (SSE): use `response_class=EventSourceResponse` and `yield`; see [Streaming](#streaming-json-lines-sse-bytes) and [the streaming reference](references/streaming.md).\n* JSON Lines and byte streaming: see [the streaming reference](references/streaming.md).\n* Dependencies: use `Annotated[..., Depends(...)]`; see [Dependency Injection](#dependency-injection) and [the dependency injection reference](references/dependencies.md) for `yield`, scopes, and class dependencies.\n* Response models: prefer return types; use `response_model` when the public response schema differs from the internal return value; see [the response reference](references/responses.md).\n* Pydantic models: do not use ellipsis or `RootModel`; see [the Pydantic reference](references/pydantic.md).\n* Routing: declare router-level prefix, tags, and shared dependencies on the `APIRouter`; see [the path operation reference](references/path-operations.md).\n* Tooling and related libraries: use uv, Ruff, ty, Asyncer, SQLModel, and HTTPX when applicable; see [the other tools reference](references/other-tools.md).", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Quick Reference", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L10-L20", "start_line": 10, "end_line": 20} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Use the `fastapi` CLI::L21", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Use the `fastapi` CLI\n## Use the `fastapi` CLI\n\nRun the development server on localhost with reload:\n\n```bash\nfastapi dev\n```\n\nRun the production server:\n\n```bash\nfastapi run\n```\n\nPrefer declaring the entrypoint in `pyproject.toml`:\n\n```toml\n[tool.fastapi]\nentrypoint = \"my_app.main:app\"\n```\n\nWhen adding the entrypoint is not possible, or the user explicitly asks not to, pass the app file path:\n\n```bash\nfastapi dev my_app/main.py\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Use the `fastapi` CLI", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L21-L47", "start_line": 21, "end_line": 47} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Use `Annotated`::L48", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Use `Annotated`\n## Use `Annotated`\n\nAlways prefer the `Annotated` style for parameter and dependency declarations. It keeps function signatures working in other contexts, respects the types, and allows reusability.\n\nUse `Annotated` for parameter declarations, including `Path`, `Query`, `Header`, etc.:\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import FastAPI, Path, Query\n\napp = FastAPI()\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(\n item_id: Annotated[int, Path(ge=1, description=\"The item ID\")],\n q: Annotated[str | None, Query(max_length=50)] = None,\n):\n return {\"message\": \"Hello World\"}\n```\n\nUse `Annotated` for dependencies with `Depends()`. Unless asked not to, create a new type alias for the dependency to allow reusing it:\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\ndef get_current_user():\n return {\"username\": \"johndoe\"}\n\n\nCurrentUserDep = Annotated[dict, Depends(get_current_user)]\n\n\n@app.get(\"/items/\")\nasync def read_item(current_user: CurrentUserDep):\n return {\"message\": \"Hello World\"}\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Use `Annotated`", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L48-L91", "start_line": 48, "end_line": 91} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Do not use Ellipsis for *path operations* or Pydantic models::L92", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Do not use Ellipsis for *path operations* or Pydantic models\n## Do not use Ellipsis for *path operations* or Pydantic models\n\nDo not use `...` as a default value for required parameters or model fields. It's not needed and not recommended.\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import FastAPI, Query\nfrom pydantic import BaseModel, Field\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float = Field(gt=0)\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, project_id: Annotated[int, Query()]):\n return item\n```\n\nSee [the Pydantic reference](references/pydantic.md) for more details.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Do not use Ellipsis for *path operations* or Pydantic models", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L92-L117", "start_line": 92, "end_line": 117} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Return Type or Response Model::L118", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Return Type or Response Model\n## Return Type or Response Model\n\nWhen possible, include a return type. It will be used to validate, filter, document, and serialize the response.\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n\n@app.get(\"/items/me\")\nasync def get_item() -> Item:\n return Item(name=\"Plumbus\", description=\"All-purpose home device\")\n```\n\nReturn types or response models filter data to avoid exposing sensitive information, and they let Pydantic serialize the data on the Rust side for performance.\n\nUse `response_model` when the type you return is not the same as the public schema you want to validate, filter, document, and serialize. See [the response reference](references/responses.md).", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Return Type or Response Model", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L118-L142", "start_line": 118, "end_line": 142} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Performance::L143", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Performance\n## Performance\n\nDo not use `ORJSONResponse` or `UJSONResponse`, they are deprecated.\n\nInstead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Performance", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L143-L148", "start_line": 143, "end_line": 148} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Including Routers::L149", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Including Routers\n## Including Routers\n\nWhen declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in `include_router()`.\n\n```python\nfrom fastapi import APIRouter, Depends, FastAPI\n\napp = FastAPI()\n\n\ndef get_current_user():\n return {\"username\": \"johndoe\"}\n\n\nrouter = APIRouter(\n prefix=\"/items\",\n tags=[\"items\"],\n dependencies=[Depends(get_current_user)],\n)\n\n\n@router.get(\"/\")\nasync def list_items():\n return []\n\n\napp.include_router(router)\n```\n\nSee [the path operation reference](references/path-operations.md) for more routing patterns.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Including Routers", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L149-L179", "start_line": 149, "end_line": 179} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Serve Frontend Apps::L180", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Serve Frontend Apps\n## Serve Frontend Apps\n\nUse `app.frontend()` to serve a built static frontend app, for example a directory generated by Vite, Astro, Angular, Svelte, Vue, or a similar tool.\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\napp.frontend(\"/\", directory=\"dist\")\n```\n\nUse `router.frontend()` when the frontend belongs to an `APIRouter`; normal router prefix behavior applies when the router is included.\n\n```python\nfrom fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter(prefix=\"/admin\")\n\nrouter.frontend(\"/\", directory=\"admin-dist\")\napp.include_router(router)\n```\n\n`app.frontend()` and `router.frontend()` are low-priority routes: regular API routes are matched first, then frontend files and client-side routing fallbacks. Use this for single-page apps and built frontend assets instead of mounting `StaticFiles` manually.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Serve Frontend Apps", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L180-L205", "start_line": 180, "end_line": 205} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Dependency Injection::L206", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Dependency Injection\n## Dependency Injection\n\nUse dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup with `yield`, or is shared across endpoints.\n\nApply shared dependencies at the router level via `dependencies=[Depends(...)]`.\n\nSee [the dependency injection reference](references/dependencies.md) for detailed patterns including `yield` with `scope`, and class dependencies.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Dependency Injection", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L206-L213", "start_line": 206, "end_line": 213} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Async vs Sync *path operations*::L214", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Async vs Sync *path operations*\n## Async vs Sync *path operations*\n\nUse `async` *path operations* only when fully certain that the logic called inside is compatible with async and await, and that it doesn't block.\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/async-items/\")\nasync def read_async_items():\n data = await some_async_library.fetch_items()\n return data\n\n\n@app.get(\"/items/\")\ndef read_items():\n data = some_blocking_library.fetch_items()\n return data\n```\n\nIn case of doubt, or by default, use regular `def` functions. They will be run in a threadpool so they don't block the event loop. The same rules apply to dependencies.\n\nMake sure blocking code is not run inside of `async` functions. The logic will work, but will damage performance heavily.\n\nWhen needing to mix blocking and async code, see Asyncer in [the other tools reference](references/other-tools.md).", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Async vs Sync *path operations*", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L214-L241", "start_line": 214, "end_line": 241} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Streaming (JSON Lines, SSE, bytes)::L242", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Streaming (JSON Lines, SSE, bytes)\n## Streaming (JSON Lines, SSE, bytes)\n\nTo stream Server-Sent Events, use `response_class=EventSourceResponse` and `yield` items from the endpoint.\n\n```python\nfrom collections.abc import AsyncIterable\n\nfrom fastapi import FastAPI\nfrom fastapi.sse import EventSourceResponse, ServerSentEvent\n\napp = FastAPI()\n\n\n@app.get(\"/events\", response_class=EventSourceResponse)\nasync def stream_events() -> AsyncIterable[ServerSentEvent]:\n yield ServerSentEvent(data={\"status\": \"started\"}, event=\"status\", id=\"1\")\n```\n\nPlain objects are automatically JSON-serialized as `data:` fields. Use `ServerSentEvent` for full control over SSE fields (`event`, `id`, `retry`, `comment`) and `raw_data` for pre-formatted strings.\n\nSee [the streaming reference](references/streaming.md) for JSON Lines, Server-Sent Events (`EventSourceResponse`, `ServerSentEvent`), and byte streaming (`StreamingResponse`) patterns.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Streaming (JSON Lines, SSE, bytes)", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L242-L263", "start_line": 242, "end_line": 263} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Tooling::L264", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Tooling\n## Tooling\n\nSee [the other tools reference](references/other-tools.md) for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Tooling", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L264-L267", "start_line": 264, "end_line": 267} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Other Libraries::L268", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Other Libraries\n## Other Libraries\n\nSee [the other tools reference](references/other-tools.md) for details on other libraries:\n\n* Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio.\n* SQLModel for working with SQL databases, prefer it over SQLAlchemy.\n* HTTPX for interacting with HTTP (other APIs), prefer it over Requests.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Other Libraries", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L268-L275", "start_line": 268, "end_line": 275} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Do not use Pydantic RootModels::L276", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Do not use Pydantic RootModels\n## Do not use Pydantic RootModels\n\nDo not use Pydantic `RootModel`; instead use regular type annotations with `Annotated` and Pydantic validation utilities.\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Body, FastAPI\nfrom pydantic import Field\n\napp = FastAPI()\n\n\n@app.post(\"/items/\")\nasync def create_items(items: Annotated[list[int], Field(min_length=1), Body()]):\n return items\n```\n\nFastAPI supports these type annotations and will create a Pydantic `TypeAdapter` for them, so types work normally without custom wrapper models. See [the Pydantic reference](references/pydantic.md).", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Do not use Pydantic RootModels", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L276-L295", "start_line": 276, "end_line": 295} {"id": "fastapi/.agents/skills/fastapi/SKILL.md::Use one HTTP operation per function::L296", "text": "# Doc: fastapi/.agents/skills/fastapi/SKILL.md | Page: FastAPI | Section: Use one HTTP operation per function\n## Use one HTTP operation per function\n\nDon't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code.\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n\n\n@app.get(\"/items/\")\nasync def list_items():\n return []\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item):\n return item\n```\n\nSee [the path operation reference](references/path-operations.md) for more examples.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/SKILL.md", "symbol": "Use one HTTP operation per function", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/SKILL.md#L296-L321", "start_line": 296, "end_line": 321} {"id": "fastapi/.agents/skills/fastapi/references/dependencies.md::Dependency Injection::L1", "text": "# Doc: fastapi/.agents/skills/fastapi/references/dependencies.md | Page: Dependency Injection | Section: Dependency Injection\n# Dependency Injection\n\nUse dependencies when:\n\n* They can't be declared in Pydantic validation and require additional logic\n* The logic depends on external resources or could block in any other way\n* Other dependencies need their results (it's a sub-dependency)\n* The logic can be shared by multiple endpoints to do things like error early, handle authentication, etc.\n* They need to handle cleanup (e.g., DB sessions, file handles), using dependencies with `yield`\n* Their logic needs input data from the request, like headers, query parameters, etc.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/dependencies.md", "symbol": "Dependency Injection", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/dependencies.md#L1-L11", "start_line": 1, "end_line": 11} {"id": "fastapi/.agents/skills/fastapi/references/dependencies.md::Dependencies with `yield` and `scope`::L12", "text": "# Doc: fastapi/.agents/skills/fastapi/references/dependencies.md | Page: Dependency Injection | Section: Dependencies with `yield` and `scope`\n## Dependencies with `yield` and `scope`\n\nWhen using dependencies with `yield`, they can have a `scope` that defines when the exit code is run.\n\nUse the default scope `\"request\"` to run the exit code after the response is sent back.\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\ndef get_db():\n db = DBSession()\n try:\n yield db\n finally:\n db.close()\n\n\nDBDep = Annotated[DBSession, Depends(get_db)]\n\n\n@app.get(\"/items/\")\nasync def read_items(db: DBDep):\n return db.query(Item).all()\n```\n\nUse the scope `\"function\"` when they should run the exit code after the response data is generated but before the response is sent back to the client.\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\ndef get_username():\n try:\n yield \"Rick\"\n finally:\n print(\"Clean up before response is sent\")\n\nUserNameDep = Annotated[str, Depends(get_username, scope=\"function\")]\n\n@app.get(\"/users/me\")\ndef get_user_me(username: UserNameDep):\n return username\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/dependencies.md", "symbol": "Dependencies with `yield` and `scope`", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/dependencies.md#L12-L64", "start_line": 12, "end_line": 64} {"id": "fastapi/.agents/skills/fastapi/references/dependencies.md::Class Dependencies::L65", "text": "# Doc: fastapi/.agents/skills/fastapi/references/dependencies.md | Page: Dependency Injection | Section: Class Dependencies\n## Class Dependencies\n\nAvoid creating class dependencies when possible.\n\nIf a class is needed, instead create a regular function dependency that returns a class instance.\n\nDo this:\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\n@dataclass\nclass DatabasePaginator:\n offset: int = 0\n limit: int = 100\n q: str | None = None\n\n def get_page(self) -> dict:\n # Simulate a page of data\n return {\n \"offset\": self.offset,\n \"limit\": self.limit,\n \"q\": self.q,\n \"items\": [],\n }\n\n\ndef get_db_paginator(\n offset: int = 0, limit: int = 100, q: str | None = None\n) -> DatabasePaginator:\n return DatabasePaginator(offset=offset, limit=limit, q=q)\n\n\nPaginatorDep = Annotated[DatabasePaginator, Depends(get_db_paginator)]\n\n\n@app.get(\"/items/\")\nasync def read_items(paginator: PaginatorDep):\n return paginator.get_page()\n```\n\ninstead of this:\n\n```python\n# DO NOT DO THIS\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\nclass DatabasePaginator:\n def __init__(self, offset: int = 0, limit: int = 100, q: str | None = None):\n self.offset = offset\n self.limit = limit\n self.q = q\n\n def get_page(self) -> dict:\n # Simulate a page of data\n return {\n \"offset\": self.offset,\n \"limit\": self.limit,\n \"q\": self.q,\n \"items\": [],\n }\n\n\n@app.get(\"/items/\")\nasync def read_items(paginator: Annotated[DatabasePaginator, Depends()]):\n return paginator.get_page()\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/dependencies.md", "symbol": "Class Dependencies", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/dependencies.md#L65-L142", "start_line": 65, "end_line": 142} {"id": "fastapi/.agents/skills/fastapi/references/other-tools.md::uv::L3", "text": "# Doc: fastapi/.agents/skills/fastapi/references/other-tools.md | Page: Other Tools | Section: uv\n## uv\n\nIf uv is available, use it to manage dependencies.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/other-tools.md", "symbol": "uv", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/other-tools.md#L3-L6", "start_line": 3, "end_line": 6} {"id": "fastapi/.agents/skills/fastapi/references/other-tools.md::Ruff::L7", "text": "# Doc: fastapi/.agents/skills/fastapi/references/other-tools.md | Page: Other Tools | Section: Ruff\n## Ruff\n\nIf Ruff is available, use it to lint and format the code. Consider enabling the FastAPI rules.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/other-tools.md", "symbol": "Ruff", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/other-tools.md#L7-L10", "start_line": 7, "end_line": 10} {"id": "fastapi/.agents/skills/fastapi/references/other-tools.md::Asyncer::L15", "text": "# Doc: fastapi/.agents/skills/fastapi/references/other-tools.md | Page: Other Tools | Section: Asyncer\n## Asyncer\n\nWhen needing to run blocking code inside of async functions, or async code inside of blocking functions, suggest using Asyncer.\n\nPrefer it over AnyIO or asyncio.\n\nInstall:\n\n```bash\nuv add asyncer\n```\n\nRun blocking sync code inside of async with `asyncify()`:\n\n```python\nfrom asyncer import asyncify\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\ndef do_blocking_work(name: str) -> str:\n # Some blocking I/O operation\n return f\"Hello {name}\"\n\n\n@app.get(\"/items/\")\nasync def read_items():\n result = await asyncify(do_blocking_work)(name=\"World\")\n return {\"message\": result}\n```\n\nAnd run async code inside of blocking sync code with `syncify()`:\n\n```python\nfrom asyncer import syncify\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\nasync def do_async_work(name: str) -> str:\n return f\"Hello {name}\"\n\n\n@app.get(\"/items/\")\ndef read_items():\n result = syncify(do_async_work)(name=\"World\")\n return {\"message\": result}\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/other-tools.md", "symbol": "Asyncer", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/other-tools.md#L15-L65", "start_line": 15, "end_line": 65} {"id": "fastapi/.agents/skills/fastapi/references/other-tools.md::SQLModel for SQL databases::L66", "text": "# Doc: fastapi/.agents/skills/fastapi/references/other-tools.md | Page: Other Tools | Section: SQLModel for SQL databases\n## SQLModel for SQL databases\n\nWhen working with SQL databases, prefer using SQLModel as it is integrated with Pydantic and will allow declaring data validation with the same models.\n\nPrefer it over SQLAlchemy.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/other-tools.md", "symbol": "SQLModel for SQL databases", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/other-tools.md#L66-L71", "start_line": 66, "end_line": 71} {"id": "fastapi/.agents/skills/fastapi/references/other-tools.md::HTTPX::L72", "text": "# Doc: fastapi/.agents/skills/fastapi/references/other-tools.md | Page: Other Tools | Section: HTTPX\n## HTTPX\n\nUse HTTPX for handling HTTP communication (e.g. with other APIs). It supports sync and async usage.\n\nPrefer it over Requests.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/other-tools.md", "symbol": "HTTPX", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/other-tools.md#L72-L76", "start_line": 72, "end_line": 76} {"id": "fastapi/.agents/skills/fastapi/references/path-operations.md::Including Routers::L3", "text": "# Doc: fastapi/.agents/skills/fastapi/references/path-operations.md | Page: Path Operations and Routing | Section: Including Routers\n## Including Routers\n\nWhen declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in `include_router()`.\n\nDo this:\n\n```python\nfrom fastapi import APIRouter, FastAPI\n\napp = FastAPI()\n\nrouter = APIRouter(prefix=\"/items\", tags=[\"items\"])\n\n\n@router.get(\"/\")\nasync def list_items():\n return []\n\n\napp.include_router(router)\n```\n\nInstead of:\n\n```python\n# DO NOT DO THIS\nfrom fastapi import APIRouter, FastAPI\n\napp = FastAPI()\n\nrouter = APIRouter()\n\n\n@router.get(\"/\")\nasync def list_items():\n return []\n\n\napp.include_router(router, prefix=\"/items\", tags=[\"items\"])\n```\n\nThere could be exceptions, but try to follow this convention.\n\nApply shared dependencies at the router level via `dependencies=[Depends(...)]`.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/path-operations.md", "symbol": "Including Routers", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/path-operations.md#L3-L47", "start_line": 3, "end_line": 47} {"id": "fastapi/.agents/skills/fastapi/references/path-operations.md::Use one HTTP operation per function::L48", "text": "# Doc: fastapi/.agents/skills/fastapi/references/path-operations.md | Page: Path Operations and Routing | Section: Use one HTTP operation per function\n## Use one HTTP operation per function\n\nDon't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code.\n\nDo this:\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n\n\n@app.get(\"/items/\")\nasync def list_items():\n return []\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item):\n return item\n```\n\nInstead of:\n\n```python\n# DO NOT DO THIS\nfrom fastapi import FastAPI, Request\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n\n\n@app.api_route(\"/items/\", methods=[\"GET\", \"POST\"])\nasync def handle_items(request: Request):\n if request.method == \"GET\":\n return []\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/path-operations.md", "symbol": "Use one HTTP operation per function", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/path-operations.md#L48-L93", "start_line": 48, "end_line": 93} {"id": "fastapi/.agents/skills/fastapi/references/pydantic.md::Do not use Ellipsis::L3", "text": "# Doc: fastapi/.agents/skills/fastapi/references/pydantic.md | Page: Pydantic | Section: Do not use Ellipsis\n## Do not use Ellipsis\n\nDo not use `...` as a default value for required parameters or model fields. It's not needed and not recommended.\n\nDo this, without Ellipsis (`...`):\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import FastAPI, Query\nfrom pydantic import BaseModel, Field\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float = Field(gt=0)\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, project_id: Annotated[int, Query()]):\n return item\n```\n\nInstead of:\n\n```python\n# DO NOT DO THIS\nfrom typing import Annotated\n\nfrom fastapi import FastAPI, Query\nfrom pydantic import BaseModel, Field\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str = ...\n description: str | None = None\n price: float = Field(..., gt=0)\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, project_id: Annotated[int, Query(...)]):\n return item\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/pydantic.md", "symbol": "Do not use Ellipsis", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/pydantic.md#L3-L51", "start_line": 3, "end_line": 51} {"id": "fastapi/.agents/skills/fastapi/references/pydantic.md::Do not use Pydantic RootModels::L52", "text": "# Doc: fastapi/.agents/skills/fastapi/references/pydantic.md | Page: Pydantic | Section: Do not use Pydantic RootModels\n## Do not use Pydantic RootModels\n\nDo not use Pydantic `RootModel`; instead use regular type annotations with `Annotated` and Pydantic validation utilities.\n\nFor example, for a list with validations:\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Body, FastAPI\nfrom pydantic import Field\n\napp = FastAPI()\n\n\n@app.post(\"/items/\")\nasync def create_items(items: Annotated[list[int], Field(min_length=1), Body()]):\n return items\n```\n\nInstead of:\n\n```python\n# DO NOT DO THIS\nfrom typing import Annotated\n\nfrom fastapi import FastAPI\nfrom pydantic import Field, RootModel\n\napp = FastAPI()\n\n\nclass ItemList(RootModel[Annotated[list[int], Field(min_length=1)]]):\n pass\n\n\n@app.post(\"/items/\")\nasync def create_items(items: ItemList):\n return items\n```\n\nFastAPI supports these type annotations and will create a Pydantic `TypeAdapter` for them, so types work normally without custom wrapper models.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/pydantic.md", "symbol": "Do not use Pydantic RootModels", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/pydantic.md#L52-L93", "start_line": 52, "end_line": 93} {"id": "fastapi/.agents/skills/fastapi/references/responses.md::Return Type or Response Model::L3", "text": "# Doc: fastapi/.agents/skills/fastapi/references/responses.md | Page: Responses | Section: Return Type or Response Model\n## Return Type or Response Model\n\nWhen possible, include a return type. It will be used to validate, filter, document, and serialize the response.\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n\n@app.get(\"/items/me\")\nasync def get_item() -> Item:\n return Item(name=\"Plumbus\", description=\"All-purpose home device\")\n```\n\nReturn types or response models filter data to avoid exposing sensitive information. They also let Pydantic serialize data on the Rust side for performance.\n\nThe return type doesn't have to be a Pydantic model. It can be a different type, like a list of integers, a dict, etc.", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/responses.md", "symbol": "Return Type or Response Model", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/responses.md#L3-L27", "start_line": 3, "end_line": 27} {"id": "fastapi/.agents/skills/fastapi/references/responses.md::When to use `response_model`::L28", "text": "# Doc: fastapi/.agents/skills/fastapi/references/responses.md | Page: Responses | Section: When to use `response_model`\n## When to use `response_model`\n\nIf the return type is not the same as the type that you want to use to validate, filter, or serialize, use the `response_model` parameter on the decorator.\n\n```python\nfrom typing import Any\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n\n@app.get(\"/items/me\", response_model=Item)\nasync def get_item() -> Any:\n return {\"name\": \"Foo\", \"description\": \"A very nice Item\"}\n```\n\nThis is particularly useful when filtering data to expose only the public fields and avoid exposing sensitive information.\n\n```python\nfrom typing import Any\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass InternalItem(BaseModel):\n name: str\n description: str | None = None\n secret_key: str\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n\n\n@app.get(\"/items/me\", response_model=Item)\nasync def get_item() -> Any:\n item = InternalItem(\n name=\"Foo\", description=\"A very nice Item\", secret_key=\"supersecret\"\n )\n return item\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/responses.md", "symbol": "When to use `response_model`", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/responses.md#L28-L79", "start_line": 28, "end_line": 79} {"id": "fastapi/.agents/skills/fastapi/references/streaming.md::Stream JSON Lines::L3", "text": "# Doc: fastapi/.agents/skills/fastapi/references/streaming.md | Page: Streaming | Section: Stream JSON Lines\n## Stream JSON Lines\n\nTo stream JSON Lines, declare the return type and use `yield` to return the data.\n\n```python\n@app.get(\"/items/stream\")\nasync def stream_items() -> AsyncIterable[Item]:\n for item in items:\n yield item\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/streaming.md", "symbol": "Stream JSON Lines", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/streaming.md#L3-L13", "start_line": 3, "end_line": 13} {"id": "fastapi/.agents/skills/fastapi/references/streaming.md::Server-Sent Events (SSE)::L14", "text": "# Doc: fastapi/.agents/skills/fastapi/references/streaming.md | Page: Streaming | Section: Server-Sent Events (SSE)\n## Server-Sent Events (SSE)\n\nTo stream Server-Sent Events, use `response_class=EventSourceResponse` and `yield` items from the endpoint.\n\nPlain objects are automatically JSON-serialized as `data:` fields, declare the return type so the serialization is done by Pydantic:\n\n```python\nfrom collections.abc import AsyncIterable\n\nfrom fastapi import FastAPI\nfrom fastapi.sse import EventSourceResponse\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n price: float\n\n\n@app.get(\"/items/stream\", response_class=EventSourceResponse)\nasync def stream_items() -> AsyncIterable[Item]:\n yield Item(name=\"Plumbus\", price=32.99)\n yield Item(name=\"Portal Gun\", price=999.99)\n```\n\nFor full control over SSE fields (`event`, `id`, `retry`, `comment`), yield `ServerSentEvent` instances:\n\n```python\nfrom collections.abc import AsyncIterable\n\nfrom fastapi import FastAPI\nfrom fastapi.sse import EventSourceResponse, ServerSentEvent\n\napp = FastAPI()\n\n\n@app.get(\"/events\", response_class=EventSourceResponse)\nasync def stream_events() -> AsyncIterable[ServerSentEvent]:\n yield ServerSentEvent(data={\"status\": \"started\"}, event=\"status\", id=\"1\")\n yield ServerSentEvent(data={\"progress\": 50}, event=\"progress\", id=\"2\")\n```\n\nUse `raw_data` instead of `data` to send pre-formatted strings without JSON encoding:\n\n```python\nyield ServerSentEvent(raw_data=\"plain text line\", event=\"log\")\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/streaming.md", "symbol": "Server-Sent Events (SSE)", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/streaming.md#L14-L63", "start_line": 14, "end_line": 63} {"id": "fastapi/.agents/skills/fastapi/references/streaming.md::Stream bytes::L64", "text": "# Doc: fastapi/.agents/skills/fastapi/references/streaming.md | Page: Streaming | Section: Stream bytes\n## Stream bytes\n\nTo stream bytes, declare a `response_class=` of `StreamingResponse` or a sub-class, and use `yield` to return the data.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.responses import StreamingResponse\nfrom app.utils import read_image\n\napp = FastAPI()\n\n\nclass PNGStreamingResponse(StreamingResponse):\n media_type = \"image/png\"\n\n@app.get(\"/image\", response_class=PNGStreamingResponse)\ndef stream_image_no_async_no_annotation():\n with read_image() as image_file:\n yield from image_file\n```\n\nprefer this over returning a `StreamingResponse` directly:\n\n```python\n# DO NOT DO THIS\n\nimport anyio\nfrom fastapi import FastAPI\nfrom fastapi.responses import StreamingResponse\nfrom app.utils import read_image\n\napp = FastAPI()\n\n\nclass PNGStreamingResponse(StreamingResponse):\n media_type = \"image/png\"\n\n\n@app.get(\"/\")\nasync def main():\n return PNGStreamingResponse(read_image())\n```", "source_type": "doc", "path": "fastapi/.agents/skills/fastapi/references/streaming.md", "symbol": "Stream bytes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/.agents/skills/fastapi/references/streaming.md#L64-L105", "start_line": 64, "end_line": 105} {"id": "fastapi/__init__.py::", "text": "# File: fastapi/__init__.py | Symbol: \n\"\"\"FastAPI framework, high performance, easy to learn, fast to code, ready for production\"\"\"\n__version__ = \"0.139.0\"\nfrom starlette import status as status\nfrom .applications import FastAPI as FastAPI\nfrom .background import BackgroundTasks as BackgroundTasks\nfrom .datastructures import UploadFile as UploadFile\nfrom .exceptions import HTTPException as HTTPException\nfrom .exceptions import WebSocketException as WebSocketException\nfrom .param_functions import Body as Body\nfrom .param_functions import Cookie as Cookie\nfrom .param_functions import Depends as Depends\nfrom .param_functions import File as File\nfrom .param_functions import Form as Form\nfrom .param_functions import Header as Header\nfrom .param_functions import Path as Path\nfrom .param_functions import Query as Query\nfrom .param_functions import Security as Security\nfrom .requests import Request as Request\nfrom .responses import Response as Response\nfrom .routing import APIRouter as APIRouter\nfrom .websockets import WebSocket as WebSocket\nfrom .websockets import WebSocketDisconnect as WebSocketDisconnect", "source_type": "code", "path": "fastapi/__init__.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/__init__.py#L1-L25", "start_line": 1, "end_line": 25} {"id": "fastapi/_compat/__init__.py::", "text": "# File: fastapi/_compat/__init__.py | Symbol: \nfrom .shared import PYDANTIC_VERSION_MINOR_TUPLE as PYDANTIC_VERSION_MINOR_TUPLE\nfrom .shared import annotation_is_pydantic_v1 as annotation_is_pydantic_v1\nfrom .shared import field_annotation_is_scalar as field_annotation_is_scalar\nfrom .shared import (\n field_annotation_is_scalar_sequence as field_annotation_is_scalar_sequence,\n)\nfrom .shared import field_annotation_is_sequence as field_annotation_is_sequence\nfrom .shared import (\n is_bytes_or_nonable_bytes_annotation as is_bytes_or_nonable_bytes_annotation,\n)\nfrom .shared import is_bytes_sequence_annotation as is_bytes_sequence_annotation\nfrom .shared import is_pydantic_v1_model_instance as is_pydantic_v1_model_instance\nfrom .shared import (\n is_uploadfile_or_nonable_uploadfile_annotation as is_uploadfile_or_nonable_uploadfile_annotation,\n)\nfrom .shared import (\n is_uploadfile_sequence_annotation as is_uploadfile_sequence_annotation,\n)\nfrom .shared import lenient_issubclass as lenient_issubclass\nfrom .shared import sequence_types as sequence_types\nfrom .shared import value_is_sequence as value_is_sequence\nfrom .v2 import ModelField as ModelField\nfrom .v2 import PydanticSchemaGenerationError as PydanticSchemaGenerationError\nfrom .v2 import RequiredParam as RequiredParam\nfrom .v2 import Undefined as Undefined\nfrom .v2 import Url as Url\nfrom .v2 import copy_field_info as copy_field_info\nfrom .v2 import create_body_model as create_body_model\nfrom .v2 import evaluate_forwardref as evaluate_forwardref\nfrom .v2 import get_cached_model_fields as get_cached_model_fields\nfrom .v2 import get_definitions as get_definitions\nfrom .v2 import get_flat_models_from_fields as get_flat_models_from_fields\nfrom .v2 import get_missing_field_error as get_missing_field_error\nfrom .v2 import get_model_name_map as get_model_name_map\nfrom .v2 import get_schema_from_model_field as get_schema_from_model_field\nfrom .v2 import is_scalar_field as is_scalar_field\nfrom .v2 import serialize_sequence_value as serialize_sequence_value\nfrom .v2 import (\n with_info_plain_validator_function as with_info_plain_validator_function,\n)", "source_type": "code", "path": "fastapi/_compat/__init__.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/__init__.py#L1-L40", "start_line": 1, "end_line": 40} {"id": "fastapi/_compat/shared.py::lenient_issubclass::L47", "text": "# File: fastapi/_compat/shared.py | Symbol: lenient_issubclass\ndef lenient_issubclass(\n cls: Any, class_or_tuple: type[_T] | tuple[type[_T], ...] | None\n) -> TypeGuard[type[_T]]:\n try:\n return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]\n except TypeError: # pragma: no cover\n if isinstance(cls, WithArgsTypes):\n return False\n raise # pragma: no cover", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "lenient_issubclass", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L47-L55", "start_line": 47, "end_line": 55} {"id": "fastapi/_compat/shared.py::_annotation_is_sequence::L58", "text": "# File: fastapi/_compat/shared.py | Symbol: _annotation_is_sequence\ndef _annotation_is_sequence(annotation: type[Any] | None) -> bool:\n if lenient_issubclass(annotation, (str, bytes)):\n return False\n return lenient_issubclass(annotation, sequence_types)", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "_annotation_is_sequence", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L58-L61", "start_line": 58, "end_line": 61} {"id": "fastapi/_compat/shared.py::field_annotation_is_sequence::L64", "text": "# File: fastapi/_compat/shared.py | Symbol: field_annotation_is_sequence\ndef field_annotation_is_sequence(annotation: type[Any] | None) -> bool:\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n for arg in get_args(annotation):\n if field_annotation_is_sequence(arg):\n return True\n return False\n return _annotation_is_sequence(annotation) or _annotation_is_sequence(\n get_origin(annotation)\n )", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "field_annotation_is_sequence", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L64-L73", "start_line": 64, "end_line": 73} {"id": "fastapi/_compat/shared.py::value_is_sequence::L76", "text": "# File: fastapi/_compat/shared.py | Symbol: value_is_sequence\ndef value_is_sequence(value: Any) -> bool:\n return isinstance(value, sequence_types) and not isinstance(value, (str, bytes))", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "value_is_sequence", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L76-L77", "start_line": 76, "end_line": 77} {"id": "fastapi/_compat/shared.py::_annotation_is_complex::L80", "text": "# File: fastapi/_compat/shared.py | Symbol: _annotation_is_complex\ndef _annotation_is_complex(annotation: type[Any] | None) -> bool:\n return (\n lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile))\n or _annotation_is_sequence(annotation)\n or is_dataclass(annotation)\n )", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "_annotation_is_complex", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L80-L85", "start_line": 80, "end_line": 85} {"id": "fastapi/_compat/shared.py::field_annotation_is_complex::L88", "text": "# File: fastapi/_compat/shared.py | Symbol: field_annotation_is_complex\ndef field_annotation_is_complex(annotation: type[Any] | None) -> bool:\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n return any(field_annotation_is_complex(arg) for arg in get_args(annotation))\n\n if origin is Annotated:\n return field_annotation_is_complex(get_args(annotation)[0])\n\n return (\n _annotation_is_complex(annotation)\n or _annotation_is_complex(origin)\n or hasattr(origin, \"__pydantic_core_schema__\")\n or hasattr(origin, \"__get_pydantic_core_schema__\")\n )", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "field_annotation_is_complex", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L88-L101", "start_line": 88, "end_line": 101} {"id": "fastapi/_compat/shared.py::field_annotation_is_scalar::L104", "text": "# File: fastapi/_compat/shared.py | Symbol: field_annotation_is_scalar\ndef field_annotation_is_scalar(annotation: Any) -> bool:\n # handle Ellipsis here to make tuple[int, ...] work nicely\n return annotation is Ellipsis or not field_annotation_is_complex(annotation)", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "field_annotation_is_scalar", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L104-L106", "start_line": 104, "end_line": 106} {"id": "fastapi/_compat/shared.py::field_annotation_is_scalar_sequence::L109", "text": "# File: fastapi/_compat/shared.py | Symbol: field_annotation_is_scalar_sequence\ndef field_annotation_is_scalar_sequence(annotation: type[Any] | None) -> bool:\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n at_least_one_scalar_sequence = False\n for arg in get_args(annotation):\n if field_annotation_is_scalar_sequence(arg):\n at_least_one_scalar_sequence = True\n continue\n elif not field_annotation_is_scalar(arg):\n return False\n return at_least_one_scalar_sequence\n return field_annotation_is_sequence(annotation) and all(\n field_annotation_is_scalar(sub_annotation)\n for sub_annotation in get_args(annotation)\n )", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "field_annotation_is_scalar_sequence", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L109-L123", "start_line": 109, "end_line": 123} {"id": "fastapi/_compat/shared.py::is_bytes_or_nonable_bytes_annotation::L126", "text": "# File: fastapi/_compat/shared.py | Symbol: is_bytes_or_nonable_bytes_annotation\ndef is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool:\n if lenient_issubclass(annotation, bytes):\n return True\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n for arg in get_args(annotation):\n if lenient_issubclass(arg, bytes):\n return True\n return False", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "is_bytes_or_nonable_bytes_annotation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L126-L134", "start_line": 126, "end_line": 134} {"id": "fastapi/_compat/shared.py::is_uploadfile_or_nonable_uploadfile_annotation::L137", "text": "# File: fastapi/_compat/shared.py | Symbol: is_uploadfile_or_nonable_uploadfile_annotation\ndef is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool:\n if lenient_issubclass(annotation, UploadFile):\n return True\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n for arg in get_args(annotation):\n if lenient_issubclass(arg, UploadFile):\n return True\n return False", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "is_uploadfile_or_nonable_uploadfile_annotation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L137-L145", "start_line": 137, "end_line": 145} {"id": "fastapi/_compat/shared.py::is_bytes_sequence_annotation::L148", "text": "# File: fastapi/_compat/shared.py | Symbol: is_bytes_sequence_annotation\ndef is_bytes_sequence_annotation(annotation: Any) -> bool:\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n at_least_one = False\n for arg in get_args(annotation):\n if is_bytes_sequence_annotation(arg):\n at_least_one = True\n continue\n return at_least_one\n return field_annotation_is_sequence(annotation) and all(\n is_bytes_or_nonable_bytes_annotation(sub_annotation)\n for sub_annotation in get_args(annotation)\n )", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "is_bytes_sequence_annotation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L148-L160", "start_line": 148, "end_line": 160} {"id": "fastapi/_compat/shared.py::is_uploadfile_sequence_annotation::L163", "text": "# File: fastapi/_compat/shared.py | Symbol: is_uploadfile_sequence_annotation\ndef is_uploadfile_sequence_annotation(annotation: Any) -> bool:\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n at_least_one = False\n for arg in get_args(annotation):\n if is_uploadfile_sequence_annotation(arg):\n at_least_one = True\n continue\n return at_least_one\n return field_annotation_is_sequence(annotation) and all(\n is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation)\n for sub_annotation in get_args(annotation)\n )", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "is_uploadfile_sequence_annotation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L163-L175", "start_line": 163, "end_line": 175} {"id": "fastapi/_compat/shared.py::is_pydantic_v1_model_instance::L178", "text": "# File: fastapi/_compat/shared.py | Symbol: is_pydantic_v1_model_instance\ndef is_pydantic_v1_model_instance(obj: Any) -> bool:\n # TODO: remove this function once the required version of Pydantic fully\n # removes pydantic.v1\n try:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", UserWarning)\n from pydantic import v1\n except ImportError: # pragma: no cover\n return False\n return isinstance(obj, v1.BaseModel)", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "is_pydantic_v1_model_instance", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L178-L187", "start_line": 178, "end_line": 187} {"id": "fastapi/_compat/shared.py::is_pydantic_v1_model_class::L190", "text": "# File: fastapi/_compat/shared.py | Symbol: is_pydantic_v1_model_class\ndef is_pydantic_v1_model_class(cls: Any) -> bool:\n # TODO: remove this function once the required version of Pydantic fully\n # removes pydantic.v1\n try:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", UserWarning)\n from pydantic import v1\n except ImportError: # pragma: no cover\n return False\n return lenient_issubclass(cls, v1.BaseModel)", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "is_pydantic_v1_model_class", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L190-L199", "start_line": 190, "end_line": 199} {"id": "fastapi/_compat/shared.py::annotation_is_pydantic_v1::L202", "text": "# File: fastapi/_compat/shared.py | Symbol: annotation_is_pydantic_v1\ndef annotation_is_pydantic_v1(annotation: Any) -> bool:\n if is_pydantic_v1_model_class(annotation):\n return True\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n for arg in get_args(annotation):\n if is_pydantic_v1_model_class(arg):\n return True\n if field_annotation_is_sequence(annotation):\n for sub_annotation in get_args(annotation):\n if annotation_is_pydantic_v1(sub_annotation):\n return True\n return False", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "annotation_is_pydantic_v1", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L202-L214", "start_line": 202, "end_line": 214} {"id": "fastapi/_compat/shared.py::", "text": "# File: fastapi/_compat/shared.py | Symbol: \nimport types\nimport typing\nimport warnings\nfrom collections import deque\nfrom collections.abc import Mapping, Sequence\nfrom dataclasses import is_dataclass\nfrom typing import (\n Annotated,\n Any,\n TypeGuard,\n TypeVar,\n Union,\n get_args,\n get_origin,\n)\nfrom fastapi.types import UnionType\nfrom pydantic import BaseModel\nfrom pydantic.version import VERSION as PYDANTIC_VERSION\nfrom starlette.datastructures import UploadFile\n_T = TypeVar(\"_T\")\n# Copy from Pydantic: pydantic/_internal/_typing_extra.py\nWithArgsTypes: tuple[Any, ...] = (\n typing._GenericAlias, # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]\n types.GenericAlias,\n types.UnionType,\n) # pyright: ignore[reportAttributeAccessIssue]\nPYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(\".\")[:2])\nsequence_annotation_to_type = {\n Sequence: list,\n list: list,\n tuple: tuple,\n set: set,\n frozenset: frozenset,\n deque: deque,\n}\nsequence_types: tuple[type[Any], ...] = tuple(sequence_annotation_to_type.keys())\n# Copy of Pydantic: pydantic/_internal/_utils.py with added TypeGuard", "source_type": "code", "path": "fastapi/_compat/shared.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/shared.py#L1-L46", "start_line": 1, "end_line": 46} {"id": "fastapi/_compat/v2.py::evaluate_forwardref::L43", "text": "# File: fastapi/_compat/v2.py | Symbol: evaluate_forwardref\ndef evaluate_forwardref(\n value: Any,\n globalns: dict[str, Any] | None = None,\n localns: dict[str, Any] | None = None,\n) -> Any:\n # eval_type_lenient has been deprecated since Pydantic v2.10.0b1 (PR #10530)\n try_eval_type = getattr(_pydantic_typing_extra, \"try_eval_type\", None)\n if try_eval_type is not None:\n return try_eval_type(value, globalns, localns)[0]\n return _pydantic_typing_extra.eval_type_lenient( # ty: ignore[deprecated]\n value, globalns, localns\n )", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "evaluate_forwardref", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L43-L54", "start_line": 43, "end_line": 54} {"id": "fastapi/_compat/v2.py::GenerateJsonSchema::L57", "text": "# File: fastapi/_compat/v2.py | Symbol: GenerateJsonSchema\nclass GenerateJsonSchema(_GenerateJsonSchema):\n # TODO: remove when this is merged (or equivalent): https://github.com/pydantic/pydantic/pull/12841\n # and dropping support for any version of Pydantic before that one (so, in a very long time)\n def bytes_schema(self, schema: CoreSchema) -> JsonSchemaValue:\n json_schema = {\"type\": \"string\", \"contentMediaType\": \"application/octet-stream\"}\n bytes_mode = (\n self._config.ser_json_bytes\n if self.mode == \"serialization\"\n else self._config.val_json_bytes\n )\n if bytes_mode == \"base64\":\n json_schema[\"contentEncoding\"] = \"base64\"\n self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)\n return json_schema", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "GenerateJsonSchema", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L57-L70", "start_line": 57, "end_line": 70} {"id": "fastapi/_compat/v2.py::asdict::L100", "text": "# File: fastapi/_compat/v2.py | Symbol: asdict\ndef asdict(field_info: FieldInfo) -> dict[str, Any]:\n attributes = {}\n for attr in _Attrs:\n value = getattr(field_info, attr, Undefined)\n if value is not Undefined:\n attributes[attr] = value\n return {\n \"annotation\": field_info.annotation,\n \"metadata\": field_info.metadata,\n \"attributes\": attributes,\n }", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "asdict", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L100-L110", "start_line": 100, "end_line": 110} {"id": "fastapi/_compat/v2.py::ModelField::L113", "text": "# File: fastapi/_compat/v2.py | Symbol: ModelField\n@dataclass\nclass ModelField:\n field_info: FieldInfo\n name: str\n mode: Literal[\"validation\", \"serialization\"] = \"validation\"\n config: ConfigDict | None = None\n\n @property\n def alias(self) -> str:\n a = self.field_info.alias\n return a if a is not None else self.name\n\n @property\n def validation_alias(self) -> str | None:\n va = self.field_info.validation_alias\n if isinstance(va, str) and va:\n return va\n return None\n\n @property\n def serialization_alias(self) -> str | None:\n sa = self.field_info.serialization_alias\n return sa or None\n\n @property\n def default(self) -> Any:\n return self.get_default()\n\n def __post_init__(self) -> None:\n with warnings.catch_warnings():\n # Pydantic >= 2.12.0 warns about field specific metadata that is unused\n # (e.g. `TypeAdapter(Annotated[int, Field(alias='b')])`). In some cases, we\n # end up building the type adapter from a model field annotation so we\n # need to ignore the warning:\n if shared.PYDANTIC_VERSION_MINOR_TUPLE >= (2, 12):\n from pydantic.warnings import UnsupportedFieldAttributeWarning\n\n warnings.simplefilter(\n \"ignore\", category=UnsupportedFieldAttributeWarning\n )\n # TODO: remove after setting the min Pydantic to v2.12.3\n # that adds asdict(), and use self.field_info.asdict() instead\n field_dict = asdict(self.field_info)\n annotated_args = (\n field_dict[\"annotation\"],\n *field_dict[\"metadata\"],\n # this FieldInfo needs to be created again so that it doesn't include\n # the old field info metadata and only the rest of the attributes\n Field(**field_dict[\"attributes\"]),\n )\n self._type_adapter: TypeAdapter[Any] = TypeAdapter(\n Annotated[annotated_args], # ty: ignore[invalid-type-form]\n config=self.config,\n )\n\n def get_default(self) -> Any:\n if self.field_info.is_required():\n return Undefined\n return self.field_info.get_default(call_default_factory=True)\n\n def validate(\n self,\n value: Any,\n values: dict[str, Any] = {}, # noqa: B006\n *,\n loc: tuple[int | str, ...] = (),\n ) -> tuple[Any, list[dict[str, Any]]]:\n try:\n return (\n self._type_adapter.validate_python(value, from_attributes=True),\n [],\n )\n except ValidationError as exc:\n return None, _regenerate_error_with_loc(\n errors=exc.errors(include_url=False), loc_prefix=loc\n )\n\n def serialize(\n self,\n value: Any,\n *,\n mode: Literal[\"json\", \"python\"] = \"json\",\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 ) -> Any:\n # What calls this code passes a value that already called\n # self._type_adapter.validate_python(value)\n return self._type_adapter.dump_python(\n value,\n mode=mode,\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 def serialize_json(\n self,\n value: Any,\n *,\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 ) -> bytes:\n # What calls this code passes a value that already called\n # self._type_adapter.validate_python(value)\n # This uses Pydantic's dump_json() which serializes directly to JSON\n # bytes in one pass (via Rust), avoiding the intermediate Python dict\n # step of dump_python(mode=\"json\") + json.dumps().\n return self._type_adapter.dump_json(\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 def __hash__(self) -> int:\n # Each ModelField is unique for our purposes, to allow making a dict from\n # ModelField to its JSON Schema.\n return id(self)", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "ModelField", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L113-L244", "start_line": 113, "end_line": 244} {"id": "fastapi/_compat/v2.py::_has_computed_fields::L247", "text": "# File: fastapi/_compat/v2.py | Symbol: _has_computed_fields\ndef _has_computed_fields(field: ModelField) -> bool:\n computed_fields = field._type_adapter.core_schema.get(\"schema\", {}).get(\n \"computed_fields\", []\n )\n return len(computed_fields) > 0", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "_has_computed_fields", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L247-L251", "start_line": 247, "end_line": 251} {"id": "fastapi/_compat/v2.py::get_schema_from_model_field::L254", "text": "# File: fastapi/_compat/v2.py | Symbol: get_schema_from_model_field\ndef get_schema_from_model_field(\n *,\n field: ModelField,\n model_name_map: ModelNameMap,\n field_mapping: dict[\n tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue\n ],\n separate_input_output_schemas: bool = True,\n) -> dict[str, Any]:\n override_mode: Literal[\"validation\"] | None = (\n None\n if (separate_input_output_schemas or _has_computed_fields(field))\n else \"validation\"\n )\n field_alias = (\n (field.validation_alias or field.alias)\n if field.mode == \"validation\"\n else (field.serialization_alias or field.alias)\n )\n\n # This expects that GenerateJsonSchema was already used to generate the definitions\n json_schema = field_mapping[(field, override_mode or field.mode)]\n if \"$ref\" not in json_schema:\n # TODO remove when deprecating Pydantic v1\n # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207\n json_schema[\"title\"] = field.field_info.title or field_alias.title().replace(\n \"_\", \" \"\n )\n return json_schema", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_schema_from_model_field", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L254-L282", "start_line": 254, "end_line": 282} {"id": "fastapi/_compat/v2.py::get_definitions::L285", "text": "# File: fastapi/_compat/v2.py | Symbol: get_definitions\ndef get_definitions(\n *,\n fields: Sequence[ModelField],\n model_name_map: ModelNameMap,\n separate_input_output_schemas: bool = True,\n) -> tuple[\n dict[tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue],\n dict[str, dict[str, Any]],\n]:\n schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE)\n validation_fields = [field for field in fields if field.mode == \"validation\"]\n serialization_fields = [field for field in fields if field.mode == \"serialization\"]\n flat_validation_models = get_flat_models_from_fields(\n validation_fields, known_models=set()\n )\n flat_serialization_models = get_flat_models_from_fields(\n serialization_fields, known_models=set()\n )\n flat_validation_model_fields = [\n ModelField(\n field_info=FieldInfo(annotation=model),\n name=model.__name__,\n mode=\"validation\",\n )\n for model in flat_validation_models\n ]\n flat_serialization_model_fields = [\n ModelField(\n field_info=FieldInfo(annotation=model),\n name=model.__name__,\n mode=\"serialization\",\n )\n for model in flat_serialization_models\n ]\n flat_model_fields = flat_validation_model_fields + flat_serialization_model_fields\n input_types = {f.field_info.annotation for f in fields}\n unique_flat_model_fields = {\n f for f in flat_model_fields if f.field_info.annotation not in input_types\n }\n inputs = [\n (\n field,\n (\n field.mode\n if (separate_input_output_schemas or _has_computed_fields(field))\n else \"validation\"\n ),\n field._type_adapter.core_schema,\n )\n for field in list(fields) + list(unique_flat_model_fields)\n ]\n field_mapping, definitions = schema_generator.generate_definitions(inputs=inputs)\n for item_def in cast(dict[str, dict[str, Any]], definitions).values():\n if \"description\" in item_def:\n item_description = cast(str, item_def[\"description\"]).split(\"\\f\")[0]\n item_def[\"description\"] = item_description\n # definitions: dict[DefsRef, dict[str, Any]]\n # but mypy complains about general str in other places that are not declared as\n # DefsRef, although DefsRef is just str:\n # DefsRef = NewType('DefsRef', str)\n # So, a cast to simplify the types here\n return field_mapping, cast(dict[str, dict[str, Any]], definitions)", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_definitions", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L285-L346", "start_line": 285, "end_line": 346} {"id": "fastapi/_compat/v2.py::is_scalar_field::L349", "text": "# File: fastapi/_compat/v2.py | Symbol: is_scalar_field\ndef is_scalar_field(field: ModelField) -> bool:\n from fastapi import params\n\n return shared.field_annotation_is_scalar(\n field.field_info.annotation\n ) and not isinstance(field.field_info, params.Body)", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "is_scalar_field", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L349-L354", "start_line": 349, "end_line": 354} {"id": "fastapi/_compat/v2.py::copy_field_info::L357", "text": "# File: fastapi/_compat/v2.py | Symbol: copy_field_info\ndef copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:\n cls = type(field_info)\n merged_field_info = cls.from_annotation(annotation)\n new_field_info = copy(field_info)\n new_field_info.metadata = merged_field_info.metadata\n new_field_info.annotation = merged_field_info.annotation\n return new_field_info", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "copy_field_info", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L357-L363", "start_line": 357, "end_line": 363} {"id": "fastapi/_compat/v2.py::serialize_sequence_value::L366", "text": "# File: fastapi/_compat/v2.py | Symbol: serialize_sequence_value\ndef serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:\n origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation\n if origin_type is Union or origin_type is UnionType: # Handle optional sequences\n union_args = get_args(field.field_info.annotation)\n for union_arg in union_args:\n if union_arg is type(None):\n continue\n origin_type = get_origin(union_arg) or union_arg\n break\n assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]\n return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index] # ty: ignore[invalid-return-type]", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "serialize_sequence_value", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L366-L376", "start_line": 366, "end_line": 376} {"id": "fastapi/_compat/v2.py::get_missing_field_error::L379", "text": "# File: fastapi/_compat/v2.py | Symbol: get_missing_field_error\ndef get_missing_field_error(loc: tuple[int | str, ...]) -> dict[str, Any]:\n error = ValidationError.from_exception_data(\n \"Field required\", [{\"type\": \"missing\", \"loc\": loc, \"input\": {}}]\n ).errors(include_url=False)[0]\n error[\"input\"] = None\n return error # type: ignore[return-value] # ty: ignore[invalid-return-type]", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_missing_field_error", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L379-L384", "start_line": 379, "end_line": 384} {"id": "fastapi/_compat/v2.py::create_body_model::L387", "text": "# File: fastapi/_compat/v2.py | Symbol: create_body_model\ndef create_body_model(\n *, fields: Sequence[ModelField], model_name: str\n) -> type[BaseModel]:\n field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields}\n BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] # ty: ignore[no-matching-overload]\n return BodyModel", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "create_body_model", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L387-L392", "start_line": 387, "end_line": 392} {"id": "fastapi/_compat/v2.py::get_model_fields::L395", "text": "# File: fastapi/_compat/v2.py | Symbol: get_model_fields\ndef get_model_fields(model: type[BaseModel]) -> list[ModelField]:\n model_fields: list[ModelField] = []\n for name, field_info in model.model_fields.items():\n type_ = field_info.annotation\n if lenient_issubclass(type_, (BaseModel, dict)) or is_dataclass(type_):\n model_config = None\n else:\n model_config = model.model_config\n model_fields.append(\n ModelField(\n field_info=field_info,\n name=name,\n config=model_config,\n )\n )\n return model_fields", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_model_fields", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L395-L410", "start_line": 395, "end_line": 410} {"id": "fastapi/_compat/v2.py::get_cached_model_fields::L413", "text": "# File: fastapi/_compat/v2.py | Symbol: get_cached_model_fields\n@lru_cache\ndef get_cached_model_fields(model: type[BaseModel]) -> list[ModelField]:\n return get_model_fields(model)", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_cached_model_fields", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L413-L415", "start_line": 413, "end_line": 415} {"id": "fastapi/_compat/v2.py::normalize_name::L425", "text": "# File: fastapi/_compat/v2.py | Symbol: normalize_name\ndef normalize_name(name: str) -> str:\n return re.sub(r\"[^a-zA-Z0-9.\\-_]\", \"_\", name)", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "normalize_name", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L425-L426", "start_line": 425, "end_line": 426} {"id": "fastapi/_compat/v2.py::get_model_name_map::L429", "text": "# File: fastapi/_compat/v2.py | Symbol: get_model_name_map\ndef get_model_name_map(unique_models: TypeModelSet) -> dict[TypeModelOrEnum, str]:\n name_model_map = {}\n for model in unique_models:\n model_name = normalize_name(model.__name__)\n name_model_map[model_name] = model\n return {v: k for k, v in name_model_map.items()}", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_model_name_map", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L429-L434", "start_line": 429, "end_line": 434} {"id": "fastapi/_compat/v2.py::get_flat_models_from_model::L437", "text": "# File: fastapi/_compat/v2.py | Symbol: get_flat_models_from_model\ndef get_flat_models_from_model(\n model: type[\"BaseModel\"], known_models: TypeModelSet | None = None\n) -> TypeModelSet:\n known_models = known_models or set()\n fields = get_model_fields(model)\n get_flat_models_from_fields(fields, known_models=known_models)\n return known_models", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_flat_models_from_model", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L437-L443", "start_line": 437, "end_line": 443} {"id": "fastapi/_compat/v2.py::get_flat_models_from_annotation::L446", "text": "# File: fastapi/_compat/v2.py | Symbol: get_flat_models_from_annotation\ndef get_flat_models_from_annotation(\n annotation: Any, known_models: TypeModelSet\n) -> TypeModelSet:\n origin = get_origin(annotation)\n if origin is not None:\n for arg in get_args(annotation):\n if lenient_issubclass(arg, (BaseModel, Enum)):\n if arg not in known_models:\n known_models.add(arg) # type: ignore[arg-type]\n if lenient_issubclass(arg, BaseModel):\n get_flat_models_from_model(arg, known_models=known_models)\n else:\n get_flat_models_from_annotation(arg, known_models=known_models)\n return known_models", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_flat_models_from_annotation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L446-L459", "start_line": 446, "end_line": 459} {"id": "fastapi/_compat/v2.py::get_flat_models_from_field::L462", "text": "# File: fastapi/_compat/v2.py | Symbol: get_flat_models_from_field\ndef get_flat_models_from_field(\n field: ModelField, known_models: TypeModelSet\n) -> TypeModelSet:\n field_type = field.field_info.annotation\n if lenient_issubclass(field_type, BaseModel):\n if field_type in known_models:\n return known_models\n known_models.add(field_type)\n get_flat_models_from_model(field_type, known_models=known_models)\n elif lenient_issubclass(field_type, Enum):\n known_models.add(field_type)\n else:\n get_flat_models_from_annotation(field_type, known_models=known_models)\n return known_models", "source_type": "code", "path": "fastapi/_compat/v2.py", "symbol": "get_flat_models_from_field", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/_compat/v2.py#L462-L475", "start_line": 462, "end_line": 475} {"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} {"id": "fastapi/cli.py::", "text": "# File: fastapi/cli.py | Symbol: \ntry:\n from fastapi_cli.cli import main as cli_main\nexcept ImportError: # pragma: no cover\n cli_main = None # type: ignore", "source_type": "code", "path": "fastapi/cli.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/cli.py#L1-L5", "start_line": 1, "end_line": 5} {"id": "fastapi/concurrency.py::contextmanager_in_threadpool::L17", "text": "# File: fastapi/concurrency.py | Symbol: contextmanager_in_threadpool\n@asynccontextmanager\nasync def contextmanager_in_threadpool(\n cm: AbstractContextManager[_T],\n) -> AsyncGenerator[_T, None]:\n # blocking __exit__ from running waiting on a free thread\n # can create race conditions/deadlocks if the context manager itself\n # has its own internal pool (e.g. a database connection pool)\n # to avoid this we let __exit__ run without a capacity limit\n # since we're creating a new limiter for each call, any non-zero limit\n # works (1 is arbitrary)\n exit_limiter = CapacityLimiter(1)\n try:\n yield await run_in_threadpool(cm.__enter__)\n except Exception as e:\n ok = bool(\n await anyio.to_thread.run_sync(\n cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter\n )\n )\n if not ok:\n raise e\n else:\n await anyio.to_thread.run_sync(\n cm.__exit__, None, None, None, limiter=exit_limiter\n )", "source_type": "code", "path": "fastapi/concurrency.py", "symbol": "contextmanager_in_threadpool", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/concurrency.py#L17-L41", "start_line": 17, "end_line": 41} {"id": "fastapi/concurrency.py::", "text": "# File: fastapi/concurrency.py | Symbol: \nfrom collections.abc import AsyncGenerator\nfrom contextlib import AbstractContextManager\nfrom contextlib import asynccontextmanager as asynccontextmanager\nfrom typing import TypeVar\nimport anyio.to_thread\nfrom anyio import CapacityLimiter\nfrom starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa\nfrom starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa\nfrom starlette.concurrency import ( # noqa\n run_until_first_complete as run_until_first_complete,\n)\n_T = TypeVar(\"_T\")", "source_type": "code", "path": "fastapi/concurrency.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/concurrency.py#L1-L14", "start_line": 1, "end_line": 14} {"id": "fastapi/datastructures.py::UploadFile::L21", "text": "# File: fastapi/datastructures.py | Symbol: UploadFile\nclass UploadFile(StarletteUploadFile):\n \"\"\"\n A file uploaded in a request.\n\n Define it as a *path operation function* (or dependency) parameter.\n\n If you are using a regular `def` function, you can use the `upload_file.file`\n attribute to access the raw standard Python file (blocking, not async), useful and\n needed for non-async code.\n\n Read more about it in the\n [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/).\n\n ## Example\n\n ```python\n from typing import Annotated\n\n from fastapi import FastAPI, File, UploadFile\n\n app = FastAPI()\n\n\n @app.post(\"/files/\")\n async def create_file(file: Annotated[bytes, File()]):\n return {\"file_size\": len(file)}\n\n\n @app.post(\"/uploadfile/\")\n async def create_upload_file(file: UploadFile):\n return {\"filename\": file.filename}\n ```\n \"\"\"\n\n file: Annotated[\n BinaryIO,\n Doc(\"The standard Python file object (non-async).\"),\n ]\n filename: Annotated[str | None, Doc(\"The original file name.\")]\n size: Annotated[int | None, Doc(\"The size of the file in bytes.\")]\n headers: Annotated[Headers, Doc(\"The headers of the request.\")]\n content_type: Annotated[\n str | None, Doc(\"The content type of the request, from the headers.\")\n ]\n\n async def write(\n self,\n data: Annotated[\n bytes,\n Doc(\n \"\"\"\n The bytes to write to the file.\n \"\"\"\n ),\n ],\n ) -> None:\n \"\"\"\n Write some bytes to the file.\n\n You normally wouldn't use this from a file you read in a request.\n\n To be awaitable, compatible with async, this is run in threadpool.\n \"\"\"\n return await super().write(data)\n\n async def read(\n self,\n size: Annotated[\n int,\n Doc(\n \"\"\"\n The number of bytes to read from the file.\n \"\"\"\n ),\n ] = -1,\n ) -> bytes:\n \"\"\"\n Read some bytes from the file.\n\n To be awaitable, compatible with async, this is run in threadpool.\n \"\"\"\n return await super().read(size)\n\n async def seek(\n self,\n offset: Annotated[\n int,\n Doc(\n \"\"\"\n The position in bytes to seek to in the file.\n \"\"\"\n ),\n ],\n ) -> None:\n \"\"\"\n Move to a position in the file.\n\n Any next read or write will be done from that position.\n\n To be awaitable, compatible with async, this is run in threadpool.\n \"\"\"\n return await super().seek(offset)\n\n async def close(self) -> None:\n \"\"\"\n Close the file.\n\n To be awaitable, compatible with async, this is run in threadpool.\n \"\"\"\n return await super().close()\n\n @classmethod\n def _validate(cls, __input_value: Any, _: Any) -> \"UploadFile\":\n if not isinstance(__input_value, StarletteUploadFile):\n raise ValueError(f\"Expected UploadFile, received: {type(__input_value)}\")\n return cast(UploadFile, __input_value)\n\n @classmethod\n def __get_pydantic_json_schema__(\n cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler\n ) -> dict[str, Any]:\n return {\"type\": \"string\", \"contentMediaType\": \"application/octet-stream\"}\n\n @classmethod\n def __get_pydantic_core_schema__(\n cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]\n ) -> Mapping[str, Any]:\n from ._compat.v2 import with_info_plain_validator_function\n\n return with_info_plain_validator_function(cls._validate)", "source_type": "code", "path": "fastapi/datastructures.py", "symbol": "UploadFile", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/datastructures.py#L21-L150", "start_line": 21, "end_line": 150} {"id": "fastapi/datastructures.py::DefaultPlaceholder::L153", "text": "# File: fastapi/datastructures.py | Symbol: DefaultPlaceholder\nclass DefaultPlaceholder:\n \"\"\"\n You shouldn't use this class directly.\n\n It's used internally to recognize when a default value has been overwritten, even\n if the overridden default value was truthy.\n \"\"\"\n\n def __init__(self, value: Any):\n self.value = value\n\n def __bool__(self) -> bool:\n return bool(self.value)\n\n def __eq__(self, o: object) -> bool:\n return isinstance(o, DefaultPlaceholder) and o.value == self.value", "source_type": "code", "path": "fastapi/datastructures.py", "symbol": "DefaultPlaceholder", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/datastructures.py#L153-L168", "start_line": 153, "end_line": 168} {"id": "fastapi/datastructures.py::Default::L174", "text": "# File: fastapi/datastructures.py | Symbol: Default\ndef Default(value: DefaultType) -> DefaultType:\n \"\"\"\n You shouldn't use this function directly.\n\n It's used internally to recognize when a default value has been overwritten, even\n if the overridden default value was truthy.\n \"\"\"\n return DefaultPlaceholder(value) # type: ignore", "source_type": "code", "path": "fastapi/datastructures.py", "symbol": "Default", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/datastructures.py#L174-L181", "start_line": 174, "end_line": 181} {"id": "fastapi/datastructures.py::", "text": "# File: fastapi/datastructures.py | Symbol: \nfrom collections.abc import Callable, Mapping\nfrom typing import (\n Annotated,\n Any,\n BinaryIO,\n TypeVar,\n cast,\n)\nfrom annotated_doc import Doc\nfrom pydantic import GetJsonSchemaHandler\nfrom starlette.datastructures import URL as URL # noqa: F401\nfrom starlette.datastructures import Address as Address # noqa: F401\nfrom starlette.datastructures import FormData as FormData # noqa: F401\nfrom starlette.datastructures import Headers as Headers # noqa: F401\nfrom starlette.datastructures import QueryParams as QueryParams # noqa: F401\nfrom starlette.datastructures import State as State # noqa: F401\nfrom starlette.datastructures import UploadFile as StarletteUploadFile\nDefaultType = TypeVar(\"DefaultType\")\n# Sentinel for \"parameter not provided\" in Param/FieldInfo.\n# Typed as None to satisfy ty\n_Unset = Default(None)", "source_type": "code", "path": "fastapi/datastructures.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/datastructures.py#L1-L186", "start_line": 1, "end_line": 186} {"id": "fastapi/dependencies/models.py::_unwrapped_call::L18", "text": "# File: fastapi/dependencies/models.py | Symbol: _unwrapped_call\ndef _unwrapped_call(call: Callable[..., Any] | None) -> Any:\n if call is None:\n return call # pragma: no cover\n unwrapped = inspect.unwrap(_impartial(call))\n return unwrapped", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "_unwrapped_call", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L18-L22", "start_line": 18, "end_line": 22} {"id": "fastapi/dependencies/models.py::_impartial::L25", "text": "# File: fastapi/dependencies/models.py | Symbol: _impartial\ndef _impartial(func: Callable[..., Any]) -> Callable[..., Any]:\n while isinstance(func, partial):\n func = func.func\n return func", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "_impartial", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L25-L28", "start_line": 25, "end_line": 28} {"id": "fastapi/dependencies/models.py::Dependant.oauth_scopes::L53", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant.oauth_scopes\n@cached_property\n def oauth_scopes(self) -> list[str]:\n scopes = self.parent_oauth_scopes.copy() if self.parent_oauth_scopes else []\n # This doesn't use a set to preserve order, just in case\n for scope in self.own_oauth_scopes or []:\n if scope not in scopes:\n scopes.append(scope)\n return scopes", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant.oauth_scopes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L53-L60", "start_line": 53, "end_line": 60} {"id": "fastapi/dependencies/models.py::Dependant.cache_key::L62", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant.cache_key\n@cached_property\n def cache_key(self) -> DependencyCacheKey:\n scopes_for_cache = (\n tuple(sorted(set(self.oauth_scopes or []))) if self._uses_scopes else ()\n )\n return (\n self.call,\n scopes_for_cache,\n self.computed_scope or \"\",\n )", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant.cache_key", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L62-L71", "start_line": 62, "end_line": 71} {"id": "fastapi/dependencies/models.py::Dependant._uses_scopes::L73", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant._uses_scopes\n@cached_property\n def _uses_scopes(self) -> bool:\n if self.own_oauth_scopes:\n return True\n if self.security_scopes_param_name is not None:\n return True\n if self._is_security_scheme:\n return True\n for sub_dep in self.dependencies:\n if sub_dep._uses_scopes:\n return True\n return False", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant._uses_scopes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L73-L84", "start_line": 73, "end_line": 84} {"id": "fastapi/dependencies/models.py::Dependant._is_security_scheme::L86", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant._is_security_scheme\n@cached_property\n def _is_security_scheme(self) -> bool:\n if self.call is None:\n return False # pragma: no cover\n unwrapped = _unwrapped_call(self.call)\n return isinstance(unwrapped, SecurityBase)", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant._is_security_scheme", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L86-L91", "start_line": 86, "end_line": 91} {"id": "fastapi/dependencies/models.py::Dependant._security_scheme::L94", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant._security_scheme\n@cached_property\n def _security_scheme(self) -> SecurityBase:\n unwrapped = _unwrapped_call(self.call)\n assert isinstance(unwrapped, SecurityBase)\n return unwrapped", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant._security_scheme", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L94-L98", "start_line": 94, "end_line": 98} {"id": "fastapi/dependencies/models.py::Dependant._security_dependencies::L100", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant._security_dependencies\n@cached_property\n def _security_dependencies(self) -> list[\"Dependant\"]:\n security_deps = [dep for dep in self.dependencies if dep._is_security_scheme]\n return security_deps", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant._security_dependencies", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L100-L103", "start_line": 100, "end_line": 103} {"id": "fastapi/dependencies/models.py::Dependant.is_gen_callable::L105", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant.is_gen_callable\n@cached_property\n def is_gen_callable(self) -> bool:\n if self.call is None:\n return False # pragma: no cover\n if inspect.isgeneratorfunction(\n _impartial(self.call)\n ) or inspect.isgeneratorfunction(_unwrapped_call(self.call)):\n return True\n if inspect.isclass(_unwrapped_call(self.call)):\n return False\n dunder_call = getattr(_impartial(self.call), \"__call__\", None) # noqa: B004\n if dunder_call is None:\n return False # pragma: no cover\n if inspect.isgeneratorfunction(\n _impartial(dunder_call)\n ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_call)):\n return True\n dunder_unwrapped_call = getattr(_unwrapped_call(self.call), \"__call__\", None) # noqa: B004\n if dunder_unwrapped_call is None:\n return False # pragma: no cover\n if inspect.isgeneratorfunction(\n _impartial(dunder_unwrapped_call)\n ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_unwrapped_call)):\n return True\n return False", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant.is_gen_callable", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L105-L129", "start_line": 105, "end_line": 129} {"id": "fastapi/dependencies/models.py::Dependant.is_async_gen_callable::L131", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant.is_async_gen_callable\n@cached_property\n def is_async_gen_callable(self) -> bool:\n if self.call is None:\n return False # pragma: no cover\n if inspect.isasyncgenfunction(\n _impartial(self.call)\n ) or inspect.isasyncgenfunction(_unwrapped_call(self.call)):\n return True\n if inspect.isclass(_unwrapped_call(self.call)):\n return False\n dunder_call = getattr(_impartial(self.call), \"__call__\", None) # noqa: B004\n if dunder_call is None:\n return False # pragma: no cover\n if inspect.isasyncgenfunction(\n _impartial(dunder_call)\n ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_call)):\n return True\n dunder_unwrapped_call = getattr(_unwrapped_call(self.call), \"__call__\", None) # noqa: B004\n if dunder_unwrapped_call is None:\n return False # pragma: no cover\n if inspect.isasyncgenfunction(\n _impartial(dunder_unwrapped_call)\n ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_unwrapped_call)):\n return True\n return False", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant.is_async_gen_callable", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L131-L155", "start_line": 131, "end_line": 155} {"id": "fastapi/dependencies/models.py::Dependant.is_coroutine_callable::L157", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant.is_coroutine_callable\n@cached_property\n def is_coroutine_callable(self) -> bool:\n if self.call is None:\n return False # pragma: no cover\n if inspect.isroutine(_impartial(self.call)) and iscoroutinefunction(\n _impartial(self.call)\n ):\n return True\n if inspect.isroutine(_unwrapped_call(self.call)) and iscoroutinefunction(\n _unwrapped_call(self.call)\n ):\n return True\n if inspect.isclass(_unwrapped_call(self.call)):\n return False\n dunder_call = getattr(_impartial(self.call), \"__call__\", None) # noqa: B004\n if dunder_call is None:\n return False # pragma: no cover\n if iscoroutinefunction(_impartial(dunder_call)) or iscoroutinefunction(\n _unwrapped_call(dunder_call)\n ):\n return True\n dunder_unwrapped_call = getattr(_unwrapped_call(self.call), \"__call__\", None) # noqa: B004\n if dunder_unwrapped_call is None:\n return False # pragma: no cover\n if iscoroutinefunction(\n _impartial(dunder_unwrapped_call)\n ) or iscoroutinefunction(_unwrapped_call(dunder_unwrapped_call)):\n return True\n return False", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant.is_coroutine_callable", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L157-L185", "start_line": 157, "end_line": 185} {"id": "fastapi/dependencies/models.py::Dependant.computed_scope::L187", "text": "# File: fastapi/dependencies/models.py | Class: Dependant | Symbol: Dependant.computed_scope\n@cached_property\n def computed_scope(self) -> str | None:\n if self.scope:\n return self.scope\n if self.is_gen_callable or self.is_async_gen_callable:\n return \"request\"\n return None", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "Dependant.computed_scope", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L187-L193", "start_line": 187, "end_line": 193} {"id": "fastapi/dependencies/models.py::", "text": "# File: fastapi/dependencies/models.py | Symbol: \nimport inspect\nimport sys\nfrom collections.abc import Callable\nfrom dataclasses import dataclass, field\nfrom functools import cached_property, partial\nfrom typing import Any, Literal\nfrom fastapi._compat import ModelField\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.types import DependencyCacheKey\nif sys.version_info >= (3, 13): # pragma: no cover\n from inspect import iscoroutinefunction\nelse: # pragma: no cover\n from asyncio import iscoroutinefunction\n@dataclass\nclass Dependant:\n path_params: list[ModelField] = field(default_factory=list)\n query_params: list[ModelField] = field(default_factory=list)\n header_params: list[ModelField] = field(default_factory=list)\n cookie_params: list[ModelField] = field(default_factory=list)\n body_params: list[ModelField] = field(default_factory=list)\n dependencies: list[\"Dependant\"] = field(default_factory=list)\n name: str | None = None\n call: Callable[..., Any] | None = None\n request_param_name: str | None = None\n websocket_param_name: str | None = None\n http_connection_param_name: str | None = None\n response_param_name: str | None = None\n background_tasks_param_name: str | None = None\n security_scopes_param_name: str | None = None\n own_oauth_scopes: list[str] | None = None\n parent_oauth_scopes: list[str] | None = None\n use_cache: bool = True\n path: str | None = None\n scope: Literal[\"function\", \"request\"] | None = None\n # Mainly to get the type of SecurityBase, but it's the same self.call", "source_type": "code", "path": "fastapi/dependencies/models.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/models.py#L1-L93", "start_line": 1, "end_line": 93} {"id": "fastapi/dependencies/utils.py::ensure_multipart_is_installed::L94", "text": "# File: fastapi/dependencies/utils.py | Symbol: ensure_multipart_is_installed\ndef ensure_multipart_is_installed() -> None:\n try:\n from python_multipart import __version__\n\n # Import an attribute that can be mocked/deleted in testing\n assert __version__ > \"0.0.12\"\n except (ImportError, AssertionError):\n try:\n # __version__ is available in both multiparts, and can be mocked\n from multipart import ( # type: ignore[no-redef,import-untyped]\n __version__,\n )\n\n assert __version__\n try:\n # parse_options_header is only available in the right multipart\n from multipart.multipart import ( # type: ignore[import-untyped]\n parse_options_header,\n )\n\n assert parse_options_header\n except ImportError:\n logger.error(multipart_incorrect_install_error)\n raise RuntimeError(multipart_incorrect_install_error) from None\n except ImportError:\n logger.error(multipart_not_installed_error)\n raise RuntimeError(multipart_not_installed_error) from None", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "ensure_multipart_is_installed", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L94-L120", "start_line": 94, "end_line": 120} {"id": "fastapi/dependencies/utils.py::get_parameterless_sub_dependant::L123", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_parameterless_sub_dependant\ndef get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant:\n assert callable(depends.dependency), (\n \"A parameter-less dependency must have a callable dependency\"\n )\n own_oauth_scopes: list[str] = []\n if isinstance(depends, params.Security) and depends.scopes:\n own_oauth_scopes.extend(depends.scopes)\n return get_dependant(\n path=path,\n call=depends.dependency,\n scope=depends.scope,\n own_oauth_scopes=own_oauth_scopes,\n )", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_parameterless_sub_dependant", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L123-L135", "start_line": 123, "end_line": 135} {"id": "fastapi/dependencies/utils.py::get_flat_dependant::L138", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_flat_dependant\ndef get_flat_dependant(\n dependant: Dependant,\n *,\n skip_repeats: bool = False,\n visited: list[DependencyCacheKey] | None = None,\n parent_oauth_scopes: list[str] | None = None,\n) -> Dependant:\n if visited is None:\n visited = []\n visited.append(dependant.cache_key)\n use_parent_oauth_scopes = (parent_oauth_scopes or []) + (\n dependant.oauth_scopes or []\n )\n\n flat_dependant = Dependant(\n path_params=dependant.path_params.copy(),\n query_params=dependant.query_params.copy(),\n header_params=dependant.header_params.copy(),\n cookie_params=dependant.cookie_params.copy(),\n body_params=dependant.body_params.copy(),\n name=dependant.name,\n call=dependant.call,\n request_param_name=dependant.request_param_name,\n websocket_param_name=dependant.websocket_param_name,\n http_connection_param_name=dependant.http_connection_param_name,\n response_param_name=dependant.response_param_name,\n background_tasks_param_name=dependant.background_tasks_param_name,\n security_scopes_param_name=dependant.security_scopes_param_name,\n own_oauth_scopes=dependant.own_oauth_scopes,\n parent_oauth_scopes=use_parent_oauth_scopes,\n use_cache=dependant.use_cache,\n path=dependant.path,\n scope=dependant.scope,\n )\n for sub_dependant in dependant.dependencies:\n if skip_repeats and sub_dependant.cache_key in visited:\n continue\n flat_sub = get_flat_dependant(\n sub_dependant,\n skip_repeats=skip_repeats,\n visited=visited,\n parent_oauth_scopes=flat_dependant.oauth_scopes,\n )\n flat_dependant.dependencies.append(flat_sub)\n flat_dependant.path_params.extend(flat_sub.path_params)\n flat_dependant.query_params.extend(flat_sub.query_params)\n flat_dependant.header_params.extend(flat_sub.header_params)\n flat_dependant.cookie_params.extend(flat_sub.cookie_params)\n flat_dependant.body_params.extend(flat_sub.body_params)\n flat_dependant.dependencies.extend(flat_sub.dependencies)\n\n return flat_dependant", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_flat_dependant", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L138-L189", "start_line": 138, "end_line": 189} {"id": "fastapi/dependencies/utils.py::_get_flat_fields_from_params::L192", "text": "# File: fastapi/dependencies/utils.py | Symbol: _get_flat_fields_from_params\ndef _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]:\n if not fields:\n return fields\n first_field = fields[0]\n if len(fields) == 1 and lenient_issubclass(\n first_field.field_info.annotation, BaseModel\n ):\n fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)\n return fields_to_extract\n return fields", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_get_flat_fields_from_params", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L192-L201", "start_line": 192, "end_line": 201} {"id": "fastapi/dependencies/utils.py::get_flat_params::L204", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_flat_params\ndef get_flat_params(dependant: Dependant) -> list[ModelField]:\n flat_dependant = get_flat_dependant(dependant, skip_repeats=True)\n path_params = _get_flat_fields_from_params(flat_dependant.path_params)\n query_params = _get_flat_fields_from_params(flat_dependant.query_params)\n header_params = _get_flat_fields_from_params(flat_dependant.header_params)\n cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)\n return path_params + query_params + header_params + cookie_params", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_flat_params", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L204-L210", "start_line": 204, "end_line": 210} {"id": "fastapi/dependencies/utils.py::_get_signature::L213", "text": "# File: fastapi/dependencies/utils.py | Symbol: _get_signature\ndef _get_signature(call: Callable[..., Any]) -> inspect.Signature:\n try:\n signature = inspect.signature(call, eval_str=True)\n except NameError:\n # Handle type annotations with if TYPE_CHECKING, not used by FastAPI\n # e.g. dependency return types\n if sys.version_info >= (3, 14):\n from annotationlib import Format\n\n signature = inspect.signature(call, annotation_format=Format.FORWARDREF)\n else:\n signature = inspect.signature(call)\n return signature", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_get_signature", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L213-L225", "start_line": 213, "end_line": 225} {"id": "fastapi/dependencies/utils.py::get_typed_signature::L228", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_typed_signature\ndef get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:\n signature = _get_signature(call)\n unwrapped = inspect.unwrap(call)\n globalns = getattr(unwrapped, \"__globals__\", {})\n typed_params = [\n inspect.Parameter(\n name=param.name,\n kind=param.kind,\n default=param.default,\n annotation=get_typed_annotation(param.annotation, globalns),\n )\n for param in signature.parameters.values()\n ]\n typed_signature = inspect.Signature(typed_params)\n return typed_signature", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_typed_signature", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L228-L242", "start_line": 228, "end_line": 242} {"id": "fastapi/dependencies/utils.py::get_typed_annotation::L245", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_typed_annotation\ndef get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any:\n if isinstance(annotation, str):\n annotation = ForwardRef(annotation)\n annotation = evaluate_forwardref(annotation, globalns, globalns)\n if annotation is type(None):\n return None\n return annotation", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_typed_annotation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L245-L251", "start_line": 245, "end_line": 251} {"id": "fastapi/dependencies/utils.py::get_typed_return_annotation::L254", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_typed_return_annotation\ndef get_typed_return_annotation(call: Callable[..., Any]) -> Any:\n signature = _get_signature(call)\n unwrapped = inspect.unwrap(call)\n annotation = signature.return_annotation\n\n if annotation is inspect.Signature.empty:\n return None\n\n globalns = getattr(unwrapped, \"__globals__\", {})\n return get_typed_annotation(annotation, globalns)", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_typed_return_annotation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L254-L263", "start_line": 254, "end_line": 263} {"id": "fastapi/dependencies/utils.py::get_stream_item_type::L276", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_stream_item_type\ndef get_stream_item_type(annotation: Any) -> Any | None:\n origin = get_origin(annotation)\n if origin is not None and origin in _STREAM_ORIGINS:\n type_args = get_args(annotation)\n if type_args:\n return type_args[0]\n return Any\n return None", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_stream_item_type", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L276-L283", "start_line": 276, "end_line": 283} {"id": "fastapi/dependencies/utils.py::get_dependant::L286", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_dependant\ndef get_dependant(\n *,\n path: str,\n call: Callable[..., Any],\n name: str | None = None,\n own_oauth_scopes: list[str] | None = None,\n parent_oauth_scopes: list[str] | None = None,\n use_cache: bool = True,\n scope: Literal[\"function\", \"request\"] | None = None,\n) -> Dependant:\n dependant = Dependant(\n call=call,\n name=name,\n path=path,\n use_cache=use_cache,\n scope=scope,\n own_oauth_scopes=own_oauth_scopes,\n parent_oauth_scopes=parent_oauth_scopes,\n )\n current_scopes = (parent_oauth_scopes or []) + (own_oauth_scopes or [])\n path_param_names = get_path_param_names(path)\n endpoint_signature = get_typed_signature(call)\n signature_params = endpoint_signature.parameters\n for param_name, param in signature_params.items():\n is_path_param = param_name in path_param_names\n param_details = analyze_param(\n param_name=param_name,\n annotation=param.annotation,\n value=param.default,\n is_path_param=is_path_param,\n )\n if param_details.depends is not None:\n assert param_details.depends.dependency\n if (\n (dependant.is_gen_callable or dependant.is_async_gen_callable)\n and dependant.computed_scope == \"request\"\n and param_details.depends.scope == \"function\"\n ):\n assert dependant.call\n call_name = getattr(dependant.call, \"__name__\", \"\")\n raise DependencyScopeError(\n f'The dependency \"{call_name}\" has a scope of '\n '\"request\", it cannot depend on dependencies with scope \"function\".'\n )\n sub_own_oauth_scopes: list[str] = []\n if isinstance(param_details.depends, params.Security):\n if param_details.depends.scopes:\n sub_own_oauth_scopes = list(param_details.depends.scopes)\n sub_dependant = get_dependant(\n path=path,\n call=param_details.depends.dependency,\n name=param_name,\n own_oauth_scopes=sub_own_oauth_scopes,\n parent_oauth_scopes=current_scopes,\n use_cache=param_details.depends.use_cache,\n scope=param_details.depends.scope,\n )\n dependant.dependencies.append(sub_dependant)\n continue\n if add_non_field_param_to_dependency(\n param_name=param_name,\n type_annotation=param_details.type_annotation,\n dependant=dependant,\n ):\n assert param_details.field is None, (\n f\"Cannot specify multiple FastAPI annotations for {param_name!r}\"\n )\n continue\n assert param_details.field is not None\n if isinstance(param_details.field.field_info, params.Body):\n dependant.body_params.append(param_details.field)\n else:\n add_param_to_fields(field=param_details.field, dependant=dependant)\n return dependant", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_dependant", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L286-L359", "start_line": 286, "end_line": 359} {"id": "fastapi/dependencies/utils.py::add_non_field_param_to_dependency::L362", "text": "# File: fastapi/dependencies/utils.py | Symbol: add_non_field_param_to_dependency\ndef add_non_field_param_to_dependency(\n *, param_name: str, type_annotation: Any, dependant: Dependant\n) -> bool | None:\n if lenient_issubclass(type_annotation, Request):\n dependant.request_param_name = param_name\n return True\n elif lenient_issubclass(type_annotation, WebSocket):\n dependant.websocket_param_name = param_name\n return True\n elif lenient_issubclass(type_annotation, HTTPConnection):\n dependant.http_connection_param_name = param_name\n return True\n elif lenient_issubclass(type_annotation, Response):\n dependant.response_param_name = param_name\n return True\n elif lenient_issubclass(type_annotation, StarletteBackgroundTasks):\n dependant.background_tasks_param_name = param_name\n return True\n elif lenient_issubclass(type_annotation, SecurityScopes):\n dependant.security_scopes_param_name = param_name\n return True\n return None", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "add_non_field_param_to_dependency", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L362-L383", "start_line": 362, "end_line": 383} {"id": "fastapi/dependencies/utils.py::ParamDetails::L386", "text": "# File: fastapi/dependencies/utils.py | Symbol: ParamDetails\n@dataclass\nclass ParamDetails:\n type_annotation: Any\n depends: params.Depends | None\n field: ModelField | None", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "ParamDetails", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L386-L390", "start_line": 386, "end_line": 390} {"id": "fastapi/dependencies/utils.py::analyze_param::L393", "text": "# File: fastapi/dependencies/utils.py | Symbol: analyze_param\ndef analyze_param(\n *,\n param_name: str,\n annotation: Any,\n value: Any,\n is_path_param: bool,\n) -> ParamDetails:\n field_info = None\n depends = None\n type_annotation: Any = Any\n use_annotation: Any = Any\n if is_typealiastype(annotation):\n # unpack in case PEP 695 type syntax is used\n annotation = annotation.__value__\n if annotation is not inspect.Signature.empty:\n use_annotation = annotation\n type_annotation = annotation\n # Extract Annotated info\n if get_origin(use_annotation) is Annotated:\n annotated_args = get_args(annotation)\n type_annotation = annotated_args[0]\n fastapi_annotations = [\n arg\n for arg in annotated_args[1:]\n if isinstance(arg, (FieldInfo, params.Depends))\n ]\n fastapi_specific_annotations = [\n arg\n for arg in fastapi_annotations\n if isinstance(\n arg,\n (\n params.Param,\n params.Body,\n params.Depends,\n ),\n )\n ]\n if fastapi_specific_annotations:\n fastapi_annotation: FieldInfo | params.Depends | None = (\n fastapi_specific_annotations[-1]\n )\n else:\n fastapi_annotation = None\n # Set default for Annotated FieldInfo\n if isinstance(fastapi_annotation, FieldInfo):\n # Copy `field_info` because we mutate `field_info.default` below.\n field_info = copy_field_info(\n field_info=fastapi_annotation,\n annotation=use_annotation,\n )\n assert (\n field_info.default == Undefined or field_info.default == RequiredParam\n ), (\n f\"`{field_info.__class__.__name__}` default value cannot be set in\"\n f\" `Annotated` for {param_name!r}. Set the default value with `=` instead.\"\n )\n if value is not inspect.Signature.empty:\n assert not is_path_param, \"Path parameters cannot have default values\"\n field_info.default = value\n else:\n field_info.default = RequiredParam\n # Get Annotated Depends\n elif isinstance(fastapi_annotation, params.Depends):\n depends = fastapi_annotation\n # Get Depends from default value\n if isinstance(value, params.Depends):\n assert depends is None, (\n \"Cannot specify `Depends` in `Annotated` and default value\"\n f\" together for {param_name!r}\"\n )\n assert field_info is None, (\n \"Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a\"\n f\" default value together for {param_name!r}\"\n )\n depends = value\n # Get FieldInfo from default value\n elif isinstance(value, FieldInfo):\n assert field_info is None, (\n \"Cannot specify FastAPI annotations in `Annotated` and default value\"\n f\" together for {param_name!r}\"\n )\n field_info = value\n if isinstance(field_info, FieldInfo):\n field_info.annotation = type_annotation\n\n # Get Depends from type annotation\n if depends is not None and depends.dependency is None:\n # Copy `depends` before mutating it\n depends = copy(depends)\n depends = dataclasses.replace(depends, dependency=type_annotation)\n\n # Handle non-param type annotations like Request\n # Only apply special handling when there's no explicit Depends - if there's a Depends,\n # the dependency will be called and its return value used instead of the special injection\n if depends is None and lenient_issubclass(\n type_annotation,\n (\n Request,\n WebSocket,\n HTTPConnection,\n Response,\n StarletteBackgroundTasks,\n SecurityScopes,\n ),\n ):\n assert field_info is None, (\n f\"Cannot specify FastAPI annotation for type {type_annotation!r}\"\n )\n # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value\n elif field_info is None and depends is None:\n default_value = value if value is not inspect.Signature.empty else RequiredParam\n if is_path_param:\n # We might check here that `default_value is RequiredParam`, but the fact is that the same\n # parameter might sometimes be a path parameter and sometimes not. See\n # `tests/test_infer_param_optionality.py` for an example.\n field_info = params.Path(annotation=use_annotation)\n elif is_uploadfile_or_nonable_uploadfile_annotation(\n type_annotation\n ) or is_uploadfile_sequence_annotation(type_annotation):\n field_info = params.File(annotation=use_annotation, default=default_value)\n elif not field_annotation_is_scalar(annotation=type_annotation):\n field_info = params.Body(annotation=use_annotation, default=default_value)\n else:\n field_info = params.Query(annotation=use_annotation, default=default_value)\n\n field = None\n # It's a field_info, not a dependency\n if field_info is not None:\n # Handle field_info.in_\n if is_path_param:\n assert isinstance(field_info, params.Path), (\n f\"Cannot use `{field_info.__class__.__name__}` for path param\"\n f\" {param_name!r}\"\n )\n elif (\n isinstance(field_info, params.Param)\n and getattr(field_info, \"in_\", None) is None\n ):\n field_info.in_ = params.ParamTypes.query\n use_annotation_from_field_info = use_annotation\n if isinstance(field_info, params.Form):\n ensure_multipart_is_installed()\n if not field_info.alias and getattr(field_info, \"convert_underscores\", None):\n alias = param_name.replace(\"_\", \"-\")\n else:\n alias = field_info.alias or param_name\n field_info.alias = alias\n field = create_model_field(\n name=param_name,\n type_=use_annotation_from_field_info,\n default=field_info.default,\n alias=alias,\n field_info=field_info,\n )\n if is_path_param:\n assert is_scalar_field(field=field), (\n \"Path params must be of one of the supported types\"\n )\n elif isinstance(field_info, params.Query):\n assert (\n is_scalar_field(field)\n or field_annotation_is_scalar_sequence(field.field_info.annotation)\n or lenient_issubclass(field.field_info.annotation, BaseModel)\n ), f\"Query parameter {param_name!r} must be one of the supported types\"\n\n return ParamDetails(type_annotation=type_annotation, depends=depends, field=field)", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "analyze_param", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L393-L559", "start_line": 393, "end_line": 559} {"id": "fastapi/dependencies/utils.py::add_param_to_fields::L562", "text": "# File: fastapi/dependencies/utils.py | Symbol: add_param_to_fields\ndef add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None:\n field_info = field.field_info\n field_info_in = getattr(field_info, \"in_\", None)\n if field_info_in == params.ParamTypes.path:\n dependant.path_params.append(field)\n elif field_info_in == params.ParamTypes.query:\n dependant.query_params.append(field)\n elif field_info_in == params.ParamTypes.header:\n dependant.header_params.append(field)\n else:\n assert field_info_in == params.ParamTypes.cookie, (\n f\"non-body parameters must be in path, query, header or cookie: {field.name}\"\n )\n dependant.cookie_params.append(field)", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "add_param_to_fields", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L562-L575", "start_line": 562, "end_line": 575} {"id": "fastapi/dependencies/utils.py::_solve_generator::L578", "text": "# File: fastapi/dependencies/utils.py | Symbol: _solve_generator\nasync def _solve_generator(\n *, dependant: Dependant, stack: AsyncExitStack, sub_values: dict[str, Any]\n) -> Any:\n assert dependant.call\n if dependant.is_async_gen_callable:\n cm = asynccontextmanager(dependant.call)(**sub_values)\n elif dependant.is_gen_callable:\n cm = contextmanager_in_threadpool(contextmanager(dependant.call)(**sub_values))\n return await stack.enter_async_context(cm)", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_solve_generator", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L578-L586", "start_line": 578, "end_line": 586} {"id": "fastapi/dependencies/utils.py::SolvedDependency::L589", "text": "# File: fastapi/dependencies/utils.py | Symbol: SolvedDependency\n@dataclass\nclass SolvedDependency:\n values: dict[str, Any]\n errors: list[Any]\n background_tasks: StarletteBackgroundTasks | None\n response: Response\n dependency_cache: dict[DependencyCacheKey, Any]", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "SolvedDependency", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L589-L595", "start_line": 589, "end_line": 595} {"id": "fastapi/dependencies/utils.py::solve_dependencies::L598", "text": "# File: fastapi/dependencies/utils.py | Symbol: solve_dependencies\nasync def solve_dependencies(\n *,\n request: Request | WebSocket,\n dependant: Dependant,\n body: dict[str, Any] | FormData | bytes | None = None,\n background_tasks: StarletteBackgroundTasks | None = None,\n response: Response | None = None,\n dependency_overrides_provider: Any | None = None,\n dependency_cache: dict[DependencyCacheKey, Any] | None = None,\n # TODO: remove this parameter later, no longer used, not removing it yet as some\n # people might be monkey patching this function (although that's not supported)\n async_exit_stack: AsyncExitStack,\n embed_body_fields: bool,\n) -> SolvedDependency:\n request_astack = request.scope.get(\"fastapi_inner_astack\")\n assert isinstance(request_astack, AsyncExitStack), (\n \"fastapi_inner_astack not found in request scope\"\n )\n function_astack = request.scope.get(\"fastapi_function_astack\")\n assert isinstance(function_astack, AsyncExitStack), (\n \"fastapi_function_astack not found in request scope\"\n )\n values: dict[str, Any] = {}\n errors: list[Any] = []\n if response is None:\n response = Response()\n del response.headers[\"content-length\"]\n response.status_code = None # type: ignore\n if dependency_cache is None:\n dependency_cache = {}\n for sub_dependant in dependant.dependencies:\n sub_dependant.call = cast(Callable[..., Any], sub_dependant.call)\n call = sub_dependant.call\n use_sub_dependant = sub_dependant\n if (\n dependency_overrides_provider\n and dependency_overrides_provider.dependency_overrides\n ):\n original_call = sub_dependant.call\n call = getattr(\n dependency_overrides_provider, \"dependency_overrides\", {}\n ).get(original_call, original_call)\n use_path: str = sub_dependant.path # type: ignore\n use_sub_dependant = get_dependant(\n path=use_path,\n call=call,\n name=sub_dependant.name,\n parent_oauth_scopes=sub_dependant.oauth_scopes,\n scope=sub_dependant.scope,\n )\n\n solved_result = await solve_dependencies(\n request=request,\n dependant=use_sub_dependant,\n body=body,\n background_tasks=background_tasks,\n response=response,\n dependency_overrides_provider=dependency_overrides_provider,\n dependency_cache=dependency_cache,\n async_exit_stack=async_exit_stack,\n embed_body_fields=embed_body_fields,\n )\n background_tasks = solved_result.background_tasks\n if solved_result.errors:\n errors.extend(solved_result.errors)\n continue\n if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache:\n solved = dependency_cache[sub_dependant.cache_key]\n elif (\n use_sub_dependant.is_gen_callable or use_sub_dependant.is_async_gen_callable\n ):\n use_astack = request_astack\n if sub_dependant.scope == \"function\":\n use_astack = function_astack\n solved = await _solve_generator(\n dependant=use_sub_dependant,\n stack=use_astack,\n sub_values=solved_result.values,\n )\n elif use_sub_dependant.is_coroutine_callable:\n solved = await call(**solved_result.values)\n else:\n solved = await run_in_threadpool(call, **solved_result.values)\n if sub_dependant.name is not None:\n values[sub_dependant.name] = solved\n if sub_dependant.cache_key not in dependency_cache:\n dependency_cache[sub_dependant.cache_key] = solved\n path_values, path_errors = request_params_to_args(\n dependant.path_params, request.path_params\n )\n query_values, query_errors = request_params_to_args(\n dependant.query_params, request.query_params\n )\n header_values, header_errors = request_params_to_args(\n dependant.header_params, request.headers\n )\n cookie_values, cookie_errors = request_params_to_args(\n dependant.cookie_params, request.cookies\n )\n values.update(path_values)\n values.update(query_values)\n values.update(header_values)\n values.update(cookie_values)\n errors += path_errors + query_errors + header_errors + cookie_errors\n if dependant.body_params:\n (\n body_values,\n body_errors,\n ) = await request_body_to_args( # body_params checked above\n body_fields=dependant.body_params,\n received_body=body,\n embed_body_fields=embed_body_fields,\n )\n values.update(body_values)\n errors.extend(body_errors)\n if dependant.http_connection_param_name:\n values[dependant.http_connection_param_name] = request\n if dependant.request_param_name and isinstance(request, Request):\n values[dependant.request_param_name] = request\n elif dependant.websocket_param_name and isinstance(request, WebSocket):\n values[dependant.websocket_param_name] = request\n if dependant.background_tasks_param_name:\n if background_tasks is None:\n background_tasks = BackgroundTasks()\n values[dependant.background_tasks_param_name] = background_tasks\n if dependant.response_param_name:\n values[dependant.response_param_name] = response\n if dependant.security_scopes_param_name:\n values[dependant.security_scopes_param_name] = SecurityScopes(\n scopes=dependant.oauth_scopes\n )\n return SolvedDependency(\n values=values,\n errors=errors,\n background_tasks=background_tasks,\n response=response,\n dependency_cache=dependency_cache,\n )", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "solve_dependencies", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L598-L735", "start_line": 598, "end_line": 735} {"id": "fastapi/dependencies/utils.py::_validate_value_with_model_field::L738", "text": "# File: fastapi/dependencies/utils.py | Symbol: _validate_value_with_model_field\ndef _validate_value_with_model_field(\n *, field: ModelField, value: Any, values: dict[str, Any], loc: tuple[str, ...]\n) -> tuple[Any, list[Any]]:\n if value is None:\n if field.field_info.is_required():\n return None, [get_missing_field_error(loc=loc)]\n else:\n return deepcopy(field.default), []\n return field.validate(value, values, loc=loc)", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_validate_value_with_model_field", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L738-L746", "start_line": 738, "end_line": 746} {"id": "fastapi/dependencies/utils.py::_is_json_field::L749", "text": "# File: fastapi/dependencies/utils.py | Symbol: _is_json_field\ndef _is_json_field(field: ModelField) -> bool:\n return any(type(item) is Json for item in field.field_info.metadata)", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_is_json_field", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L749-L750", "start_line": 749, "end_line": 750} {"id": "fastapi/dependencies/utils.py::_get_multidict_value::L753", "text": "# File: fastapi/dependencies/utils.py | Symbol: _get_multidict_value\ndef _get_multidict_value(\n field: ModelField, values: Mapping[str, Any], alias: str | None = None\n) -> Any:\n alias = alias or get_validation_alias(field)\n if (\n (not _is_json_field(field))\n and field_annotation_is_sequence(field.field_info.annotation)\n and isinstance(values, (ImmutableMultiDict, Headers))\n ):\n value = values.getlist(alias)\n else:\n value = values.get(alias, None)\n if (\n value is None\n or (\n isinstance(field.field_info, params.Form)\n and isinstance(value, str) # For type checks\n and value == \"\"\n )\n or (\n field_annotation_is_sequence(field.field_info.annotation)\n and len(value) == 0\n )\n ):\n if field.field_info.is_required():\n return\n else:\n return deepcopy(field.default)\n return value", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_get_multidict_value", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L753-L781", "start_line": 753, "end_line": 781} {"id": "fastapi/dependencies/utils.py::request_params_to_args::L784", "text": "# File: fastapi/dependencies/utils.py | Symbol: request_params_to_args\ndef request_params_to_args(\n fields: Sequence[ModelField],\n received_params: Mapping[str, Any] | QueryParams | Headers,\n) -> tuple[dict[str, Any], list[Any]]:\n values: dict[str, Any] = {}\n errors: list[dict[str, Any]] = []\n\n if not fields:\n return values, errors\n\n first_field = fields[0]\n fields_to_extract = fields\n single_not_embedded_field = False\n default_convert_underscores = True\n if len(fields) == 1 and lenient_issubclass(\n first_field.field_info.annotation, BaseModel\n ):\n fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)\n single_not_embedded_field = True\n # If headers are in a Pydantic model, the way to disable convert_underscores\n # would be with Header(convert_underscores=False) at the Pydantic model level\n default_convert_underscores = getattr(\n first_field.field_info, \"convert_underscores\", True\n )\n\n params_to_process: dict[str, Any] = {}\n\n processed_keys = set()\n\n for field in fields_to_extract:\n alias = None\n if isinstance(received_params, Headers):\n # Handle fields extracted from a Pydantic Model for a header, each field\n # doesn't have a FieldInfo of type Header with the default convert_underscores=True\n convert_underscores = getattr(\n field.field_info, \"convert_underscores\", default_convert_underscores\n )\n if convert_underscores:\n alias = get_validation_alias(field)\n if alias == field.name:\n alias = alias.replace(\"_\", \"-\")\n value = _get_multidict_value(field, received_params, alias=alias)\n if value is not None:\n params_to_process[get_validation_alias(field)] = value\n processed_keys.add(alias or get_validation_alias(field))\n # For headers with convert_underscores=True, mark both the converted\n # header name and the original field alias as processed to avoid\n # accepting the original alias as an extra header.\n processed_keys.add(get_validation_alias(field))\n\n for key in received_params.keys():\n if key not in processed_keys:\n if isinstance(received_params, (ImmutableMultiDict, Headers)):\n value = received_params.getlist(key)\n if isinstance(value, list) and (len(value) == 1):\n params_to_process[key] = value[0]\n else:\n params_to_process[key] = value\n else:\n params_to_process[key] = received_params.get(key)\n\n if single_not_embedded_field:\n field_info = first_field.field_info\n assert isinstance(field_info, params.Param), (\n \"Params must be subclasses of Param\"\n )\n loc: tuple[str, ...] = (field_info.in_.value,)\n v_, errors_ = _validate_value_with_model_field(\n field=first_field, value=params_to_process, values=values, loc=loc\n )\n return {first_field.name: v_}, errors_\n\n for field in fields:\n value = _get_multidict_value(field, received_params)\n field_info = field.field_info\n assert isinstance(field_info, params.Param), (\n \"Params must be subclasses of Param\"\n )\n loc = (field_info.in_.value, get_validation_alias(field))\n v_, errors_ = _validate_value_with_model_field(\n field=field, value=value, values=values, loc=loc\n )\n if errors_:\n errors.extend(errors_)\n else:\n values[field.name] = v_\n return values, errors", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "request_params_to_args", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L784-L870", "start_line": 784, "end_line": 870} {"id": "fastapi/dependencies/utils.py::is_union_of_base_models::L873", "text": "# File: fastapi/dependencies/utils.py | Symbol: is_union_of_base_models\ndef is_union_of_base_models(field_type: Any) -> bool:\n \"\"\"Check if field type is a Union where all members are BaseModel subclasses.\"\"\"\n from fastapi.types import UnionType\n\n origin = get_origin(field_type)\n\n # Check if it's a Union type (covers both typing.Union and types.UnionType in Python 3.10+)\n if origin is not Union and origin is not UnionType:\n return False\n\n union_args = get_args(field_type)\n\n for arg in union_args:\n if not lenient_issubclass(arg, BaseModel):\n return False\n\n return True", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "is_union_of_base_models", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L873-L889", "start_line": 873, "end_line": 889} {"id": "fastapi/dependencies/utils.py::_should_embed_body_fields::L892", "text": "# File: fastapi/dependencies/utils.py | Symbol: _should_embed_body_fields\ndef _should_embed_body_fields(fields: list[ModelField]) -> bool:\n if not fields:\n return False\n # More than one dependency could have the same field, it would show up as multiple\n # fields but it's the same one, so count them by name\n body_param_names_set = {field.name for field in fields}\n # A top level field has to be a single field, not multiple\n if len(body_param_names_set) > 1:\n return True\n first_field = fields[0]\n # If it explicitly specifies it is embedded, it has to be embedded\n if getattr(first_field.field_info, \"embed\", None):\n return True\n # If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level\n # otherwise it has to be embedded, so that the key value pair can be extracted\n if (\n isinstance(first_field.field_info, params.Form)\n and not lenient_issubclass(first_field.field_info.annotation, BaseModel)\n and not is_union_of_base_models(first_field.field_info.annotation)\n ):\n return True\n return False", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_should_embed_body_fields", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L892-L913", "start_line": 892, "end_line": 913} {"id": "fastapi/dependencies/utils.py::_extract_form_body::L916", "text": "# File: fastapi/dependencies/utils.py | Symbol: _extract_form_body\nasync def _extract_form_body(\n body_fields: list[ModelField],\n received_body: FormData,\n) -> dict[str, Any]:\n values = {}\n\n for field in body_fields:\n value = _get_multidict_value(field, received_body)\n field_info = field.field_info\n if (\n isinstance(field_info, params.File)\n and is_bytes_or_nonable_bytes_annotation(field.field_info.annotation)\n and isinstance(value, UploadFile)\n ):\n value = await value.read()\n elif (\n is_bytes_sequence_annotation(field.field_info.annotation)\n and isinstance(field_info, params.File)\n and value_is_sequence(value)\n ):\n # For types\n assert isinstance(value, sequence_types)\n results: list[bytes | str] = []\n for sub_value in value:\n results.append(await sub_value.read())\n value = serialize_sequence_value(field=field, value=results)\n if value is not None:\n values[get_validation_alias(field)] = value\n field_aliases = {get_validation_alias(field) for field in body_fields}\n for key in received_body.keys():\n if key not in field_aliases:\n param_values = received_body.getlist(key)\n if len(param_values) == 1:\n values[key] = param_values[0]\n else:\n values[key] = param_values\n return values", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "_extract_form_body", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L916-L952", "start_line": 916, "end_line": 952} {"id": "fastapi/dependencies/utils.py::request_body_to_args::L955", "text": "# File: fastapi/dependencies/utils.py | Symbol: request_body_to_args\nasync def request_body_to_args(\n body_fields: list[ModelField],\n received_body: dict[str, Any] | FormData | bytes | None,\n embed_body_fields: bool,\n) -> tuple[dict[str, Any], list[dict[str, Any]]]:\n values: dict[str, Any] = {}\n errors: list[dict[str, Any]] = []\n assert body_fields, \"request_body_to_args() should be called with fields\"\n single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields\n first_field = body_fields[0]\n body_to_process = received_body\n\n fields_to_extract: list[ModelField] = body_fields\n\n if (\n single_not_embedded_field\n and lenient_issubclass(first_field.field_info.annotation, BaseModel)\n and isinstance(received_body, FormData)\n ):\n fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)\n\n if isinstance(received_body, FormData):\n body_to_process = await _extract_form_body(fields_to_extract, received_body)\n\n if single_not_embedded_field:\n loc: tuple[str, ...] = (\"body\",)\n v_, errors_ = _validate_value_with_model_field(\n field=first_field, value=body_to_process, values=values, loc=loc\n )\n return {first_field.name: v_}, errors_\n for field in body_fields:\n loc = (\"body\", get_validation_alias(field))\n value: Any | None = None\n if body_to_process is not None and not isinstance(body_to_process, bytes):\n try:\n value = body_to_process.get(get_validation_alias(field))\n # If the received body is a list, not a dict\n except AttributeError:\n errors.append(get_missing_field_error(loc))\n continue\n v_, errors_ = _validate_value_with_model_field(\n field=field, value=value, values=values, loc=loc\n )\n if errors_:\n errors.extend(errors_)\n else:\n values[field.name] = v_\n return values, errors", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "request_body_to_args", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L955-L1002", "start_line": 955, "end_line": 1002} {"id": "fastapi/dependencies/utils.py::get_body_field::L1005", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_body_field\ndef get_body_field(\n *, flat_dependant: Dependant, name: str, embed_body_fields: bool\n) -> ModelField | None:\n \"\"\"\n Get a ModelField representing the request body for a path operation, combining\n all body parameters into a single field if necessary.\n\n Used to check if it's form data (with `isinstance(body_field, params.Form)`)\n or JSON and to generate the JSON Schema for a request body.\n\n This is **not** used to validate/parse the request body, that's done with each\n individual body parameter.\n \"\"\"\n if not flat_dependant.body_params:\n return None\n first_param = flat_dependant.body_params[0]\n if not embed_body_fields:\n return first_param\n model_name = \"Body_\" + name\n BodyModel = create_body_model(\n fields=flat_dependant.body_params, model_name=model_name\n )\n required = any(\n True for f in flat_dependant.body_params if f.field_info.is_required()\n )\n BodyFieldInfo_kwargs: dict[str, Any] = {\n \"annotation\": BodyModel,\n \"alias\": \"body\",\n }\n if not required:\n BodyFieldInfo_kwargs[\"default\"] = None\n if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params):\n BodyFieldInfo: type[params.Body] = params.File\n elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params):\n BodyFieldInfo = params.Form\n else:\n BodyFieldInfo = params.Body\n\n body_param_media_types = [\n f.field_info.media_type\n for f in flat_dependant.body_params\n if isinstance(f.field_info, params.Body)\n ]\n if len(set(body_param_media_types)) == 1:\n BodyFieldInfo_kwargs[\"media_type\"] = body_param_media_types[0]\n final_field = create_model_field(\n name=\"body\",\n type_=BodyModel,\n alias=\"body\",\n field_info=BodyFieldInfo(**BodyFieldInfo_kwargs),\n )\n return final_field", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_body_field", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L1005-L1056", "start_line": 1005, "end_line": 1056} {"id": "fastapi/dependencies/utils.py::get_validation_alias::L1059", "text": "# File: fastapi/dependencies/utils.py | Symbol: get_validation_alias\ndef get_validation_alias(field: ModelField) -> str:\n va = getattr(field, \"validation_alias\", None)\n return va or field.alias", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "get_validation_alias", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L1059-L1061", "start_line": 1059, "end_line": 1061} {"id": "fastapi/dependencies/utils.py::", "text": "# File: fastapi/dependencies/utils.py | Symbol: \nimport dataclasses\nimport inspect\nimport sys\nfrom collections.abc import (\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Callable,\n Generator,\n Iterable,\n Iterator,\n Mapping,\n Sequence,\n)\nfrom contextlib import AsyncExitStack, contextmanager\nfrom copy import copy, deepcopy\nfrom dataclasses import dataclass\nfrom typing import (\n Annotated,\n Any,\n ForwardRef,\n Literal,\n Union,\n cast,\n get_args,\n get_origin,\n)\nfrom fastapi import params\nfrom fastapi._compat import (\n ModelField,\n RequiredParam,\n Undefined,\n copy_field_info,\n create_body_model,\n evaluate_forwardref,\n field_annotation_is_scalar,\n field_annotation_is_scalar_sequence,\n field_annotation_is_sequence,\n get_cached_model_fields,\n get_missing_field_error,\n is_bytes_or_nonable_bytes_annotation,\n is_bytes_sequence_annotation,\n is_scalar_field,\n is_uploadfile_or_nonable_uploadfile_annotation,\n is_uploadfile_sequence_annotation,\n lenient_issubclass,\n sequence_types,\n serialize_sequence_value,\n value_is_sequence,\n)\nfrom fastapi.background import BackgroundTasks\nfrom fastapi.concurrency import (\n asynccontextmanager,\n contextmanager_in_threadpool,\n)\nfrom fastapi.dependencies.models import Dependant\nfrom fastapi.exceptions import DependencyScopeError\nfrom fastapi.logger import logger\nfrom fastapi.security.oauth2 import SecurityScopes\nfrom fastapi.types import DependencyCacheKey\nfrom fastapi.utils import create_model_field, get_path_param_names\nfrom pydantic import BaseModel, Json\nfrom pydantic.fields import FieldInfo\nfrom starlette.background import BackgroundTasks as StarletteBackgroundTasks\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import (\n FormData,\n Headers,\n ImmutableMultiDict,\n QueryParams,\n UploadFile,\n)\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.responses import Response\nfrom starlette.websockets import WebSocket\nfrom typing_inspection.typing_objects import is_typealiastype\nmultipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n 'You can install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\nmultipart_incorrect_install_error = (\n 'Form data requires \"python-multipart\" to be installed. '\n 'It seems you installed \"multipart\" instead. \\n'\n 'You can remove \"multipart\" with: \\n\\n'\n \"pip uninstall multipart\\n\\n\"\n 'And then install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\n_STREAM_ORIGINS = {\n AsyncIterable,\n AsyncIterator,\n AsyncGenerator,\n Iterable,\n Iterator,\n Generator,\n}", "source_type": "code", "path": "fastapi/dependencies/utils.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L1-L273", "start_line": 1, "end_line": 273} {"id": "fastapi/encoders.py::isoformat::L53", "text": "# File: fastapi/encoders.py | Symbol: isoformat\ndef isoformat(o: datetime.date | datetime.time) -> str:\n return o.isoformat()", "source_type": "code", "path": "fastapi/encoders.py", "symbol": "isoformat", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/encoders.py#L53-L54", "start_line": 53, "end_line": 54} {"id": "fastapi/encoders.py::decimal_encoder::L59", "text": "# File: fastapi/encoders.py | Symbol: decimal_encoder\ndef decimal_encoder(dec_value: Decimal) -> int | float:\n \"\"\"\n Encodes a Decimal as int if there's no exponent, otherwise float\n\n This is useful when we use ConstrainedDecimal to represent Numeric(x,0)\n where an integer (but not int typed) is used. Encoding this as a float\n results in failed round-tripping between encode and parse.\n Our Id type is a prime example of this.\n\n >>> decimal_encoder(Decimal(\"1.0\"))\n 1.0\n\n >>> decimal_encoder(Decimal(\"1\"))\n 1\n\n >>> decimal_encoder(Decimal(\"NaN\"))\n nan\n \"\"\"\n exponent = dec_value.as_tuple().exponent\n if isinstance(exponent, int) and exponent >= 0:\n return int(dec_value)\n else:\n return float(dec_value)", "source_type": "code", "path": "fastapi/encoders.py", "symbol": "decimal_encoder", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/encoders.py#L59-L81", "start_line": 59, "end_line": 81} {"id": "fastapi/encoders.py::generate_encoders_by_class_tuples::L115", "text": "# File: fastapi/encoders.py | Symbol: generate_encoders_by_class_tuples\ndef generate_encoders_by_class_tuples(\n type_encoder_map: dict[Any, Callable[[Any], Any]],\n) -> dict[Callable[[Any], Any], tuple[Any, ...]]:\n encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict(\n tuple\n )\n for type_, encoder in type_encoder_map.items():\n encoders_by_class_tuples[encoder] += (type_,)\n return encoders_by_class_tuples", "source_type": "code", "path": "fastapi/encoders.py", "symbol": "generate_encoders_by_class_tuples", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/encoders.py#L115-L123", "start_line": 115, "end_line": 123} {"id": "fastapi/encoders.py::jsonable_encoder::L129", "text": "# File: fastapi/encoders.py | Symbol: jsonable_encoder\ndef jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n include: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Pydantic's `include` parameter, passed to Pydantic models to set the\n fields to include.\n \"\"\"\n ),\n ] = None,\n exclude: Annotated[\n IncEx | None,\n Doc(\n \"\"\"\n Pydantic's `exclude` parameter, passed to Pydantic models to set the\n fields to exclude.\n \"\"\"\n ),\n ] = None,\n by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `by_alias` parameter, passed to Pydantic models to define if\n the output should use the alias names (when provided) or the Python\n attribute names. In an API, if you set an alias, it's probably because you\n want to use it in the result, so you probably want to leave this set to\n `True`.\n \"\"\"\n ),\n ] = True,\n exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_unset` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that were not explicitly\n set (and that only had their default values).\n \"\"\"\n ),\n ] = False,\n exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that had the same default\n value, even when they were explicitly set.\n \"\"\"\n ),\n ] = False,\n exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_none` parameter, passed to Pydantic models to define\n if it should exclude from the output any fields that have a `None` value.\n \"\"\"\n ),\n ] = False,\n custom_encoder: Annotated[\n dict[Any, Callable[[Any], Any]] | None,\n Doc(\n \"\"\"\n Pydantic's `custom_encoder` parameter, passed to Pydantic models to define\n a custom encoder.\n \"\"\"\n ),\n ] = None,\n sqlalchemy_safe: Annotated[\n bool,\n Doc(\n \"\"\"\n Exclude from the output any fields that start with the name `_sa`.\n\n This is mainly a hack for compatibility with SQLAlchemy objects, they\n store internal SQLAlchemy-specific state in attributes named with `_sa`,\n and those objects can't (and shouldn't be) serialized to JSON.\n \"\"\"\n ),\n ] = True,\n) -> Any:\n \"\"\"\n Convert any object to something that can be encoded in JSON.\n\n This is used internally by FastAPI to make sure anything you return can be\n encoded as JSON before it is sent to the client.\n\n You can also use it yourself, for example to convert objects before saving them\n in a database that supports only JSON.\n\n Read more about it in the\n [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).\n \"\"\"\n custom_encoder = custom_encoder or {}\n if custom_encoder:\n if type(obj) in custom_encoder:\n return custom_encoder[type(obj)](obj)\n else:\n for encoder_type, encoder_instance in custom_encoder.items():\n if isinstance(obj, encoder_type):\n return encoder_instance(obj)\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include) # type: ignore[assignment] # ty: ignore[invalid-assignment]\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude) # type: ignore[assignment] # ty: ignore[invalid-assignment]\n if isinstance(obj, BaseModel):\n obj_dict = obj.model_dump(\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if dataclasses.is_dataclass(obj):\n assert not isinstance(obj, type)\n obj_dict = dataclasses.asdict(obj)\n return jsonable_encoder(\n obj_dict,\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 custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if isinstance(obj, PydanticUndefinedType):\n return None\n if isinstance(obj, dict):\n encoded_dict = {}\n allowed_keys = set(obj.keys())\n if include is not None:\n allowed_keys &= set(include)\n if exclude is not None:\n allowed_keys -= set(exclude)\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and key in allowed_keys\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n encoded_value = jsonable_encoder(\n value,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n encoded_dict[encoded_key] = encoded_value\n return encoded_dict\n if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)):\n encoded_list = []\n for item in obj:\n encoded_list.append(\n jsonable_encoder(\n item,\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 custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n )\n return encoded_list\n\n if type(obj) in ENCODERS_BY_TYPE:\n return ENCODERS_BY_TYPE[type(obj)](obj)\n for encoder, classes_tuple in encoders_by_class_tuples.items():\n if isinstance(obj, classes_tuple):\n return encoder(obj)\n if is_pydantic_v1_model_instance(obj):\n raise PydanticV1NotSupportedError(\n \"pydantic.v1 models are no longer supported by FastAPI.\"\n f\" Please update the model {obj!r}.\"\n )\n try:\n data = dict(obj)\n except Exception as e:\n errors: list[Exception] = []\n errors.append(e)\n try:\n data = vars(obj)\n except Exception as e:\n errors.append(e)\n raise ValueError(errors) from e\n return jsonable_encoder(\n data,\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 custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )", "source_type": "code", "path": "fastapi/encoders.py", "symbol": "jsonable_encoder", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/encoders.py#L129-L364", "start_line": 129, "end_line": 364} {"id": "fastapi/encoders.py::", "text": "# File: fastapi/encoders.py | Symbol: \nimport dataclasses\nimport datetime\nfrom collections import defaultdict, deque\nfrom collections.abc import Callable\nfrom decimal import Decimal\nfrom enum import Enum\nfrom ipaddress import (\n IPv4Address,\n IPv4Interface,\n IPv4Network,\n IPv6Address,\n IPv6Interface,\n IPv6Network,\n)\nfrom pathlib import Path, PurePath\nfrom re import Pattern\nfrom types import GeneratorType\nfrom typing import Annotated, Any\nfrom uuid import UUID\nfrom annotated_doc import Doc\nfrom fastapi.exceptions import PydanticV1NotSupportedError\nfrom fastapi.types import IncEx\nfrom pydantic import BaseModel\nfrom pydantic.networks import AnyUrl, NameEmail\nfrom pydantic.types import SecretBytes, SecretStr\nfrom pydantic_core import PydanticUndefinedType\nfrom ._compat import (\n Url,\n is_pydantic_v1_model_instance,\n)\ntry:\n # pydantic.color.Color is deprecated since v2.0b3, but supporting for bwd-compat\n from pydantic.color import Color # ty: ignore[deprecated]\nexcept ImportError: # pragma: no cover\n class Color: # type: ignore[no-redef]\n pass\ntry:\n # Supporting the new Color format for newer versions of Pydantic\n from pydantic_extra_types.color import Color as PyExtraColor\nexcept ImportError: # pragma: no cover\n class PyExtraColor: # type: ignore[no-redef]\n pass\n# Taken from Pydantic v1 as is\n# Adapted from Pydantic v1\n# TODO: pv2 should this return strings instead?\nENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = {\n bytes: lambda o: o.decode(),\n Color: str,\n PyExtraColor: str,\n datetime.date: isoformat,\n datetime.datetime: isoformat,\n datetime.time: isoformat,\n datetime.timedelta: lambda td: td.total_seconds(),\n Decimal: decimal_encoder,\n Enum: lambda o: o.value,\n frozenset: list,\n deque: list,\n GeneratorType: list,\n IPv4Address: str,\n IPv4Interface: str,\n IPv4Network: str,\n IPv6Address: str,\n IPv6Interface: str,\n IPv6Network: str,\n NameEmail: str,\n Path: str,\n Pattern: lambda o: o.pattern,\n SecretBytes: str,\n SecretStr: str,\n set: list,\n UUID: str,\n Url: str,\n AnyUrl: str,\n}\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)", "source_type": "code", "path": "fastapi/encoders.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/encoders.py#L1-L126", "start_line": 1, "end_line": 126} {"id": "fastapi/exception_handlers.py::http_exception_handler::L11", "text": "# File: fastapi/exception_handlers.py | Symbol: http_exception_handler\nasync def http_exception_handler(request: Request, exc: HTTPException) -> Response:\n headers = getattr(exc, \"headers\", None)\n if not is_body_allowed_for_status_code(exc.status_code):\n return Response(status_code=exc.status_code, headers=headers)\n return JSONResponse(\n {\"detail\": exc.detail}, status_code=exc.status_code, headers=headers\n )", "source_type": "code", "path": "fastapi/exception_handlers.py", "symbol": "http_exception_handler", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exception_handlers.py#L11-L17", "start_line": 11, "end_line": 17} {"id": "fastapi/exception_handlers.py::request_validation_exception_handler::L20", "text": "# File: fastapi/exception_handlers.py | Symbol: request_validation_exception_handler\nasync def request_validation_exception_handler(\n request: Request, exc: RequestValidationError\n) -> JSONResponse:\n return JSONResponse(\n status_code=422,\n content={\"detail\": jsonable_encoder(exc.errors())},\n )", "source_type": "code", "path": "fastapi/exception_handlers.py", "symbol": "request_validation_exception_handler", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exception_handlers.py#L20-L26", "start_line": 20, "end_line": 26} {"id": "fastapi/exception_handlers.py::websocket_request_validation_exception_handler::L29", "text": "# File: fastapi/exception_handlers.py | Symbol: websocket_request_validation_exception_handler\nasync def websocket_request_validation_exception_handler(\n websocket: WebSocket, exc: WebSocketRequestValidationError\n) -> None:\n await websocket.close(\n code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())\n )", "source_type": "code", "path": "fastapi/exception_handlers.py", "symbol": "websocket_request_validation_exception_handler", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exception_handlers.py#L29-L34", "start_line": 29, "end_line": 34} {"id": "fastapi/exception_handlers.py::", "text": "# File: fastapi/exception_handlers.py | Symbol: \nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError\nfrom fastapi.utils import is_body_allowed_for_status_code\nfrom fastapi.websockets import WebSocket\nfrom starlette.exceptions import HTTPException\nfrom starlette.requests import Request\nfrom starlette.responses import JSONResponse, Response\nfrom starlette.status import WS_1008_POLICY_VIOLATION", "source_type": "code", "path": "fastapi/exception_handlers.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exception_handlers.py#L1-L8", "start_line": 1, "end_line": 8} {"id": "fastapi/exceptions.py::EndpointContext::L10", "text": "# File: fastapi/exceptions.py | Symbol: EndpointContext\nclass EndpointContext(TypedDict, total=False):\n function: str\n path: str\n file: str\n line: int", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "EndpointContext", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L10-L14", "start_line": 10, "end_line": 14} {"id": "fastapi/exceptions.py::HTTPException::L17", "text": "# File: fastapi/exceptions.py | Symbol: HTTPException\nclass HTTPException(StarletteHTTPException):\n \"\"\"\n An HTTP exception you can raise in your own code to show errors to the client.\n\n This is for client errors, invalid authentication, invalid data, etc. Not for server\n errors in your code.\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, HTTPException\n\n app = FastAPI()\n\n items = {\"foo\": \"The Foo Wrestlers\"}\n\n\n @app.get(\"/items/{item_id}\")\n async def read_item(item_id: str):\n if item_id not in items:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return {\"item\": items[item_id]}\n ```\n \"\"\"\n\n def __init__(\n self,\n status_code: Annotated[\n int,\n Doc(\n \"\"\"\n HTTP status code to send to the client.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n \"\"\"\n ),\n ],\n detail: Annotated[\n Any,\n Doc(\n \"\"\"\n Any data to be sent to the client in the `detail` key of the JSON\n response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n \"\"\"\n ),\n ] = None,\n headers: Annotated[\n Mapping[str, str] | None,\n Doc(\n \"\"\"\n Any headers to send to the client in the response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers)\n\n \"\"\"\n ),\n ] = None,\n ) -> None:\n super().__init__(status_code=status_code, detail=detail, headers=headers)", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "HTTPException", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L17-L83", "start_line": 17, "end_line": 83} {"id": "fastapi/exceptions.py::WebSocketException::L86", "text": "# File: fastapi/exceptions.py | Symbol: WebSocketException\nclass WebSocketException(StarletteWebSocketException):\n \"\"\"\n A WebSocket exception you can raise in your own code to show errors to the client.\n\n This is for client errors, invalid authentication, invalid data, etc. Not for server\n errors in your code.\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 typing import Annotated\n\n from fastapi import (\n Cookie,\n FastAPI,\n WebSocket,\n WebSocketException,\n status,\n )\n\n app = FastAPI()\n\n @app.websocket(\"/items/{item_id}/ws\")\n async def websocket_endpoint(\n *,\n websocket: WebSocket,\n session: Annotated[str | None, Cookie()] = None,\n item_id: str,\n ):\n if session is None:\n raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)\n await websocket.accept()\n while True:\n data = await websocket.receive_text()\n await websocket.send_text(f\"Session cookie is: {session}\")\n await websocket.send_text(f\"Message text was: {data}, for item ID: {item_id}\")\n ```\n \"\"\"\n\n def __init__(\n self,\n code: Annotated[\n int,\n Doc(\n \"\"\"\n A closing code from the\n [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).\n \"\"\"\n ),\n ],\n reason: Annotated[\n str | None,\n Doc(\n \"\"\"\n The reason to close the WebSocket connection.\n\n It is UTF-8-encoded data. The interpretation of the reason is up to the\n application, it is not specified by the WebSocket specification.\n\n It could contain text that could be human-readable or interpretable\n by the client code, etc.\n \"\"\"\n ),\n ] = None,\n ) -> None:\n super().__init__(code=code, reason=reason)", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "WebSocketException", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L86-L154", "start_line": 86, "end_line": 154} {"id": "fastapi/exceptions.py::FastAPIError::L161", "text": "# File: fastapi/exceptions.py | Symbol: FastAPIError\nclass FastAPIError(RuntimeError):\n \"\"\"\n A generic, FastAPI-specific error.\n \"\"\"", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "FastAPIError", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L161-L164", "start_line": 161, "end_line": 164} {"id": "fastapi/exceptions.py::DependencyScopeError::L167", "text": "# File: fastapi/exceptions.py | Symbol: DependencyScopeError\nclass DependencyScopeError(FastAPIError):\n \"\"\"\n A dependency declared that it depends on another dependency with an invalid\n (narrower) scope.\n \"\"\"", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "DependencyScopeError", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L167-L171", "start_line": 167, "end_line": 171} {"id": "fastapi/exceptions.py::ValidationException::L174", "text": "# File: fastapi/exceptions.py | Symbol: ValidationException\nclass ValidationException(Exception):\n def __init__(\n self,\n errors: Sequence[Any],\n *,\n endpoint_ctx: EndpointContext | None = None,\n ) -> None:\n self._errors = errors\n self.endpoint_ctx = endpoint_ctx\n\n ctx = endpoint_ctx or {}\n self.endpoint_function = ctx.get(\"function\")\n self.endpoint_path = ctx.get(\"path\")\n self.endpoint_file = ctx.get(\"file\")\n self.endpoint_line = ctx.get(\"line\")\n\n def errors(self) -> Sequence[Any]:\n return self._errors\n\n def _format_endpoint_context(self) -> str:\n if not (self.endpoint_file and self.endpoint_line and self.endpoint_function):\n if self.endpoint_path:\n return f\"\\n Endpoint: {self.endpoint_path}\"\n return \"\"\n\n context = f'\\n File \"{self.endpoint_file}\", line {self.endpoint_line}, in {self.endpoint_function}'\n if self.endpoint_path:\n context += f\"\\n {self.endpoint_path}\"\n return context\n\n def __str__(self) -> str:\n message = f\"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\\n\"\n for err in self._errors:\n message += f\" {err}\\n\"\n message += self._format_endpoint_context()\n return message.rstrip()", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "ValidationException", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L174-L209", "start_line": 174, "end_line": 209} {"id": "fastapi/exceptions.py::RequestValidationError::L212", "text": "# File: fastapi/exceptions.py | Symbol: RequestValidationError\nclass RequestValidationError(ValidationException):\n def __init__(\n self,\n errors: Sequence[Any],\n *,\n body: Any = None,\n endpoint_ctx: EndpointContext | None = None,\n ) -> None:\n super().__init__(errors, endpoint_ctx=endpoint_ctx)\n self.body = body", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "RequestValidationError", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L212-L221", "start_line": 212, "end_line": 221} {"id": "fastapi/exceptions.py::WebSocketRequestValidationError::L224", "text": "# File: fastapi/exceptions.py | Symbol: WebSocketRequestValidationError\nclass WebSocketRequestValidationError(ValidationException):\n def __init__(\n self,\n errors: Sequence[Any],\n *,\n endpoint_ctx: EndpointContext | None = None,\n ) -> None:\n super().__init__(errors, endpoint_ctx=endpoint_ctx)", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "WebSocketRequestValidationError", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L224-L231", "start_line": 224, "end_line": 231} {"id": "fastapi/exceptions.py::ResponseValidationError::L234", "text": "# File: fastapi/exceptions.py | Symbol: ResponseValidationError\nclass ResponseValidationError(ValidationException):\n def __init__(\n self,\n errors: Sequence[Any],\n *,\n body: Any = None,\n endpoint_ctx: EndpointContext | None = None,\n ) -> None:\n super().__init__(errors, endpoint_ctx=endpoint_ctx)\n self.body = body", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "ResponseValidationError", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L234-L243", "start_line": 234, "end_line": 243} {"id": "fastapi/exceptions.py::PydanticV1NotSupportedError::L246", "text": "# File: fastapi/exceptions.py | Symbol: PydanticV1NotSupportedError\nclass PydanticV1NotSupportedError(FastAPIError):\n \"\"\"\n A pydantic.v1 model is used, which is no longer supported.\n \"\"\"", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "PydanticV1NotSupportedError", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L246-L249", "start_line": 246, "end_line": 249} {"id": "fastapi/exceptions.py::FastAPIDeprecationWarning::L252", "text": "# File: fastapi/exceptions.py | Symbol: FastAPIDeprecationWarning\nclass FastAPIDeprecationWarning(UserWarning):\n \"\"\"\n A custom deprecation warning as DeprecationWarning is ignored\n Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries\n \"\"\"", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "FastAPIDeprecationWarning", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L252-L256", "start_line": 252, "end_line": 256} {"id": "fastapi/exceptions.py::", "text": "# File: fastapi/exceptions.py | Symbol: \nfrom collections.abc import Mapping, Sequence\nfrom typing import Annotated, Any, TypedDict\nfrom annotated_doc import Doc\nfrom pydantic import BaseModel, create_model\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\nfrom starlette.exceptions import WebSocketException as StarletteWebSocketException\nRequestErrorModel: type[BaseModel] = create_model(\"Request\")\nWebSocketErrorModel: type[BaseModel] = create_model(\"WebSocket\")", "source_type": "code", "path": "fastapi/exceptions.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/exceptions.py#L1-L158", "start_line": 1, "end_line": 158} {"id": "fastapi/logger.py::", "text": "# File: fastapi/logger.py | Symbol: \nimport logging\nlogger = logging.getLogger(\"fastapi\")", "source_type": "code", "path": "fastapi/logger.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/logger.py#L1-L3", "start_line": 1, "end_line": 3} {"id": "fastapi/middleware/__init__.py::", "text": "# File: fastapi/middleware/__init__.py | Symbol: \nfrom starlette.middleware import Middleware as Middleware", "source_type": "code", "path": "fastapi/middleware/__init__.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/__init__.py#L1-L1", "start_line": 1, "end_line": 1} {"id": "fastapi/middleware/asyncexitstack.py::AsyncExitStackMiddleware::L8", "text": "# File: fastapi/middleware/asyncexitstack.py | Symbol: AsyncExitStackMiddleware\nclass AsyncExitStackMiddleware:\n def __init__(\n self, app: ASGIApp, context_name: str = \"fastapi_middleware_astack\"\n ) -> None:\n self.app = app\n self.context_name = context_name\n\n async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n async with AsyncExitStack() as stack:\n scope[self.context_name] = stack\n await self.app(scope, receive, send)", "source_type": "code", "path": "fastapi/middleware/asyncexitstack.py", "symbol": "AsyncExitStackMiddleware", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/asyncexitstack.py#L8-L18", "start_line": 8, "end_line": 18} {"id": "fastapi/middleware/asyncexitstack.py::", "text": "# File: fastapi/middleware/asyncexitstack.py | Symbol: \nfrom contextlib import AsyncExitStack\nfrom starlette.types import ASGIApp, Receive, Scope, Send\n# Used mainly to close files after the request is done, dependencies are closed\n# in their own AsyncExitStack", "source_type": "code", "path": "fastapi/middleware/asyncexitstack.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/asyncexitstack.py#L1-L7", "start_line": 1, "end_line": 7} {"id": "fastapi/middleware/cors.py::", "text": "# File: fastapi/middleware/cors.py | Symbol: \nfrom starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa", "source_type": "code", "path": "fastapi/middleware/cors.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/cors.py#L1-L1", "start_line": 1, "end_line": 1} {"id": "fastapi/middleware/gzip.py::", "text": "# File: fastapi/middleware/gzip.py | Symbol: \nfrom starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa", "source_type": "code", "path": "fastapi/middleware/gzip.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/gzip.py#L1-L1", "start_line": 1, "end_line": 1} {"id": "fastapi/middleware/httpsredirect.py::", "text": "# File: fastapi/middleware/httpsredirect.py | Symbol: \nfrom starlette.middleware.httpsredirect import ( # noqa\n HTTPSRedirectMiddleware as HTTPSRedirectMiddleware,\n)", "source_type": "code", "path": "fastapi/middleware/httpsredirect.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/httpsredirect.py#L1-L3", "start_line": 1, "end_line": 3} {"id": "fastapi/middleware/trustedhost.py::", "text": "# File: fastapi/middleware/trustedhost.py | Symbol: \nfrom starlette.middleware.trustedhost import ( # noqa\n TrustedHostMiddleware as TrustedHostMiddleware,\n)", "source_type": "code", "path": "fastapi/middleware/trustedhost.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/trustedhost.py#L1-L3", "start_line": 1, "end_line": 3} {"id": "fastapi/middleware/wsgi.py::", "text": "# File: fastapi/middleware/wsgi.py | Symbol: \nfrom starlette.middleware.wsgi import (\n WSGIMiddleware as WSGIMiddleware,\n) # pragma: no cover # noqa", "source_type": "code", "path": "fastapi/middleware/wsgi.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/middleware/wsgi.py#L1-L3", "start_line": 1, "end_line": 3} {"id": "fastapi/openapi/constants.py::", "text": "# File: fastapi/openapi/constants.py | Symbol: \nMETHODS_WITH_BODY = {\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"}\nREF_PREFIX = \"#/components/schemas/\"\nREF_TEMPLATE = \"#/components/schemas/{model}\"", "source_type": "code", "path": "fastapi/openapi/constants.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/constants.py#L1-L3", "start_line": 1, "end_line": 3} {"id": "fastapi/openapi/docs.py::_html_safe_json::L9", "text": "# File: fastapi/openapi/docs.py | Symbol: _html_safe_json\ndef _html_safe_json(value: Any) -> str:\n \"\"\"Serialize a value to JSON with HTML special characters escaped.\n\n This prevents injection when the JSON is embedded inside a \n \n \n \n \n \"\"\"\n return HTMLResponse(html)", "source_type": "code", "path": "fastapi/openapi/docs.py", "symbol": "get_swagger_ui_html", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/docs.py#L40-L194", "start_line": 40, "end_line": 194} {"id": "fastapi/openapi/docs.py::get_redoc_html::L197", "text": "# File: fastapi/openapi/docs.py | Symbol: get_redoc_html\ndef get_redoc_html(\n *,\n openapi_url: Annotated[\n str,\n Doc(\n \"\"\"\n The OpenAPI URL that ReDoc should load and use.\n\n This is normally done automatically by FastAPI using the default URL\n `/openapi.json`.\n\n Read more about it in the\n [FastAPI docs for Conditional OpenAPI](https://fastapi.tiangolo.com/how-to/conditional-openapi/#conditional-openapi-from-settings-and-env-vars)\n \"\"\"\n ),\n ],\n title: Annotated[\n str,\n Doc(\n \"\"\"\n The HTML `` content, normally shown in the browser tab.\n\n Read more about it in the\n [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/)\n \"\"\"\n ),\n ],\n redoc_js_url: Annotated[\n str,\n Doc(\n \"\"\"\n The URL to use to load the ReDoc JavaScript.\n\n It is normally set to a CDN URL.\n\n Read more about it in the\n [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/)\n \"\"\"\n ),\n ] = \"https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js\",\n redoc_favicon_url: Annotated[\n str,\n Doc(\n \"\"\"\n The URL of the favicon to use. It is normally shown in the browser tab.\n \"\"\"\n ),\n ] = \"https://fastapi.tiangolo.com/img/favicon.png\",\n with_google_fonts: Annotated[\n bool,\n Doc(\n \"\"\"\n Load and use Google Fonts.\n \"\"\"\n ),\n ] = True,\n) -> HTMLResponse:\n \"\"\"\n Generate and return the HTML response that loads ReDoc for the alternative\n API docs (normally served at `/redoc`).\n\n You would only call this function yourself if you needed to override some parts,\n for example the URLs to use to load ReDoc's JavaScript and CSS.\n\n Read more about it in the\n [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/).\n \"\"\"\n html = f\"\"\"\n <!DOCTYPE html>\n <html>\n <head>\n <title>{title}\n \n \n \n \"\"\"\n if with_google_fonts:\n html += \"\"\"\n \n \"\"\"\n html += f\"\"\"\n \n \n \n \n \n \n \n \n \n \n \"\"\"\n return HTMLResponse(html)", "source_type": "code", "path": "fastapi/openapi/docs.py", "symbol": "get_redoc_html", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/docs.py#L197-L298", "start_line": 197, "end_line": 298} {"id": "fastapi/openapi/docs.py::get_swagger_ui_oauth2_redirect_html::L301", "text": "# File: fastapi/openapi/docs.py | Symbol: get_swagger_ui_oauth2_redirect_html\ndef get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:\n \"\"\"\n Generate the HTML response with the OAuth2 redirection for Swagger UI.\n\n You normally don't need to use or change this.\n \"\"\"\n # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html\n html = \"\"\"\n \n \n \n Swagger UI: OAuth2 Redirect\n \n \n \n \n \n \"\"\"\n return HTMLResponse(content=html)", "source_type": "code", "path": "fastapi/openapi/docs.py", "symbol": "get_swagger_ui_oauth2_redirect_html", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/docs.py#L301-L389", "start_line": 301, "end_line": 389} {"id": "fastapi/openapi/docs.py::", "text": "# File: fastapi/openapi/docs.py | Symbol: \nimport json\nfrom typing import Annotated, Any\nfrom annotated_doc import Doc\nfrom fastapi.encoders import jsonable_encoder\nfrom starlette.responses import HTMLResponse\nswagger_ui_default_parameters: Annotated[\n dict[str, Any],\n Doc(\n \"\"\"\n Default configurations for Swagger UI.\n You can use it as a template to add any other configurations needed.\n \"\"\"\n ),\n] = {\n \"dom_id\": \"#swagger-ui\",\n \"layout\": \"BaseLayout\",\n \"deepLinking\": True,\n \"showExtensions\": True,\n \"showCommonExtensions\": True,\n}", "source_type": "code", "path": "fastapi/openapi/docs.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/docs.py#L1-L37", "start_line": 1, "end_line": 37} {"id": "fastapi/openapi/models.py::BaseModelWithConfig::L57", "text": "# File: fastapi/openapi/models.py | Symbol: BaseModelWithConfig\nclass BaseModelWithConfig(BaseModel):\n model_config = {\"extra\": \"allow\"}", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "BaseModelWithConfig", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L57-L58", "start_line": 57, "end_line": 58} {"id": "fastapi/openapi/models.py::Contact::L61", "text": "# File: fastapi/openapi/models.py | Symbol: Contact\nclass Contact(BaseModelWithConfig):\n name: str | None = None\n url: AnyUrl | None = None\n email: EmailStr | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Contact", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L61-L64", "start_line": 61, "end_line": 64} {"id": "fastapi/openapi/models.py::License::L67", "text": "# File: fastapi/openapi/models.py | Symbol: License\nclass License(BaseModelWithConfig):\n name: str\n identifier: str | None = None\n url: AnyUrl | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "License", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L67-L70", "start_line": 67, "end_line": 70} {"id": "fastapi/openapi/models.py::Info::L73", "text": "# File: fastapi/openapi/models.py | Symbol: Info\nclass Info(BaseModelWithConfig):\n title: str\n summary: str | None = None\n description: str | None = None\n termsOfService: str | None = None\n contact: Contact | None = None\n license: License | None = None\n version: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Info", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L73-L80", "start_line": 73, "end_line": 80} {"id": "fastapi/openapi/models.py::ServerVariable::L83", "text": "# File: fastapi/openapi/models.py | Symbol: ServerVariable\nclass ServerVariable(BaseModelWithConfig):\n enum: Annotated[list[str] | None, Field(min_length=1)] = None\n default: str\n description: str | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "ServerVariable", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L83-L86", "start_line": 83, "end_line": 86} {"id": "fastapi/openapi/models.py::Server::L89", "text": "# File: fastapi/openapi/models.py | Symbol: Server\nclass Server(BaseModelWithConfig):\n url: AnyUrl | str\n description: str | None = None\n variables: dict[str, ServerVariable] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Server", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L89-L92", "start_line": 89, "end_line": 92} {"id": "fastapi/openapi/models.py::Reference::L95", "text": "# File: fastapi/openapi/models.py | Symbol: Reference\nclass Reference(BaseModel):\n ref: str = Field(alias=\"$ref\")", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Reference", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L95-L96", "start_line": 95, "end_line": 96} {"id": "fastapi/openapi/models.py::Discriminator::L99", "text": "# File: fastapi/openapi/models.py | Symbol: Discriminator\nclass Discriminator(BaseModel):\n propertyName: str\n mapping: dict[str, str] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Discriminator", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L99-L101", "start_line": 99, "end_line": 101} {"id": "fastapi/openapi/models.py::XML::L104", "text": "# File: fastapi/openapi/models.py | Symbol: XML\nclass XML(BaseModelWithConfig):\n name: str | None = None\n namespace: str | None = None\n prefix: str | None = None\n attribute: bool | None = None\n wrapped: bool | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "XML", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L104-L109", "start_line": 104, "end_line": 109} {"id": "fastapi/openapi/models.py::ExternalDocumentation::L112", "text": "# File: fastapi/openapi/models.py | Symbol: ExternalDocumentation\nclass ExternalDocumentation(BaseModelWithConfig):\n description: str | None = None\n url: AnyUrl", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "ExternalDocumentation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L112-L114", "start_line": 112, "end_line": 114} {"id": "fastapi/openapi/models.py::Schema::L123", "text": "# File: fastapi/openapi/models.py | Symbol: Schema\nclass Schema(BaseModelWithConfig):\n # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu\n # Core Vocabulary\n schema_: str | None = Field(default=None, alias=\"$schema\")\n vocabulary: str | None = Field(default=None, alias=\"$vocabulary\")\n id: str | None = Field(default=None, alias=\"$id\")\n anchor: str | None = Field(default=None, alias=\"$anchor\")\n dynamicAnchor: str | None = Field(default=None, alias=\"$dynamicAnchor\")\n ref: str | None = Field(default=None, alias=\"$ref\")\n dynamicRef: str | None = Field(default=None, alias=\"$dynamicRef\")\n defs: dict[str, \"SchemaOrBool\"] | None = Field(default=None, alias=\"$defs\")\n comment: str | None = Field(default=None, alias=\"$comment\")\n # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s\n # A Vocabulary for Applying Subschemas\n allOf: list[\"SchemaOrBool\"] | None = None\n anyOf: list[\"SchemaOrBool\"] | None = None\n oneOf: list[\"SchemaOrBool\"] | None = None\n not_: Optional[\"SchemaOrBool\"] = Field(default=None, alias=\"not\")\n if_: Optional[\"SchemaOrBool\"] = Field(default=None, alias=\"if\")\n then: Optional[\"SchemaOrBool\"] = None\n else_: Optional[\"SchemaOrBool\"] = Field(default=None, alias=\"else\")\n dependentSchemas: dict[str, \"SchemaOrBool\"] | None = None\n prefixItems: list[\"SchemaOrBool\"] | None = None\n items: Optional[\"SchemaOrBool\"] = None\n contains: Optional[\"SchemaOrBool\"] = None\n properties: dict[str, \"SchemaOrBool\"] | None = None\n patternProperties: dict[str, \"SchemaOrBool\"] | None = None\n additionalProperties: Optional[\"SchemaOrBool\"] = None\n propertyNames: Optional[\"SchemaOrBool\"] = None\n unevaluatedItems: Optional[\"SchemaOrBool\"] = None\n unevaluatedProperties: Optional[\"SchemaOrBool\"] = None\n # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural\n # A Vocabulary for Structural Validation\n type: SchemaType | list[SchemaType] | None = None\n enum: list[Any] | None = None\n const: Any | None = None\n multipleOf: float | None = Field(default=None, gt=0)\n maximum: float | None = None\n exclusiveMaximum: float | None = None\n minimum: float | None = None\n exclusiveMinimum: float | None = None\n maxLength: int | None = Field(default=None, ge=0)\n minLength: int | None = Field(default=None, ge=0)\n pattern: str | None = None\n maxItems: int | None = Field(default=None, ge=0)\n minItems: int | None = Field(default=None, ge=0)\n uniqueItems: bool | None = None\n maxContains: int | None = Field(default=None, ge=0)\n minContains: int | None = Field(default=None, ge=0)\n maxProperties: int | None = Field(default=None, ge=0)\n minProperties: int | None = Field(default=None, ge=0)\n required: list[str] | None = None\n dependentRequired: dict[str, set[str]] | None = None\n # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c\n # Vocabularies for Semantic Content With \"format\"\n format: str | None = None\n # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten\n # A Vocabulary for the Contents of String-Encoded Data\n contentEncoding: str | None = None\n contentMediaType: str | None = None\n contentSchema: Optional[\"SchemaOrBool\"] = None\n # Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta\n # A Vocabulary for Basic Meta-Data Annotations\n title: str | None = None\n description: str | None = None\n default: Any | None = None\n deprecated: bool | None = None\n readOnly: bool | None = None\n writeOnly: bool | None = None\n examples: list[Any] | None = None\n # Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object\n # Schema Object\n discriminator: Discriminator | None = None\n xml: XML | None = None\n externalDocs: ExternalDocumentation | None = None\n example: Annotated[\n Any | None,\n typing_deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Schema", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L123-L204", "start_line": 123, "end_line": 204} {"id": "fastapi/openapi/models.py::Example::L212", "text": "# File: fastapi/openapi/models.py | Symbol: Example\nclass Example(TypedDict, total=False):\n summary: str | None\n description: str | None\n value: Any | None\n externalValue: AnyUrl | None\n\n __pydantic_config__ = {\"extra\": \"allow\"} # type: ignore[misc] # ty: ignore[invalid-typed-dict-statement]", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Example", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L212-L218", "start_line": 212, "end_line": 218} {"id": "fastapi/openapi/models.py::ParameterInType::L221", "text": "# File: fastapi/openapi/models.py | Symbol: ParameterInType\nclass ParameterInType(Enum):\n query = \"query\"\n header = \"header\"\n path = \"path\"\n cookie = \"cookie\"", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "ParameterInType", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L221-L225", "start_line": 221, "end_line": 225} {"id": "fastapi/openapi/models.py::Encoding::L228", "text": "# File: fastapi/openapi/models.py | Symbol: Encoding\nclass Encoding(BaseModelWithConfig):\n contentType: str | None = None\n headers: dict[str, Union[\"Header\", Reference]] | None = None\n style: str | None = None\n explode: bool | None = None\n allowReserved: bool | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Encoding", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L228-L233", "start_line": 228, "end_line": 233} {"id": "fastapi/openapi/models.py::MediaType::L236", "text": "# File: fastapi/openapi/models.py | Symbol: MediaType\nclass MediaType(BaseModelWithConfig):\n schema_: Schema | Reference | None = Field(default=None, alias=\"schema\")\n example: Any | None = None\n examples: dict[str, Example | Reference] | None = None\n encoding: dict[str, Encoding] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "MediaType", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L236-L240", "start_line": 236, "end_line": 240} {"id": "fastapi/openapi/models.py::ParameterBase::L243", "text": "# File: fastapi/openapi/models.py | Symbol: ParameterBase\nclass ParameterBase(BaseModelWithConfig):\n description: str | None = None\n required: bool | None = None\n deprecated: bool | None = None\n # Serialization rules for simple scenarios\n style: str | None = None\n explode: bool | None = None\n allowReserved: bool | None = None\n schema_: Schema | Reference | None = Field(default=None, alias=\"schema\")\n example: Any | None = None\n examples: dict[str, Example | Reference] | None = None\n # Serialization rules for more complex scenarios\n content: dict[str, MediaType] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "ParameterBase", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L243-L255", "start_line": 243, "end_line": 255} {"id": "fastapi/openapi/models.py::Parameter::L258", "text": "# File: fastapi/openapi/models.py | Symbol: Parameter\nclass Parameter(ParameterBase):\n name: str\n in_: ParameterInType = Field(alias=\"in\")", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Parameter", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L258-L260", "start_line": 258, "end_line": 260} {"id": "fastapi/openapi/models.py::RequestBody::L267", "text": "# File: fastapi/openapi/models.py | Symbol: RequestBody\nclass RequestBody(BaseModelWithConfig):\n description: str | None = None\n content: dict[str, MediaType]\n required: bool | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "RequestBody", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L267-L270", "start_line": 267, "end_line": 270} {"id": "fastapi/openapi/models.py::Link::L273", "text": "# File: fastapi/openapi/models.py | Symbol: Link\nclass Link(BaseModelWithConfig):\n operationRef: str | None = None\n operationId: str | None = None\n parameters: dict[str, Any | str] | None = None\n requestBody: Any | str | None = None\n description: str | None = None\n server: Server | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Link", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L273-L279", "start_line": 273, "end_line": 279} {"id": "fastapi/openapi/models.py::Response::L282", "text": "# File: fastapi/openapi/models.py | Symbol: Response\nclass Response(BaseModelWithConfig):\n description: str\n headers: dict[str, Header | Reference] | None = None\n content: dict[str, MediaType] | None = None\n links: dict[str, Link | Reference] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Response", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L282-L286", "start_line": 282, "end_line": 286} {"id": "fastapi/openapi/models.py::Operation::L289", "text": "# File: fastapi/openapi/models.py | Symbol: Operation\nclass Operation(BaseModelWithConfig):\n tags: list[str] | None = None\n summary: str | None = None\n description: str | None = None\n externalDocs: ExternalDocumentation | None = None\n operationId: str | None = None\n parameters: list[Parameter | Reference] | None = None\n requestBody: RequestBody | Reference | None = None\n # Using Any for Specification Extensions\n responses: dict[str, Response | Any] | None = None\n callbacks: dict[str, dict[str, \"PathItem\"] | Reference] | None = None\n deprecated: bool | None = None\n security: list[dict[str, list[str]]] | None = None\n servers: list[Server] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Operation", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L289-L302", "start_line": 289, "end_line": 302} {"id": "fastapi/openapi/models.py::PathItem::L305", "text": "# File: fastapi/openapi/models.py | Symbol: PathItem\nclass PathItem(BaseModelWithConfig):\n ref: str | None = Field(default=None, alias=\"$ref\")\n summary: str | None = None\n description: str | None = None\n get: Operation | None = None\n put: Operation | None = None\n post: Operation | None = None\n delete: Operation | None = None\n options: Operation | None = None\n head: Operation | None = None\n patch: Operation | None = None\n trace: Operation | None = None\n servers: list[Server] | None = None\n parameters: list[Parameter | Reference] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "PathItem", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L305-L318", "start_line": 305, "end_line": 318} {"id": "fastapi/openapi/models.py::SecuritySchemeType::L321", "text": "# File: fastapi/openapi/models.py | Symbol: SecuritySchemeType\nclass SecuritySchemeType(Enum):\n apiKey = \"apiKey\"\n http = \"http\"\n oauth2 = \"oauth2\"\n openIdConnect = \"openIdConnect\"", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "SecuritySchemeType", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L321-L325", "start_line": 321, "end_line": 325} {"id": "fastapi/openapi/models.py::SecurityBase::L328", "text": "# File: fastapi/openapi/models.py | Symbol: SecurityBase\nclass SecurityBase(BaseModelWithConfig):\n type_: SecuritySchemeType = Field(alias=\"type\")\n description: str | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "SecurityBase", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L328-L330", "start_line": 328, "end_line": 330} {"id": "fastapi/openapi/models.py::APIKeyIn::L333", "text": "# File: fastapi/openapi/models.py | Symbol: APIKeyIn\nclass APIKeyIn(Enum):\n query = \"query\"\n header = \"header\"\n cookie = \"cookie\"", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "APIKeyIn", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L333-L336", "start_line": 333, "end_line": 336} {"id": "fastapi/openapi/models.py::APIKey::L339", "text": "# File: fastapi/openapi/models.py | Symbol: APIKey\nclass APIKey(SecurityBase):\n type_: SecuritySchemeType = Field(default=SecuritySchemeType.apiKey, alias=\"type\")\n in_: APIKeyIn = Field(alias=\"in\")\n name: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "APIKey", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L339-L342", "start_line": 339, "end_line": 342} {"id": "fastapi/openapi/models.py::HTTPBase::L345", "text": "# File: fastapi/openapi/models.py | Symbol: HTTPBase\nclass HTTPBase(SecurityBase):\n type_: SecuritySchemeType = Field(default=SecuritySchemeType.http, alias=\"type\")\n scheme: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "HTTPBase", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L345-L347", "start_line": 345, "end_line": 347} {"id": "fastapi/openapi/models.py::HTTPBearer::L350", "text": "# File: fastapi/openapi/models.py | Symbol: HTTPBearer\nclass HTTPBearer(HTTPBase):\n scheme: Literal[\"bearer\"] = \"bearer\"\n bearerFormat: str | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "HTTPBearer", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L350-L352", "start_line": 350, "end_line": 352} {"id": "fastapi/openapi/models.py::OAuthFlow::L355", "text": "# File: fastapi/openapi/models.py | Symbol: OAuthFlow\nclass OAuthFlow(BaseModelWithConfig):\n refreshUrl: str | None = None\n scopes: dict[str, str] = {}", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OAuthFlow", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L355-L357", "start_line": 355, "end_line": 357} {"id": "fastapi/openapi/models.py::OAuthFlowImplicit::L360", "text": "# File: fastapi/openapi/models.py | Symbol: OAuthFlowImplicit\nclass OAuthFlowImplicit(OAuthFlow):\n authorizationUrl: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OAuthFlowImplicit", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L360-L361", "start_line": 360, "end_line": 361} {"id": "fastapi/openapi/models.py::OAuthFlowPassword::L364", "text": "# File: fastapi/openapi/models.py | Symbol: OAuthFlowPassword\nclass OAuthFlowPassword(OAuthFlow):\n tokenUrl: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OAuthFlowPassword", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L364-L365", "start_line": 364, "end_line": 365} {"id": "fastapi/openapi/models.py::OAuthFlowClientCredentials::L368", "text": "# File: fastapi/openapi/models.py | Symbol: OAuthFlowClientCredentials\nclass OAuthFlowClientCredentials(OAuthFlow):\n tokenUrl: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OAuthFlowClientCredentials", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L368-L369", "start_line": 368, "end_line": 369} {"id": "fastapi/openapi/models.py::OAuthFlowAuthorizationCode::L372", "text": "# File: fastapi/openapi/models.py | Symbol: OAuthFlowAuthorizationCode\nclass OAuthFlowAuthorizationCode(OAuthFlow):\n authorizationUrl: str\n tokenUrl: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OAuthFlowAuthorizationCode", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L372-L374", "start_line": 372, "end_line": 374} {"id": "fastapi/openapi/models.py::OAuthFlows::L377", "text": "# File: fastapi/openapi/models.py | Symbol: OAuthFlows\nclass OAuthFlows(BaseModelWithConfig):\n implicit: OAuthFlowImplicit | None = None\n password: OAuthFlowPassword | None = None\n clientCredentials: OAuthFlowClientCredentials | None = None\n authorizationCode: OAuthFlowAuthorizationCode | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OAuthFlows", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L377-L381", "start_line": 377, "end_line": 381} {"id": "fastapi/openapi/models.py::OAuth2::L384", "text": "# File: fastapi/openapi/models.py | Symbol: OAuth2\nclass OAuth2(SecurityBase):\n type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias=\"type\")\n flows: OAuthFlows", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OAuth2", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L384-L386", "start_line": 384, "end_line": 386} {"id": "fastapi/openapi/models.py::OpenIdConnect::L389", "text": "# File: fastapi/openapi/models.py | Symbol: OpenIdConnect\nclass OpenIdConnect(SecurityBase):\n type_: SecuritySchemeType = Field(\n default=SecuritySchemeType.openIdConnect, alias=\"type\"\n )\n openIdConnectUrl: str", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OpenIdConnect", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L389-L393", "start_line": 389, "end_line": 393} {"id": "fastapi/openapi/models.py::Components::L399", "text": "# File: fastapi/openapi/models.py | Symbol: Components\nclass Components(BaseModelWithConfig):\n schemas: dict[str, Schema | Reference] | None = None\n responses: dict[str, Response | Reference] | None = None\n parameters: dict[str, Parameter | Reference] | None = None\n examples: dict[str, Example | Reference] | None = None\n requestBodies: dict[str, RequestBody | Reference] | None = None\n headers: dict[str, Header | Reference] | None = None\n securitySchemes: dict[str, SecurityScheme | Reference] | None = None\n links: dict[str, Link | Reference] | None = None\n # Using Any for Specification Extensions\n callbacks: dict[str, dict[str, PathItem] | Reference | Any] | None = None\n pathItems: dict[str, PathItem | Reference] | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Components", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L399-L410", "start_line": 399, "end_line": 410} {"id": "fastapi/openapi/models.py::Tag::L413", "text": "# File: fastapi/openapi/models.py | Symbol: Tag\nclass Tag(BaseModelWithConfig):\n name: str\n description: str | None = None\n externalDocs: ExternalDocumentation | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "Tag", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L413-L416", "start_line": 413, "end_line": 416} {"id": "fastapi/openapi/models.py::OpenAPI::L419", "text": "# File: fastapi/openapi/models.py | Symbol: OpenAPI\nclass OpenAPI(BaseModelWithConfig):\n openapi: str\n info: Info\n jsonSchemaDialect: str | None = None\n servers: list[Server] | None = None\n # Using Any for Specification Extensions\n paths: dict[str, PathItem | Any] | None = None\n webhooks: dict[str, PathItem | Reference] | None = None\n components: Components | None = None\n security: list[dict[str, list[str]]] | None = None\n tags: list[Tag] | None = None\n externalDocs: ExternalDocumentation | None = None", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "OpenAPI", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L419-L430", "start_line": 419, "end_line": 430} {"id": "fastapi/openapi/models.py::", "text": "# File: fastapi/openapi/models.py | Symbol: \nfrom collections.abc import Callable, Iterable, Mapping\nfrom enum import Enum\nfrom typing import Annotated, Any, Literal, Optional, Union\nfrom fastapi._compat import with_info_plain_validator_function\nfrom fastapi.logger import logger\nfrom pydantic import (\n AnyUrl,\n BaseModel,\n Field,\n GetJsonSchemaHandler,\n)\nfrom typing_extensions import TypedDict\nfrom typing_extensions import deprecated as typing_deprecated\ntry:\n import email_validator\n assert email_validator # make autoflake ignore the unused import\n from pydantic import EmailStr\nexcept ImportError: # pragma: no cover\n class EmailStr(str): # type: ignore[no-redef]\n @classmethod\n def __get_validators__(cls) -> Iterable[Callable[..., Any]]:\n yield cls.validate\n @classmethod\n def validate(cls, v: Any) -> str:\n logger.warning(\n \"email-validator not installed, email fields will be treated as str.\\n\"\n \"To install, run: pip install email-validator\"\n )\n return str(v)\n @classmethod\n def _validate(cls, __input_value: Any, _: Any) -> str:\n logger.warning(\n \"email-validator not installed, email fields will be treated as str.\\n\"\n \"To install, run: pip install email-validator\"\n )\n return str(__input_value)\n @classmethod\n def __get_pydantic_json_schema__(\n cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler\n ) -> dict[str, Any]:\n return {\"type\": \"string\", \"format\": \"email\"}\n @classmethod\n def __get_pydantic_core_schema__(\n cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]\n ) -> Mapping[str, Any]:\n return with_info_plain_validator_function(cls._validate)\n# Ref JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation#name-type\nSchemaType = Literal[\n \"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"\n]\n# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents\n# A JSON Schema MUST be an object or a boolean.\nSchemaOrBool = Schema | bool\nSecurityScheme = APIKey | HTTPBase | OAuth2 | OpenIdConnect | HTTPBearer\nSchema.model_rebuild()\nOperation.model_rebuild()\nEncoding.model_rebuild()", "source_type": "code", "path": "fastapi/openapi/models.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/models.py#L1-L435", "start_line": 1, "end_line": 435} {"id": "fastapi/openapi/utils.py::get_openapi_security_definitions::L81", "text": "# File: fastapi/openapi/utils.py | Symbol: get_openapi_security_definitions\ndef get_openapi_security_definitions(\n flat_dependant: Dependant,\n) -> tuple[dict[str, Any], list[dict[str, Any]]]:\n security_definitions = {}\n # Use a dict to merge scopes for same security scheme\n operation_security_dict: dict[str, list[str]] = {}\n for security_dependency in flat_dependant._security_dependencies:\n security_definition = jsonable_encoder(\n security_dependency._security_scheme.model,\n by_alias=True,\n exclude_none=True,\n )\n security_name = security_dependency._security_scheme.scheme_name\n security_definitions[security_name] = security_definition\n # Merge scopes for the same security scheme\n if security_name not in operation_security_dict:\n operation_security_dict[security_name] = []\n for scope in security_dependency.oauth_scopes or []:\n if scope not in operation_security_dict[security_name]:\n operation_security_dict[security_name].append(scope)\n operation_security = [\n {name: scopes} for name, scopes in operation_security_dict.items()\n ]\n return security_definitions, operation_security", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "get_openapi_security_definitions", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L81-L104", "start_line": 81, "end_line": 104} {"id": "fastapi/openapi/utils.py::_get_openapi_operation_parameters::L107", "text": "# File: fastapi/openapi/utils.py | Symbol: _get_openapi_operation_parameters\ndef _get_openapi_operation_parameters(\n *,\n dependant: Dependant,\n model_name_map: ModelNameMap,\n field_mapping: dict[\n tuple[ModelField, Literal[\"validation\", \"serialization\"]], dict[str, Any]\n ],\n separate_input_output_schemas: bool = True,\n) -> list[dict[str, Any]]:\n parameters = []\n flat_dependant = get_flat_dependant(dependant, skip_repeats=True)\n path_params = _get_flat_fields_from_params(flat_dependant.path_params)\n query_params = _get_flat_fields_from_params(flat_dependant.query_params)\n header_params = _get_flat_fields_from_params(flat_dependant.header_params)\n cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)\n parameter_groups = [\n (ParamTypes.path, path_params),\n (ParamTypes.query, query_params),\n (ParamTypes.header, header_params),\n (ParamTypes.cookie, cookie_params),\n ]\n default_convert_underscores = True\n if len(flat_dependant.header_params) == 1:\n first_field = flat_dependant.header_params[0]\n if lenient_issubclass(first_field.field_info.annotation, BaseModel):\n default_convert_underscores = getattr(\n first_field.field_info, \"convert_underscores\", True\n )\n for param_type, param_group in parameter_groups:\n for param in param_group:\n field_info = param.field_info\n # field_info = cast(Param, field_info)\n if not getattr(field_info, \"include_in_schema\", True):\n continue\n param_schema = get_schema_from_model_field(\n field=param,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n name = get_validation_alias(param)\n convert_underscores = getattr(\n param.field_info,\n \"convert_underscores\",\n default_convert_underscores,\n )\n if (\n param_type == ParamTypes.header\n and name == param.name\n and convert_underscores\n ):\n name = param.name.replace(\"_\", \"-\")\n\n parameter = {\n \"name\": name,\n \"in\": param_type.value,\n \"required\": param.field_info.is_required(),\n \"schema\": param_schema,\n }\n if field_info.description:\n parameter[\"description\"] = field_info.description\n openapi_examples = getattr(field_info, \"openapi_examples\", None)\n example = getattr(field_info, \"example\", None)\n if openapi_examples:\n parameter[\"examples\"] = jsonable_encoder(openapi_examples)\n elif example is not _Unset:\n parameter[\"example\"] = jsonable_encoder(example)\n if getattr(field_info, \"deprecated\", None):\n parameter[\"deprecated\"] = True\n parameters.append(parameter)\n return parameters", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "_get_openapi_operation_parameters", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L107-L177", "start_line": 107, "end_line": 177} {"id": "fastapi/openapi/utils.py::get_openapi_operation_request_body::L180", "text": "# File: fastapi/openapi/utils.py | Symbol: get_openapi_operation_request_body\ndef get_openapi_operation_request_body(\n *,\n body_field: ModelField | None,\n model_name_map: ModelNameMap,\n field_mapping: dict[\n tuple[ModelField, Literal[\"validation\", \"serialization\"]], dict[str, Any]\n ],\n separate_input_output_schemas: bool = True,\n) -> dict[str, Any] | None:\n if not body_field:\n return None\n assert isinstance(body_field, ModelField)\n body_schema = get_schema_from_model_field(\n field=body_field,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n field_info = cast(Body, body_field.field_info)\n request_media_type = field_info.media_type\n required = body_field.field_info.is_required()\n request_body_oai: dict[str, Any] = {}\n if required:\n request_body_oai[\"required\"] = required\n request_media_content: dict[str, Any] = {\"schema\": body_schema}\n if field_info.openapi_examples:\n request_media_content[\"examples\"] = jsonable_encoder(\n field_info.openapi_examples\n )\n elif field_info.example is not _Unset:\n request_media_content[\"example\"] = jsonable_encoder(field_info.example)\n request_body_oai[\"content\"] = {request_media_type: request_media_content}\n return request_body_oai", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "get_openapi_operation_request_body", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L180-L212", "start_line": 180, "end_line": 212} {"id": "fastapi/openapi/utils.py::generate_operation_id::L215", "text": "# File: fastapi/openapi/utils.py | Symbol: generate_operation_id\ndef generate_operation_id(\n *, route: routing._APIRouteLike, method: str\n) -> str: # pragma: nocover\n warnings.warn(\n message=\"fastapi.openapi.utils.generate_operation_id() was deprecated, \"\n \"it is not used internally, and will be removed soon\",\n category=FastAPIDeprecationWarning,\n stacklevel=2,\n )\n if route.operation_id:\n return route.operation_id\n path: str = route.path_format\n return generate_operation_id_for_path(name=route.name, path=path, method=method)", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "generate_operation_id", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L215-L227", "start_line": 215, "end_line": 227} {"id": "fastapi/openapi/utils.py::generate_operation_summary::L230", "text": "# File: fastapi/openapi/utils.py | Symbol: generate_operation_summary\ndef generate_operation_summary(*, route: routing._APIRouteLike, method: str) -> str:\n if route.summary:\n return route.summary\n return route.name.replace(\"_\", \" \").title()", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "generate_operation_summary", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L230-L233", "start_line": 230, "end_line": 233} {"id": "fastapi/openapi/utils.py::get_openapi_operation_metadata::L236", "text": "# File: fastapi/openapi/utils.py | Symbol: get_openapi_operation_metadata\ndef get_openapi_operation_metadata(\n *, route: routing._APIRouteLike, method: str, operation_ids: set[str]\n) -> dict[str, Any]:\n operation: dict[str, Any] = {}\n if route.tags:\n operation[\"tags\"] = route.tags\n operation[\"summary\"] = generate_operation_summary(route=route, method=method)\n if route.description:\n operation[\"description\"] = route.description\n operation_id = route.operation_id or route.unique_id\n if operation_id in operation_ids:\n endpoint_name = getattr(route.endpoint, \"__name__\", \"\")\n message = f\"Duplicate Operation ID {operation_id} for function {endpoint_name}\"\n file_name = getattr(route.endpoint, \"__globals__\", {}).get(\"__file__\")\n if file_name:\n message += f\" at {file_name}\"\n warnings.warn(message, stacklevel=1)\n operation_ids.add(operation_id)\n operation[\"operationId\"] = operation_id\n if route.deprecated:\n operation[\"deprecated\"] = route.deprecated\n return operation", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "get_openapi_operation_metadata", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L236-L257", "start_line": 236, "end_line": 257} {"id": "fastapi/openapi/utils.py::get_openapi_path::L260", "text": "# File: fastapi/openapi/utils.py | Symbol: get_openapi_path\ndef get_openapi_path(\n *,\n route: routing._APIRouteLike,\n operation_ids: set[str],\n model_name_map: ModelNameMap,\n field_mapping: dict[\n tuple[ModelField, Literal[\"validation\", \"serialization\"]], dict[str, Any]\n ],\n separate_input_output_schemas: bool = True,\n) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:\n path = {}\n security_schemes: dict[str, Any] = {}\n definitions: dict[str, Any] = {}\n assert route.methods is not None, \"Methods must be a list\"\n if isinstance(route.response_class, DefaultPlaceholder):\n current_response_class: type[Response] = route.response_class.value\n else:\n current_response_class = route.response_class\n assert current_response_class, \"A response class is needed to generate OpenAPI\"\n route_response_media_type: str | None = current_response_class.media_type\n if route.include_in_schema:\n for method in route.methods:\n operation = get_openapi_operation_metadata(\n route=route, method=method, operation_ids=operation_ids\n )\n parameters: list[dict[str, Any]] = []\n flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True)\n security_definitions, operation_security = get_openapi_security_definitions(\n flat_dependant=flat_dependant\n )\n if operation_security:\n operation.setdefault(\"security\", []).extend(operation_security)\n if security_definitions:\n security_schemes.update(security_definitions)\n operation_parameters = _get_openapi_operation_parameters(\n dependant=route.dependant,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n parameters.extend(operation_parameters)\n if parameters:\n all_parameters = {\n (param[\"in\"], param[\"name\"]): param for param in parameters\n }\n required_parameters = {\n (param[\"in\"], param[\"name\"]): param\n for param in parameters\n if param.get(\"required\")\n }\n # Make sure required definitions of the same parameter take precedence\n # over non-required definitions\n all_parameters.update(required_parameters)\n operation[\"parameters\"] = list(all_parameters.values())\n if method in METHODS_WITH_BODY:\n request_body_oai = get_openapi_operation_request_body(\n body_field=route.body_field,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n if request_body_oai:\n operation[\"requestBody\"] = request_body_oai\n if route.callbacks:\n callbacks = {}\n for callback in route.callbacks:\n if isinstance(callback, routing.APIRoute):\n (\n cb_path,\n cb_security_schemes,\n cb_definitions,\n ) = get_openapi_path(\n route=cast(routing._APIRouteLike, callback),\n operation_ids=operation_ids,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n callbacks[callback.name] = {callback.path: cb_path}\n operation[\"callbacks\"] = callbacks\n if route.status_code is not None:\n status_code = str(route.status_code)\n else:\n # It would probably make more sense for all response classes to have an\n # explicit default status_code, and to extract it from them, instead of\n # doing this inspection tricks, that would probably be in the future\n # TODO: probably make status_code a default class attribute for all\n # responses in Starlette\n response_signature = inspect.signature(current_response_class.__init__)\n status_code_param = response_signature.parameters.get(\"status_code\")\n if status_code_param is not None:\n if isinstance(status_code_param.default, int):\n status_code = str(status_code_param.default)\n operation.setdefault(\"responses\", {}).setdefault(status_code, {})[\n \"description\"\n ] = route.response_description\n if is_body_allowed_for_status_code(route.status_code):\n # Check for JSONL streaming (generator endpoints)\n if route.is_json_stream:\n jsonl_content: dict[str, Any] = {}\n if route.stream_item_field:\n item_schema = get_schema_from_model_field(\n field=route.stream_item_field,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n jsonl_content[\"itemSchema\"] = item_schema\n else:\n jsonl_content[\"itemSchema\"] = {}\n operation.setdefault(\"responses\", {}).setdefault(\n status_code, {}\n ).setdefault(\"content\", {})[\"application/jsonl\"] = jsonl_content\n elif route.is_sse_stream:\n sse_content: dict[str, Any] = {}\n item_schema = copy.deepcopy(_SSE_EVENT_SCHEMA)\n if route.stream_item_field:\n content_schema = get_schema_from_model_field(\n field=route.stream_item_field,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n item_schema[\"required\"] = [\"data\"]\n item_schema[\"properties\"][\"data\"] = {\n \"type\": \"string\",\n \"contentMediaType\": \"application/json\",\n \"contentSchema\": content_schema,\n }\n sse_content[\"itemSchema\"] = item_schema\n operation.setdefault(\"responses\", {}).setdefault(\n status_code, {}\n ).setdefault(\"content\", {})[\"text/event-stream\"] = sse_content\n elif route_response_media_type:\n response_schema = {\"type\": \"string\"}\n if lenient_issubclass(current_response_class, JSONResponse):\n if route.response_field:\n response_schema = get_schema_from_model_field(\n field=route.response_field,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n else:\n response_schema = {}\n operation.setdefault(\"responses\", {}).setdefault(\n status_code, {}\n ).setdefault(\"content\", {}).setdefault(\n route_response_media_type, {}\n )[\"schema\"] = response_schema\n if route.responses:\n operation_responses = operation.setdefault(\"responses\", {})\n for (\n additional_status_code,\n additional_response,\n ) in route.responses.items():\n process_response = copy.deepcopy(additional_response)\n process_response.pop(\"model\", None)\n status_code_key = str(additional_status_code).upper()\n if status_code_key == \"DEFAULT\":\n status_code_key = \"default\"\n openapi_response = operation_responses.setdefault(\n status_code_key, {}\n )\n assert isinstance(process_response, dict), (\n \"An additional response must be a dict\"\n )\n field = route.response_fields.get(additional_status_code)\n additional_field_schema: dict[str, Any] | None = None\n if field:\n additional_field_schema = get_schema_from_model_field(\n field=field,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n media_type = route_response_media_type or \"application/json\"\n additional_schema = (\n process_response.setdefault(\"content\", {})\n .setdefault(media_type, {})\n .setdefault(\"schema\", {})\n )\n deep_dict_update(additional_schema, additional_field_schema)\n status_text: str | None = status_code_ranges.get(\n str(additional_status_code).upper()\n ) or http.client.responses.get(int(additional_status_code))\n description = (\n process_response.get(\"description\")\n or openapi_response.get(\"description\")\n or status_text\n or \"Additional Response\"\n )\n deep_dict_update(openapi_response, process_response)\n openapi_response[\"description\"] = description\n http422 = \"422\"\n all_route_params = get_flat_params(route.dependant)\n if (all_route_params or route.body_field) and not any(\n status in operation[\"responses\"]\n for status in [http422, \"4XX\", \"default\"]\n ):\n operation[\"responses\"][http422] = {\n \"description\": \"Validation Error\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\"$ref\": REF_PREFIX + \"HTTPValidationError\"}\n }\n },\n }\n if \"ValidationError\" not in definitions:\n definitions.update(\n {\n \"ValidationError\": validation_error_definition,\n \"HTTPValidationError\": validation_error_response_definition,\n }\n )\n if route.openapi_extra:\n deep_dict_update(operation, route.openapi_extra)\n path[method.lower()] = operation\n return path, security_schemes, definitions", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "get_openapi_path", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L260-L478", "start_line": 260, "end_line": 478} {"id": "fastapi/openapi/utils.py::_get_api_route_for_openapi::L481", "text": "# File: fastapi/openapi/utils.py | Symbol: _get_api_route_for_openapi\ndef _get_api_route_for_openapi(\n route_context: routing.RouteContext,\n) -> routing._APIRouteLike | None:\n if isinstance(route_context.original_route, routing.APIRoute):\n return cast(routing._APIRouteLike, route_context)\n return None", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "_get_api_route_for_openapi", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L481-L486", "start_line": 481, "end_line": 486} {"id": "fastapi/openapi/utils.py::get_fields_from_routes::L489", "text": "# File: fastapi/openapi/utils.py | Symbol: get_fields_from_routes\ndef get_fields_from_routes(\n routes: Sequence[BaseRoute | routing.RouteContext],\n) -> list[ModelField]:\n body_fields_from_routes: list[ModelField] = []\n responses_from_routes: list[ModelField] = []\n request_fields_from_routes: list[ModelField] = []\n callback_flat_models: list[ModelField] = []\n for route_context in routing.iter_route_contexts(routes):\n api_route = _get_api_route_for_openapi(route_context)\n if api_route is None:\n continue\n if api_route.include_in_schema:\n if api_route.body_field:\n assert isinstance(api_route.body_field, ModelField), (\n \"A request body must be a Pydantic Field\"\n )\n body_fields_from_routes.append(api_route.body_field)\n if api_route.response_field:\n responses_from_routes.append(api_route.response_field)\n if api_route.response_fields:\n responses_from_routes.extend(api_route.response_fields.values())\n if api_route.stream_item_field:\n responses_from_routes.append(api_route.stream_item_field)\n if api_route.callbacks:\n callback_flat_models.extend(get_fields_from_routes(api_route.callbacks))\n params = get_flat_params(api_route.dependant)\n request_fields_from_routes.extend(params)\n\n flat_models = callback_flat_models + list(\n body_fields_from_routes + responses_from_routes + request_fields_from_routes\n )\n return flat_models", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "get_fields_from_routes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L489-L520", "start_line": 489, "end_line": 520} {"id": "fastapi/openapi/utils.py::get_openapi::L523", "text": "# File: fastapi/openapi/utils.py | Symbol: get_openapi\ndef get_openapi(\n *,\n title: str,\n version: str,\n openapi_version: str = \"3.1.0\",\n summary: str | None = None,\n description: str | None = None,\n routes: Sequence[BaseRoute | routing.RouteContext],\n webhooks: Sequence[BaseRoute | routing.RouteContext] | None = None,\n tags: list[dict[str, Any]] | None = None,\n servers: list[dict[str, str | Any]] | None = None,\n terms_of_service: str | None = None,\n contact: dict[str, str | Any] | None = None,\n license_info: dict[str, str | Any] | None = None,\n separate_input_output_schemas: bool = True,\n external_docs: dict[str, Any] | None = None,\n) -> dict[str, Any]:\n info: dict[str, Any] = {\"title\": title, \"version\": version}\n if summary:\n info[\"summary\"] = summary\n if description:\n info[\"description\"] = description\n if terms_of_service:\n info[\"termsOfService\"] = terms_of_service\n if contact:\n info[\"contact\"] = contact\n if license_info:\n info[\"license\"] = license_info\n output: dict[str, Any] = {\"openapi\": openapi_version, \"info\": info}\n if servers:\n output[\"servers\"] = servers\n components: dict[str, dict[str, Any]] = {}\n paths: dict[str, dict[str, Any]] = {}\n webhook_paths: dict[str, dict[str, Any]] = {}\n operation_ids: set[str] = set()\n all_fields = get_fields_from_routes(list(routes) + list(webhooks or []))\n flat_models = get_flat_models_from_fields(all_fields, known_models=set())\n model_name_map = get_model_name_map(flat_models)\n field_mapping, definitions = get_definitions(\n fields=all_fields,\n model_name_map=model_name_map,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n for route_context in routing.iter_route_contexts(routes):\n api_route = _get_api_route_for_openapi(route_context)\n if api_route is not None:\n result = get_openapi_path(\n route=api_route,\n operation_ids=operation_ids,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n if result:\n path, security_schemes, path_definitions = result\n if path:\n paths.setdefault(api_route.path_format, {}).update(path)\n if security_schemes:\n components.setdefault(\"securitySchemes\", {}).update(\n security_schemes\n )\n if path_definitions:\n definitions.update(path_definitions)\n for webhook_context in routing.iter_route_contexts(webhooks or []):\n api_webhook = _get_api_route_for_openapi(webhook_context)\n if api_webhook is not None:\n result = get_openapi_path(\n route=api_webhook,\n operation_ids=operation_ids,\n model_name_map=model_name_map,\n field_mapping=field_mapping,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n if result:\n path, security_schemes, path_definitions = result\n if path:\n webhook_paths.setdefault(api_webhook.path_format, {}).update(path)\n if security_schemes:\n components.setdefault(\"securitySchemes\", {}).update(\n security_schemes\n )\n if path_definitions:\n definitions.update(path_definitions)\n if definitions:\n components[\"schemas\"] = {k: definitions[k] for k in sorted(definitions)}\n if components:\n output[\"components\"] = components\n output[\"paths\"] = paths\n if webhook_paths:\n output[\"webhooks\"] = webhook_paths\n if tags:\n output[\"tags\"] = tags\n if external_docs:\n output[\"externalDocs\"] = external_docs\n return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore[no-any-return]", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "get_openapi", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L523-L617", "start_line": 523, "end_line": 617} {"id": "fastapi/openapi/utils.py::", "text": "# File: fastapi/openapi/utils.py | Symbol: \nimport copy\nimport http.client\nimport inspect\nimport warnings\nfrom collections.abc import Sequence\nfrom typing import Any, Literal, cast\nfrom fastapi import routing\nfrom fastapi._compat import (\n ModelField,\n get_definitions,\n get_flat_models_from_fields,\n get_model_name_map,\n get_schema_from_model_field,\n lenient_issubclass,\n)\nfrom fastapi.datastructures import DefaultPlaceholder, _Unset\nfrom fastapi.dependencies.models import Dependant\nfrom fastapi.dependencies.utils import (\n _get_flat_fields_from_params,\n get_flat_dependant,\n get_flat_params,\n get_validation_alias,\n)\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.exceptions import FastAPIDeprecationWarning\nfrom fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX\nfrom fastapi.openapi.models import OpenAPI\nfrom fastapi.params import Body, ParamTypes\nfrom fastapi.responses import Response\nfrom fastapi.sse import _SSE_EVENT_SCHEMA\nfrom fastapi.types import ModelNameMap\nfrom fastapi.utils import (\n deep_dict_update,\n generate_operation_id_for_path,\n is_body_allowed_for_status_code,\n)\nfrom pydantic import BaseModel\nfrom starlette.responses import JSONResponse\nfrom starlette.routing import BaseRoute\nvalidation_error_definition = {\n \"title\": \"ValidationError\",\n \"type\": \"object\",\n \"properties\": {\n \"loc\": {\n \"title\": \"Location\",\n \"type\": \"array\",\n \"items\": {\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]},\n },\n \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n \"type\": {\"title\": \"Error Type\", \"type\": \"string\"},\n \"input\": {\"title\": \"Input\"},\n \"ctx\": {\"title\": \"Context\", \"type\": \"object\"},\n },\n \"required\": [\"loc\", \"msg\", \"type\"],\n}\nvalidation_error_response_definition = {\n \"title\": \"HTTPValidationError\",\n \"type\": \"object\",\n \"properties\": {\n \"detail\": {\n \"title\": \"Detail\",\n \"type\": \"array\",\n \"items\": {\"$ref\": REF_PREFIX + \"ValidationError\"},\n }\n },\n}\nstatus_code_ranges: dict[str, str] = {\n \"1XX\": \"Information\",\n \"2XX\": \"Success\",\n \"3XX\": \"Redirection\",\n \"4XX\": \"Client Error\",\n \"5XX\": \"Server Error\",\n \"DEFAULT\": \"Default Response\",\n}", "source_type": "code", "path": "fastapi/openapi/utils.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/openapi/utils.py#L1-L78", "start_line": 1, "end_line": 78} {"id": "fastapi/param_functions.py::Path::L13", "text": "# File: fastapi/param_functions.py | Symbol: Path\ndef Path( # noqa: N802\n default: Annotated[\n Any,\n Doc(\n \"\"\"\n Default value if the parameter field is not set.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = ...,\n *,\n default_factory: Annotated[\n Callable[[], Any] | None,\n Doc(\n \"\"\"\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = _Unset,\n alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n \"\"\"\n ),\n ] = None,\n alias_priority: Annotated[\n int | None,\n Doc(\n \"\"\"\n Priority of the alias. This affects whether an alias generator is used.\n \"\"\"\n ),\n ] = _Unset,\n validation_alias: Annotated[\n str | AliasPath | AliasChoices | None,\n Doc(\n \"\"\"\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n \"\"\"\n ),\n ] = None,\n serialization_alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n \"\"\"\n ),\n ] = None,\n title: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable title.\n\n Read more about it in the\n [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#declare-metadata)\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable description.\n \"\"\"\n ),\n ] = None,\n gt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n ge: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n lt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than. If set, value must be less than this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n le: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n min_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Minimum length for strings.\n \"\"\"\n ),\n ] = None,\n max_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum length for strings.\n \"\"\"\n ),\n ] = None,\n pattern: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n ] = None,\n regex: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: Annotated[\n str | None,\n Doc(\n \"\"\"\n Parameter field name for discriminating the type in a tagged union.\n \"\"\"\n ),\n ] = None,\n strict: Annotated[\n bool | None,\n Doc(\n \"\"\"\n If `True`, strict validation is applied to the field.\n \"\"\"\n ),\n ] = _Unset,\n multiple_of: Annotated[\n float | None,\n Doc(\n \"\"\"\n Value must be a multiple of this. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n allow_inf_nan: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n max_digits: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of digits allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n decimal_places: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of decimal places allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n examples: Annotated[\n list[Any] | None,\n Doc(\n \"\"\"\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n \"\"\"\n ),\n ] = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: Annotated[\n dict[str, Example] | None,\n Doc(\n \"\"\"\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n deprecated | str | bool | None,\n Doc(\n \"\"\"\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = True,\n json_schema_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Any additional JSON schema data.\n \"\"\"\n ),\n ] = None,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Include extra fields used by the JSON Schema.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n The `extra` kwargs is deprecated. Use `json_schema_extra` instead.\n \"\"\"\n ),\n ],\n) -> Any:\n \"\"\"\n Declare a path parameter for a *path operation*.\n\n Read more about it in the\n [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/).\n\n ```python\n from typing import Annotated\n\n from fastapi import FastAPI, Path\n\n app = FastAPI()\n\n\n @app.get(\"/items/{item_id}\")\n async def read_items(\n item_id: Annotated[int, Path(title=\"The ID of the item to get\")],\n ):\n return {\"item_id\": item_id}\n ```\n \"\"\"\n return params.Path(\n default=default,\n default_factory=default_factory,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Path", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L13-L354", "start_line": 13, "end_line": 354} {"id": "fastapi/param_functions.py::Query::L357", "text": "# File: fastapi/param_functions.py | Symbol: Query\ndef Query( # noqa: N802\n default: Annotated[\n Any,\n Doc(\n \"\"\"\n Default value if the parameter field is not set.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alternative-old-query-as-the-default-value)\n \"\"\"\n ),\n ] = Undefined,\n *,\n default_factory: Annotated[\n Callable[[], Any] | None,\n Doc(\n \"\"\"\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = _Unset,\n alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters)\n \"\"\"\n ),\n ] = None,\n alias_priority: Annotated[\n int | None,\n Doc(\n \"\"\"\n Priority of the alias. This affects whether an alias generator is used.\n \"\"\"\n ),\n ] = _Unset,\n validation_alias: Annotated[\n str | AliasPath | AliasChoices | None,\n Doc(\n \"\"\"\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n \"\"\"\n ),\n ] = None,\n serialization_alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n \"\"\"\n ),\n ] = None,\n title: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable title.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable description.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)\n \"\"\"\n ),\n ] = None,\n gt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n ge: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n lt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than. If set, value must be less than this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n le: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n \"\"\"\n ),\n ] = None,\n min_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Minimum length for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)\n \"\"\"\n ),\n ] = None,\n max_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum length for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)\n \"\"\"\n ),\n ] = None,\n pattern: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions\n \"\"\"\n ),\n ] = None,\n regex: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: Annotated[\n str | None,\n Doc(\n \"\"\"\n Parameter field name for discriminating the type in a tagged union.\n \"\"\"\n ),\n ] = None,\n strict: Annotated[\n bool | None,\n Doc(\n \"\"\"\n If `True`, strict validation is applied to the field.\n \"\"\"\n ),\n ] = _Unset,\n multiple_of: Annotated[\n float | None,\n Doc(\n \"\"\"\n Value must be a multiple of this. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n allow_inf_nan: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n max_digits: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of digits allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n decimal_places: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of decimal places allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n examples: Annotated[\n list[Any] | None,\n Doc(\n \"\"\"\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n \"\"\"\n ),\n ] = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: Annotated[\n dict[str, Example] | None,\n Doc(\n \"\"\"\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n deprecated | str | bool | None,\n Doc(\n \"\"\"\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#deprecating-parameters)\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi\n \"\"\"\n ),\n ] = True,\n json_schema_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Any additional JSON schema data.\n \"\"\"\n ),\n ] = None,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Include extra fields used by the JSON Schema.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n The `extra` kwargs is deprecated. Use `json_schema_extra` instead.\n \"\"\"\n ),\n ],\n) -> Any:\n return params.Query(\n default=default,\n default_factory=default_factory,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Query", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L357-L698", "start_line": 357, "end_line": 698} {"id": "fastapi/param_functions.py::Header::L701", "text": "# File: fastapi/param_functions.py | Symbol: Header\ndef Header( # noqa: N802\n default: Annotated[\n Any,\n Doc(\n \"\"\"\n Default value if the parameter field is not set.\n \"\"\"\n ),\n ] = Undefined,\n *,\n default_factory: Annotated[\n Callable[[], Any] | None,\n Doc(\n \"\"\"\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = _Unset,\n alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n \"\"\"\n ),\n ] = None,\n alias_priority: Annotated[\n int | None,\n Doc(\n \"\"\"\n Priority of the alias. This affects whether an alias generator is used.\n \"\"\"\n ),\n ] = _Unset,\n validation_alias: Annotated[\n str | AliasPath | AliasChoices | None,\n Doc(\n \"\"\"\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n \"\"\"\n ),\n ] = None,\n serialization_alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n \"\"\"\n ),\n ] = None,\n convert_underscores: Annotated[\n bool,\n Doc(\n \"\"\"\n Automatically convert underscores to hyphens in the parameter field name.\n\n Read more about it in the\n [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion)\n \"\"\"\n ),\n ] = True,\n title: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable title.\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable description.\n \"\"\"\n ),\n ] = None,\n gt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n \"\"\"\n ),\n ] = None,\n ge: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n lt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than. If set, value must be less than this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n le: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n min_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Minimum length for strings.\n \"\"\"\n ),\n ] = None,\n max_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum length for strings.\n \"\"\"\n ),\n ] = None,\n pattern: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n ] = None,\n regex: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: Annotated[\n str | None,\n Doc(\n \"\"\"\n Parameter field name for discriminating the type in a tagged union.\n \"\"\"\n ),\n ] = None,\n strict: Annotated[\n bool | None,\n Doc(\n \"\"\"\n If `True`, strict validation is applied to the field.\n \"\"\"\n ),\n ] = _Unset,\n multiple_of: Annotated[\n float | None,\n Doc(\n \"\"\"\n Value must be a multiple of this. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n allow_inf_nan: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n max_digits: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of digits allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n decimal_places: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of decimal places allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n examples: Annotated[\n list[Any] | None,\n Doc(\n \"\"\"\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n \"\"\"\n ),\n ] = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: Annotated[\n dict[str, Example] | None,\n Doc(\n \"\"\"\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n deprecated | str | bool | None,\n Doc(\n \"\"\"\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = True,\n json_schema_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Any additional JSON schema data.\n \"\"\"\n ),\n ] = None,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Include extra fields used by the JSON Schema.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n The `extra` kwargs is deprecated. Use `json_schema_extra` instead.\n \"\"\"\n ),\n ],\n) -> Any:\n return params.Header(\n default=default,\n default_factory=default_factory,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n convert_underscores=convert_underscores,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Header", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L701-L1015", "start_line": 701, "end_line": 1015} {"id": "fastapi/param_functions.py::Cookie::L1018", "text": "# File: fastapi/param_functions.py | Symbol: Cookie\ndef Cookie( # noqa: N802\n default: Annotated[\n Any,\n Doc(\n \"\"\"\n Default value if the parameter field is not set.\n \"\"\"\n ),\n ] = Undefined,\n *,\n default_factory: Annotated[\n Callable[[], Any] | None,\n Doc(\n \"\"\"\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = _Unset,\n alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n \"\"\"\n ),\n ] = None,\n alias_priority: Annotated[\n int | None,\n Doc(\n \"\"\"\n Priority of the alias. This affects whether an alias generator is used.\n \"\"\"\n ),\n ] = _Unset,\n validation_alias: Annotated[\n str | AliasPath | AliasChoices | None,\n Doc(\n \"\"\"\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n \"\"\"\n ),\n ] = None,\n serialization_alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n \"\"\"\n ),\n ] = None,\n title: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable title.\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable description.\n \"\"\"\n ),\n ] = None,\n gt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n \"\"\"\n ),\n ] = None,\n ge: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n lt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than. If set, value must be less than this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n le: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n min_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Minimum length for strings.\n \"\"\"\n ),\n ] = None,\n max_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum length for strings.\n \"\"\"\n ),\n ] = None,\n pattern: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n ] = None,\n regex: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: Annotated[\n str | None,\n Doc(\n \"\"\"\n Parameter field name for discriminating the type in a tagged union.\n \"\"\"\n ),\n ] = None,\n strict: Annotated[\n bool | None,\n Doc(\n \"\"\"\n If `True`, strict validation is applied to the field.\n \"\"\"\n ),\n ] = _Unset,\n multiple_of: Annotated[\n float | None,\n Doc(\n \"\"\"\n Value must be a multiple of this. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n allow_inf_nan: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n max_digits: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of digits allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n decimal_places: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of decimal places allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n examples: Annotated[\n list[Any] | None,\n Doc(\n \"\"\"\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n \"\"\"\n ),\n ] = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: Annotated[\n dict[str, Example] | None,\n Doc(\n \"\"\"\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n deprecated | str | bool | None,\n Doc(\n \"\"\"\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = True,\n json_schema_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Any additional JSON schema data.\n \"\"\"\n ),\n ] = None,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Include extra fields used by the JSON Schema.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n The `extra` kwargs is deprecated. Use `json_schema_extra` instead.\n \"\"\"\n ),\n ],\n) -> Any:\n return params.Cookie(\n default=default,\n default_factory=default_factory,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Cookie", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L1018-L1320", "start_line": 1018, "end_line": 1320} {"id": "fastapi/param_functions.py::Body::L1323", "text": "# File: fastapi/param_functions.py | Symbol: Body\ndef Body( # noqa: N802\n default: Annotated[\n Any,\n Doc(\n \"\"\"\n Default value if the parameter field is not set.\n \"\"\"\n ),\n ] = Undefined,\n *,\n default_factory: Annotated[\n Callable[[], Any] | None,\n Doc(\n \"\"\"\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = _Unset,\n embed: Annotated[\n bool | None,\n Doc(\n \"\"\"\n When `embed` is `True`, the parameter will be expected in a JSON body as a\n key instead of being the JSON body itself.\n\n This happens automatically when more than one `Body` parameter is declared.\n\n Read more about it in the\n [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter).\n \"\"\"\n ),\n ] = None,\n media_type: Annotated[\n str,\n Doc(\n \"\"\"\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n \"\"\"\n ),\n ] = \"application/json\",\n alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n \"\"\"\n ),\n ] = None,\n alias_priority: Annotated[\n int | None,\n Doc(\n \"\"\"\n Priority of the alias. This affects whether an alias generator is used.\n \"\"\"\n ),\n ] = _Unset,\n validation_alias: Annotated[\n str | AliasPath | AliasChoices | None,\n Doc(\n \"\"\"\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n \"\"\"\n ),\n ] = None,\n serialization_alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n \"\"\"\n ),\n ] = None,\n title: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable title.\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable description.\n \"\"\"\n ),\n ] = None,\n gt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n \"\"\"\n ),\n ] = None,\n ge: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n lt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than. If set, value must be less than this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n le: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n min_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Minimum length for strings.\n \"\"\"\n ),\n ] = None,\n max_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum length for strings.\n \"\"\"\n ),\n ] = None,\n pattern: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n ] = None,\n regex: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: Annotated[\n str | None,\n Doc(\n \"\"\"\n Parameter field name for discriminating the type in a tagged union.\n \"\"\"\n ),\n ] = None,\n strict: Annotated[\n bool | None,\n Doc(\n \"\"\"\n If `True`, strict validation is applied to the field.\n \"\"\"\n ),\n ] = _Unset,\n multiple_of: Annotated[\n float | None,\n Doc(\n \"\"\"\n Value must be a multiple of this. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n allow_inf_nan: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n max_digits: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of digits allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n decimal_places: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of decimal places allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n examples: Annotated[\n list[Any] | None,\n Doc(\n \"\"\"\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n \"\"\"\n ),\n ] = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: Annotated[\n dict[str, Example] | None,\n Doc(\n \"\"\"\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n deprecated | str | bool | None,\n Doc(\n \"\"\"\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = True,\n json_schema_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Any additional JSON schema data.\n \"\"\"\n ),\n ] = None,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Include extra fields used by the JSON Schema.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n The `extra` kwargs is deprecated. Use `json_schema_extra` instead.\n \"\"\"\n ),\n ],\n) -> Any:\n return params.Body(\n default=default,\n default_factory=default_factory,\n embed=embed,\n media_type=media_type,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Body", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L1323-L1650", "start_line": 1323, "end_line": 1650} {"id": "fastapi/param_functions.py::Form::L1653", "text": "# File: fastapi/param_functions.py | Symbol: Form\ndef Form( # noqa: N802\n default: Annotated[\n Any,\n Doc(\n \"\"\"\n Default value if the parameter field is not set.\n \"\"\"\n ),\n ] = Undefined,\n *,\n default_factory: Annotated[\n Callable[[], Any] | None,\n Doc(\n \"\"\"\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = _Unset,\n media_type: Annotated[\n str,\n Doc(\n \"\"\"\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n \"\"\"\n ),\n ] = \"application/x-www-form-urlencoded\",\n alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n \"\"\"\n ),\n ] = None,\n alias_priority: Annotated[\n int | None,\n Doc(\n \"\"\"\n Priority of the alias. This affects whether an alias generator is used.\n \"\"\"\n ),\n ] = _Unset,\n validation_alias: Annotated[\n str | AliasPath | AliasChoices | None,\n Doc(\n \"\"\"\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n \"\"\"\n ),\n ] = None,\n serialization_alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n \"\"\"\n ),\n ] = None,\n title: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable title.\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable description.\n \"\"\"\n ),\n ] = None,\n gt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n \"\"\"\n ),\n ] = None,\n ge: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n lt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than. If set, value must be less than this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n le: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n min_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Minimum length for strings.\n \"\"\"\n ),\n ] = None,\n max_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum length for strings.\n \"\"\"\n ),\n ] = None,\n pattern: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n ] = None,\n regex: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: Annotated[\n str | None,\n Doc(\n \"\"\"\n Parameter field name for discriminating the type in a tagged union.\n \"\"\"\n ),\n ] = None,\n strict: Annotated[\n bool | None,\n Doc(\n \"\"\"\n If `True`, strict validation is applied to the field.\n \"\"\"\n ),\n ] = _Unset,\n multiple_of: Annotated[\n float | None,\n Doc(\n \"\"\"\n Value must be a multiple of this. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n allow_inf_nan: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n max_digits: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of digits allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n decimal_places: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of decimal places allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n examples: Annotated[\n list[Any] | None,\n Doc(\n \"\"\"\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n \"\"\"\n ),\n ] = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: Annotated[\n dict[str, Example] | None,\n Doc(\n \"\"\"\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n deprecated | str | bool | None,\n Doc(\n \"\"\"\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = True,\n json_schema_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Any additional JSON schema data.\n \"\"\"\n ),\n ] = None,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Include extra fields used by the JSON Schema.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n The `extra` kwargs is deprecated. Use `json_schema_extra` instead.\n \"\"\"\n ),\n ],\n) -> Any:\n return params.Form(\n default=default,\n default_factory=default_factory,\n media_type=media_type,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Form", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L1653-L1965", "start_line": 1653, "end_line": 1965} {"id": "fastapi/param_functions.py::File::L1968", "text": "# File: fastapi/param_functions.py | Symbol: File\ndef File( # noqa: N802\n default: Annotated[\n Any,\n Doc(\n \"\"\"\n Default value if the parameter field is not set.\n \"\"\"\n ),\n ] = Undefined,\n *,\n default_factory: Annotated[\n Callable[[], Any] | None,\n Doc(\n \"\"\"\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n \"\"\"\n ),\n ] = _Unset,\n media_type: Annotated[\n str,\n Doc(\n \"\"\"\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n \"\"\"\n ),\n ] = \"multipart/form-data\",\n alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n \"\"\"\n ),\n ] = None,\n alias_priority: Annotated[\n int | None,\n Doc(\n \"\"\"\n Priority of the alias. This affects whether an alias generator is used.\n \"\"\"\n ),\n ] = _Unset,\n validation_alias: Annotated[\n str | AliasPath | AliasChoices | None,\n Doc(\n \"\"\"\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n \"\"\"\n ),\n ] = None,\n serialization_alias: Annotated[\n str | None,\n Doc(\n \"\"\"\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n \"\"\"\n ),\n ] = None,\n title: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable title.\n \"\"\"\n ),\n ] = None,\n description: Annotated[\n str | None,\n Doc(\n \"\"\"\n Human-readable description.\n \"\"\"\n ),\n ] = None,\n gt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n \"\"\"\n ),\n ] = None,\n ge: Annotated[\n float | None,\n Doc(\n \"\"\"\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n lt: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than. If set, value must be less than this. Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n le: Annotated[\n float | None,\n Doc(\n \"\"\"\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n \"\"\"\n ),\n ] = None,\n min_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Minimum length for strings.\n \"\"\"\n ),\n ] = None,\n max_length: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum length for strings.\n \"\"\"\n ),\n ] = None,\n pattern: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n ] = None,\n regex: Annotated[\n str | None,\n Doc(\n \"\"\"\n RegEx pattern for strings.\n \"\"\"\n ),\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: Annotated[\n str | None,\n Doc(\n \"\"\"\n Parameter field name for discriminating the type in a tagged union.\n \"\"\"\n ),\n ] = None,\n strict: Annotated[\n bool | None,\n Doc(\n \"\"\"\n If `True`, strict validation is applied to the field.\n \"\"\"\n ),\n ] = _Unset,\n multiple_of: Annotated[\n float | None,\n Doc(\n \"\"\"\n Value must be a multiple of this. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n allow_inf_nan: Annotated[\n bool | None,\n Doc(\n \"\"\"\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n \"\"\"\n ),\n ] = _Unset,\n max_digits: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of digits allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n decimal_places: Annotated[\n int | None,\n Doc(\n \"\"\"\n Maximum number of decimal places allowed for decimal values.\n \"\"\"\n ),\n ] = _Unset,\n examples: Annotated[\n list[Any] | None,\n Doc(\n \"\"\"\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n \"\"\"\n ),\n ] = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: Annotated[\n dict[str, Example] | None,\n Doc(\n \"\"\"\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n \"\"\"\n ),\n ] = None,\n deprecated: Annotated[\n deprecated | str | bool | None,\n Doc(\n \"\"\"\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = None,\n include_in_schema: Annotated[\n bool,\n Doc(\n \"\"\"\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n \"\"\"\n ),\n ] = True,\n json_schema_extra: Annotated[\n dict[str, Any] | None,\n Doc(\n \"\"\"\n Any additional JSON schema data.\n \"\"\"\n ),\n ] = None,\n **extra: Annotated[\n Any,\n Doc(\n \"\"\"\n Include extra fields used by the JSON Schema.\n \"\"\"\n ),\n deprecated(\n \"\"\"\n The `extra` kwargs is deprecated. Use `json_schema_extra` instead.\n \"\"\"\n ),\n ],\n) -> Any:\n return params.File(\n default=default,\n default_factory=default_factory,\n media_type=media_type,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "File", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L1968-L2280", "start_line": 1968, "end_line": 2280} {"id": "fastapi/param_functions.py::Depends::L2283", "text": "# File: fastapi/param_functions.py | Symbol: Depends\ndef Depends( # noqa: N802\n dependency: Annotated[\n Callable[..., Any] | None,\n Doc(\n \"\"\"\n A \"dependable\" callable (like a function).\n\n Don't call it directly, FastAPI will call it for you, just pass the object\n directly.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)\n \"\"\"\n ),\n ] = None,\n *,\n use_cache: Annotated[\n bool,\n Doc(\n \"\"\"\n By default, after a dependency is called the first time in a request, if\n the dependency is declared again for the rest of the request (for example\n if the dependency is needed by several dependencies), the value will be\n re-used for the rest of the request.\n\n Set `use_cache` to `False` to disable this behavior and ensure the\n dependency is called again (if declared more than once) in the same request.\n\n Read more about it in the\n [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)\n \"\"\"\n ),\n ] = True,\n scope: Annotated[\n Literal[\"function\", \"request\"] | None,\n Doc(\n \"\"\"\n Mainly for dependencies with `yield`, define when the dependency function\n should start (the code before `yield`) and when it should end (the code\n after `yield`).\n\n * `\"function\"`: start the dependency before the *path operation function*\n that handles the request, end the dependency after the *path operation\n function* ends, but **before** the response is sent back to the client.\n So, the dependency function will be executed **around** the *path operation\n **function***.\n * `\"request\"`: start the dependency before the *path operation function*\n that handles the request (similar to when using `\"function\"`), but end\n **after** the response is sent back to the client. So, the dependency\n function will be executed **around** the **request** and response cycle.\n\n Read more about it in the\n [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope)\n \"\"\"\n ),\n ] = None,\n) -> Any:\n \"\"\"\n Declare a FastAPI dependency.\n\n It takes a single \"dependable\" callable (like a function).\n\n Don't call it directly, FastAPI will call it for you.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/).\n\n **Example**\n\n ```python\n from typing import Annotated\n\n from fastapi import Depends, FastAPI\n\n app = FastAPI()\n\n\n async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):\n return {\"q\": q, \"skip\": skip, \"limit\": limit}\n\n\n @app.get(\"/items/\")\n async def read_items(commons: Annotated[dict, Depends(common_parameters)]):\n return commons\n ```\n \"\"\"\n return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope)", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Depends", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L2283-L2369", "start_line": 2283, "end_line": 2369} {"id": "fastapi/param_functions.py::Security::L2372", "text": "# File: fastapi/param_functions.py | Symbol: Security\ndef Security( # noqa: N802\n dependency: Annotated[\n Callable[..., Any] | None,\n Doc(\n \"\"\"\n A \"dependable\" callable (like a function).\n\n Don't call it directly, FastAPI will call it for you, just pass the object\n directly.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)\n \"\"\"\n ),\n ] = None,\n *,\n scopes: Annotated[\n Sequence[str] | None,\n Doc(\n \"\"\"\n OAuth2 scopes required for the *path operation* that uses this Security\n dependency.\n\n The term \"scope\" comes from the OAuth2 specification, it seems to be\n intentionally vague and interpretable. It normally refers to permissions,\n in cases to roles.\n\n These scopes are integrated with OpenAPI (and the API docs at `/docs`).\n So they are visible in the OpenAPI specification.\n\n Read more about it in the\n [FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/)\n \"\"\"\n ),\n ] = None,\n use_cache: Annotated[\n bool,\n Doc(\n \"\"\"\n By default, after a dependency is called the first time in a request, if\n the dependency is declared again for the rest of the request (for example\n if the dependency is needed by several dependencies), the value will be\n re-used for the rest of the request.\n\n Set `use_cache` to `False` to disable this behavior and ensure the\n dependency is called again (if declared more than once) in the same request.\n\n Read more about it in the\n [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)\n \"\"\"\n ),\n ] = True,\n) -> Any:\n \"\"\"\n Declare a FastAPI Security dependency.\n\n The only difference with a regular dependency is that it can declare OAuth2\n scopes that will be integrated with OpenAPI and the automatic UI docs (by default\n at `/docs`).\n\n It takes a single \"dependable\" callable (like a function).\n\n Don't call it directly, FastAPI will call it for you.\n\n Read more about it in the\n [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and\n in the\n [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).\n\n **Example**\n\n ```python\n from typing import Annotated\n\n from fastapi import Security, FastAPI\n\n from .db import User\n from .security import get_current_active_user\n\n app = FastAPI()\n\n @app.get(\"/users/me/items/\")\n async def read_own_items(\n current_user: Annotated[User, Security(get_current_active_user, scopes=[\"items\"])]\n ):\n return [{\"item_id\": \"Foo\", \"owner\": current_user.username}]\n ```\n \"\"\"\n return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "Security", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L2372-L2460", "start_line": 2372, "end_line": 2460} {"id": "fastapi/param_functions.py::", "text": "# File: fastapi/param_functions.py | Symbol: \nfrom collections.abc import Callable, Sequence\nfrom typing import Annotated, Any, Literal\nfrom annotated_doc import Doc\nfrom fastapi import params\nfrom fastapi._compat import Undefined\nfrom fastapi.datastructures import _Unset\nfrom fastapi.openapi.models import Example\nfrom pydantic import AliasChoices, AliasPath\nfrom typing_extensions import deprecated", "source_type": "code", "path": "fastapi/param_functions.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/param_functions.py#L1-L10", "start_line": 1, "end_line": 10} {"id": "fastapi/params.py::ParamTypes::L19", "text": "# File: fastapi/params.py | Symbol: ParamTypes\nclass ParamTypes(Enum):\n query = \"query\"\n header = \"header\"\n path = \"path\"\n cookie = \"cookie\"", "source_type": "code", "path": "fastapi/params.py", "symbol": "ParamTypes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L19-L23", "start_line": 19, "end_line": 23} {"id": "fastapi/params.py::Param::L26", "text": "# File: fastapi/params.py | Symbol: Param\nclass Param(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class]\n in_: ParamTypes\n\n def __init__(\n self,\n default: Any = Undefined,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n if example is not _Unset:\n warnings.warn(\n \"`example` has been deprecated, please use `examples` instead\",\n category=FastAPIDeprecationWarning,\n stacklevel=4,\n )\n self.example = example\n self.include_in_schema = include_in_schema\n self.openapi_examples = openapi_examples\n kwargs = dict(\n default=default,\n default_factory=default_factory,\n alias=alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n discriminator=discriminator,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n **extra,\n )\n if examples is not None:\n kwargs[\"examples\"] = examples\n if regex is not None:\n warnings.warn(\n \"`regex` has been deprecated, please use `pattern` instead\",\n category=FastAPIDeprecationWarning,\n stacklevel=4,\n )\n current_json_schema_extra = json_schema_extra or extra\n kwargs[\"deprecated\"] = deprecated\n\n if serialization_alias in (_Unset, None) and isinstance(alias, str):\n serialization_alias = alias\n if validation_alias in (_Unset, None):\n validation_alias = alias\n kwargs.update(\n {\n \"annotation\": annotation,\n \"alias_priority\": alias_priority,\n \"validation_alias\": validation_alias,\n \"serialization_alias\": serialization_alias,\n \"strict\": strict,\n \"json_schema_extra\": current_json_schema_extra,\n }\n )\n kwargs[\"pattern\"] = pattern or regex\n\n use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}\n\n super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type]\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({self.default})\"", "source_type": "code", "path": "fastapi/params.py", "symbol": "Param", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L26-L134", "start_line": 26, "end_line": 134} {"id": "fastapi/params.py::Path::L137", "text": "# File: fastapi/params.py | Symbol: Path\nclass Path(Param): # type: ignore[misc]\n in_ = ParamTypes.path\n\n def __init__(\n self,\n default: Any = ...,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n assert default is ..., \"Path parameters cannot have a default value\"\n self.in_ = self.in_\n super().__init__(\n default=default,\n default_factory=default_factory,\n annotation=annotation,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n deprecated=deprecated,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/params.py", "symbol": "Path", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L137-L218", "start_line": 137, "end_line": 218} {"id": "fastapi/params.py::Query::L221", "text": "# File: fastapi/params.py | Symbol: Query\nclass Query(Param): # type: ignore[misc]\n in_ = ParamTypes.query\n\n def __init__(\n self,\n default: Any = Undefined,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n super().__init__(\n default=default,\n default_factory=default_factory,\n annotation=annotation,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n deprecated=deprecated,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/params.py", "symbol": "Query", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L221-L300", "start_line": 221, "end_line": 300} {"id": "fastapi/params.py::Header::L303", "text": "# File: fastapi/params.py | Symbol: Header\nclass Header(Param): # type: ignore[misc]\n in_ = ParamTypes.header\n\n def __init__(\n self,\n default: Any = Undefined,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n convert_underscores: bool = True,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n self.convert_underscores = convert_underscores\n super().__init__(\n default=default,\n default_factory=default_factory,\n annotation=annotation,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n deprecated=deprecated,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/params.py", "symbol": "Header", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L303-L384", "start_line": 303, "end_line": 384} {"id": "fastapi/params.py::Cookie::L387", "text": "# File: fastapi/params.py | Symbol: Cookie\nclass Cookie(Param): # type: ignore[misc]\n in_ = ParamTypes.cookie\n\n def __init__(\n self,\n default: Any = Undefined,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n super().__init__(\n default=default,\n default_factory=default_factory,\n annotation=annotation,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n deprecated=deprecated,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/params.py", "symbol": "Cookie", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L387-L466", "start_line": 387, "end_line": 466} {"id": "fastapi/params.py::Body::L469", "text": "# File: fastapi/params.py | Symbol: Body\nclass Body(FieldInfo): # type: ignore[misc] # ty: ignore[subclass-of-final-class]\n def __init__(\n self,\n default: Any = Undefined,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n embed: bool | None = None,\n media_type: str = \"application/json\",\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n self.embed = embed\n self.media_type = media_type\n if example is not _Unset:\n warnings.warn(\n \"`example` has been deprecated, please use `examples` instead\",\n category=FastAPIDeprecationWarning,\n stacklevel=4,\n )\n self.example = example\n self.include_in_schema = include_in_schema\n self.openapi_examples = openapi_examples\n kwargs = dict(\n default=default,\n default_factory=default_factory,\n alias=alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n discriminator=discriminator,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n **extra,\n )\n if examples is not None:\n kwargs[\"examples\"] = examples\n if regex is not None:\n warnings.warn(\n \"`regex` has been deprecated, please use `pattern` instead\",\n category=FastAPIDeprecationWarning,\n stacklevel=4,\n )\n current_json_schema_extra = json_schema_extra or extra\n kwargs[\"deprecated\"] = deprecated\n if serialization_alias in (_Unset, None) and isinstance(alias, str):\n serialization_alias = alias\n if validation_alias in (_Unset, None):\n validation_alias = alias\n kwargs.update(\n {\n \"annotation\": annotation,\n \"alias_priority\": alias_priority,\n \"validation_alias\": validation_alias,\n \"serialization_alias\": serialization_alias,\n \"strict\": strict,\n \"json_schema_extra\": current_json_schema_extra,\n }\n )\n kwargs[\"pattern\"] = pattern or regex\n\n use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}\n\n super().__init__(**use_kwargs) # ty: ignore[invalid-argument-type]\n\n def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({self.default})\"", "source_type": "code", "path": "fastapi/params.py", "symbol": "Body", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L469-L578", "start_line": 469, "end_line": 578} {"id": "fastapi/params.py::Form::L581", "text": "# File: fastapi/params.py | Symbol: Form\nclass Form(Body): # type: ignore[misc]\n def __init__(\n self,\n default: Any = Undefined,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n media_type: str = \"application/x-www-form-urlencoded\",\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n super().__init__(\n default=default,\n default_factory=default_factory,\n annotation=annotation,\n media_type=media_type,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n deprecated=deprecated,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/params.py", "symbol": "Form", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L581-L660", "start_line": 581, "end_line": 660} {"id": "fastapi/params.py::File::L663", "text": "# File: fastapi/params.py | Symbol: File\nclass File(Form): # type: ignore[misc]\n def __init__(\n self,\n default: Any = Undefined,\n *,\n default_factory: Callable[[], Any] | None = _Unset,\n annotation: Any | None = None,\n media_type: str = \"multipart/form-data\",\n alias: str | None = None,\n alias_priority: int | None = _Unset,\n validation_alias: str | AliasPath | AliasChoices | None = None,\n serialization_alias: str | None = None,\n title: str | None = None,\n description: str | None = None,\n gt: float | None = None,\n ge: float | None = None,\n lt: float | None = None,\n le: float | None = None,\n min_length: int | None = None,\n max_length: int | None = None,\n pattern: str | None = None,\n regex: Annotated[\n str | None,\n deprecated(\n \"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead.\"\n ),\n ] = None,\n discriminator: str | None = None,\n strict: bool | None = _Unset,\n multiple_of: float | None = _Unset,\n allow_inf_nan: bool | None = _Unset,\n max_digits: int | None = _Unset,\n decimal_places: int | None = _Unset,\n examples: list[Any] | None = None,\n example: Annotated[\n Any | None,\n deprecated(\n \"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, \"\n \"although still supported. Use examples instead.\"\n ),\n ] = _Unset,\n openapi_examples: dict[str, Example] | None = None,\n deprecated: deprecated | str | bool | None = None,\n include_in_schema: bool = True,\n json_schema_extra: dict[str, Any] | None = None,\n **extra: Any,\n ):\n super().__init__(\n default=default,\n default_factory=default_factory,\n annotation=annotation,\n media_type=media_type,\n alias=alias,\n alias_priority=alias_priority,\n validation_alias=validation_alias,\n serialization_alias=serialization_alias,\n title=title,\n description=description,\n gt=gt,\n ge=ge,\n lt=lt,\n le=le,\n min_length=min_length,\n max_length=max_length,\n pattern=pattern,\n regex=regex,\n discriminator=discriminator,\n strict=strict,\n multiple_of=multiple_of,\n allow_inf_nan=allow_inf_nan,\n max_digits=max_digits,\n decimal_places=decimal_places,\n deprecated=deprecated,\n example=example,\n examples=examples,\n openapi_examples=openapi_examples,\n include_in_schema=include_in_schema,\n json_schema_extra=json_schema_extra,\n **extra,\n )", "source_type": "code", "path": "fastapi/params.py", "symbol": "File", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L663-L742", "start_line": 663, "end_line": 742} {"id": "fastapi/params.py::Depends::L745", "text": "# File: fastapi/params.py | Symbol: Depends\n@dataclass(frozen=True)\nclass Depends:\n dependency: Callable[..., Any] | None = None\n use_cache: bool = True\n scope: Literal[\"function\", \"request\"] | None = None", "source_type": "code", "path": "fastapi/params.py", "symbol": "Depends", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L745-L749", "start_line": 745, "end_line": 749} {"id": "fastapi/params.py::Security::L752", "text": "# File: fastapi/params.py | Symbol: Security\n@dataclass(frozen=True)\nclass Security(Depends):\n scopes: Sequence[str] | None = None", "source_type": "code", "path": "fastapi/params.py", "symbol": "Security", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L752-L754", "start_line": 752, "end_line": 754} {"id": "fastapi/params.py::", "text": "# File: fastapi/params.py | Symbol: \nimport warnings\nfrom collections.abc import Callable, Sequence\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom typing import Annotated, Any, Literal\nfrom fastapi.exceptions import FastAPIDeprecationWarning\nfrom fastapi.openapi.models import Example\nfrom pydantic import AliasChoices, AliasPath\nfrom pydantic.fields import FieldInfo\nfrom typing_extensions import deprecated\nfrom ._compat import (\n Undefined,\n)\nfrom .datastructures import _Unset", "source_type": "code", "path": "fastapi/params.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/params.py#L1-L16", "start_line": 1, "end_line": 16} {"id": "fastapi/requests.py::", "text": "# File: fastapi/requests.py | Symbol: \nfrom starlette.requests import HTTPConnection as HTTPConnection # noqa: F401\nfrom starlette.requests import Request as Request # noqa: F401", "source_type": "code", "path": "fastapi/requests.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/requests.py#L1-L2", "start_line": 1, "end_line": 2} {"id": "fastapi/responses.py::_UjsonModule::L16", "text": "# File: fastapi/responses.py | Symbol: _UjsonModule\nclass _UjsonModule(Protocol):\n def dumps(self, __obj: Any, *, ensure_ascii: bool = ...) -> str: ...", "source_type": "code", "path": "fastapi/responses.py", "symbol": "_UjsonModule", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/responses.py#L16-L17", "start_line": 16, "end_line": 17} {"id": "fastapi/responses.py::_OrjsonModule::L20", "text": "# File: fastapi/responses.py | Symbol: _OrjsonModule\nclass _OrjsonModule(Protocol):\n OPT_NON_STR_KEYS: int\n OPT_SERIALIZE_NUMPY: int\n\n def dumps(self, __obj: Any, *, option: int = ...) -> bytes: ...", "source_type": "code", "path": "fastapi/responses.py", "symbol": "_OrjsonModule", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/responses.py#L20-L24", "start_line": 20, "end_line": 24} {"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} {"id": "fastapi/security/api_key.py::APIKeyHeader::L147", "text": "# File: fastapi/security/api_key.py | Symbol: APIKeyHeader\nclass APIKeyHeader(APIKeyBase):\n \"\"\"\n API key authentication using a header.\n\n This defines the name of the header that should be provided in the request with\n the API key and integrates that into the OpenAPI documentation. It extracts\n the key value sent in the header automatically and provides it as the dependency\n result. But it doesn't define how to send that 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 APIKeyHeader\n\n app = FastAPI()\n\n header_scheme = APIKeyHeader(name=\"x-key\")\n\n\n @app.get(\"/items/\")\n async def read_items(key: str = Depends(header_scheme)):\n return {\"key\": key}\n ```\n \"\"\"\n\n def __init__(\n self,\n *,\n name: Annotated[str, Doc(\"Header name.\")],\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 header is not provided, `APIKeyHeader` will\n automatically cancel the request and send the client an error.\n\n If `auto_error` is set to `False`, when the header is not available,\n instead of erroring out, the dependency result will be `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 header or\n in an HTTP Bearer token).\n \"\"\"\n ),\n ] = True,\n ):\n super().__init__(\n location=APIKeyIn.header,\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.headers.get(self.model.name)\n return self.check_api_key(api_key)", "source_type": "code", "path": "fastapi/security/api_key.py", "symbol": "APIKeyHeader", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/api_key.py#L147-L232", "start_line": 147, "end_line": 232} {"id": "fastapi/security/api_key.py::APIKeyCookie::L235", "text": "# File: fastapi/security/api_key.py | Symbol: APIKeyCookie\nclass APIKeyCookie(APIKeyBase):\n \"\"\"\n API key authentication using a cookie.\n\n This defines the name of the cookie that should be provided in the request with\n the API key and integrates that into the OpenAPI documentation. It extracts\n the key value sent in the cookie automatically and provides it as the dependency\n result. But it doesn't define how to set that cookie.\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 APIKeyCookie\n\n app = FastAPI()\n\n cookie_scheme = APIKeyCookie(name=\"session\")\n\n\n @app.get(\"/items/\")\n async def read_items(session: str = Depends(cookie_scheme)):\n return {\"session\": session}\n ```\n \"\"\"\n\n def __init__(\n self,\n *,\n name: Annotated[str, Doc(\"Cookie name.\")],\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 cookie is not provided, `APIKeyCookie` will\n automatically cancel the request and send the client an error.\n\n If `auto_error` is set to `False`, when the cookie is not available,\n instead of erroring out, the dependency result will be `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 cookie or\n in an HTTP Bearer token).\n \"\"\"\n ),\n ] = True,\n ):\n super().__init__(\n location=APIKeyIn.cookie,\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.cookies.get(self.model.name)\n return self.check_api_key(api_key)", "source_type": "code", "path": "fastapi/security/api_key.py", "symbol": "APIKeyCookie", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/api_key.py#L235-L320", "start_line": 235, "end_line": 320} {"id": "fastapi/security/api_key.py::", "text": "# File: fastapi/security/api_key.py | Symbol: \nfrom typing import Annotated\nfrom annotated_doc import Doc\nfrom fastapi.openapi.models import APIKey, APIKeyIn\nfrom fastapi.security.base import SecurityBase\nfrom starlette.exceptions import HTTPException\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_401_UNAUTHORIZED", "source_type": "code", "path": "fastapi/security/api_key.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/api_key.py#L1-L8", "start_line": 1, "end_line": 8} {"id": "fastapi/security/base.py::SecurityBase::L4", "text": "# File: fastapi/security/base.py | Symbol: SecurityBase\nclass SecurityBase:\n model: SecurityBaseModel\n scheme_name: str", "source_type": "code", "path": "fastapi/security/base.py", "symbol": "SecurityBase", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/base.py#L4-L6", "start_line": 4, "end_line": 6} {"id": "fastapi/security/base.py::", "text": "# File: fastapi/security/base.py | Symbol: \nfrom fastapi.openapi.models import SecurityBase as SecurityBaseModel", "source_type": "code", "path": "fastapi/security/base.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/base.py#L1-L1", "start_line": 1, "end_line": 1} {"id": "fastapi/security/http.py::HTTPBasicCredentials::L16", "text": "# File: fastapi/security/http.py | Symbol: HTTPBasicCredentials\nclass HTTPBasicCredentials(BaseModel):\n \"\"\"\n The HTTP Basic credentials given as the result of using `HTTPBasic` in a\n dependency.\n\n Read more about it in the\n [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/).\n \"\"\"\n\n username: Annotated[str, Doc(\"The HTTP Basic username.\")]\n password: Annotated[str, Doc(\"The HTTP Basic password.\")]", "source_type": "code", "path": "fastapi/security/http.py", "symbol": "HTTPBasicCredentials", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/http.py#L16-L26", "start_line": 16, "end_line": 26} {"id": "fastapi/security/http.py::HTTPAuthorizationCredentials::L29", "text": "# File: fastapi/security/http.py | Symbol: HTTPAuthorizationCredentials\nclass HTTPAuthorizationCredentials(BaseModel):\n \"\"\"\n The HTTP authorization credentials in the result of using `HTTPBearer` or\n `HTTPDigest` in a dependency.\n\n The HTTP authorization header value is split by the first space.\n\n The first part is the `scheme`, the second part is the `credentials`.\n\n For example, in an HTTP Bearer token scheme, the client will send a header\n like:\n\n ```\n Authorization: Bearer deadbeef12346\n ```\n\n In this case:\n\n * `scheme` will have the value `\"Bearer\"`\n * `credentials` will have the value `\"deadbeef12346\"`\n \"\"\"\n\n scheme: Annotated[\n str,\n Doc(\n \"\"\"\n The HTTP authorization scheme extracted from the header value.\n \"\"\"\n ),\n ]\n credentials: Annotated[\n str,\n Doc(\n \"\"\"\n The HTTP authorization credentials extracted from the header value.\n \"\"\"\n ),\n ]", "source_type": "code", "path": "fastapi/security/http.py", "symbol": "HTTPAuthorizationCredentials", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/http.py#L29-L66", "start_line": 29, "end_line": 66} {"id": "fastapi/security/http.py::HTTPBase::L69", "text": "# File: fastapi/security/http.py | Symbol: HTTPBase\nclass HTTPBase(SecurityBase):\n model: HTTPBaseModel\n\n def __init__(\n self,\n *,\n scheme: str,\n scheme_name: str | None = None,\n description: str | None = None,\n auto_error: bool = True,\n ):\n self.model = HTTPBaseModel(scheme=scheme, description=description)\n self.scheme_name = scheme_name or self.__class__.__name__\n self.auto_error = auto_error\n\n def make_authenticate_headers(self) -> dict[str, str]:\n return {\"WWW-Authenticate\": f\"{self.model.scheme.title()}\"}\n\n def make_not_authenticated_error(self) -> HTTPException:\n return HTTPException(\n status_code=HTTP_401_UNAUTHORIZED,\n detail=\"Not authenticated\",\n headers=self.make_authenticate_headers(),\n )\n\n async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None:\n authorization = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)", "source_type": "code", "path": "fastapi/security/http.py", "symbol": "HTTPBase", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/http.py#L69-L102", "start_line": 69, "end_line": 102} {"id": "fastapi/security/http.py::HTTPBasic::L105", "text": "# File: fastapi/security/http.py | Symbol: HTTPBasic\nclass HTTPBasic(HTTPBase):\n \"\"\"\n HTTP Basic authentication.\n\n Ref: https://datatracker.ietf.org/doc/html/rfc7617\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 an `HTTPBasicCredentials` object containing the\n `username` and the `password`.\n\n Read more about it in the\n [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/).\n\n ## Example\n\n ```python\n from typing import Annotated\n\n from fastapi import Depends, FastAPI\n from fastapi.security import HTTPBasic, HTTPBasicCredentials\n\n app = FastAPI()\n\n security = HTTPBasic()\n\n\n @app.get(\"/users/me\")\n def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):\n return {\"username\": credentials.username, \"password\": credentials.password}\n ```\n \"\"\"\n\n def __init__(\n self,\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 realm: Annotated[\n str | None,\n Doc(\n \"\"\"\n HTTP Basic authentication realm.\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 HTTP Basic authentication is not provided (a\n header), `HTTPBasic` will automatically cancel the request and send the\n client an error.\n\n If `auto_error` is set to `False`, when the HTTP Basic authentication\n is not available, instead of erroring out, the dependency result will\n be `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 HTTP Basic\n authentication or in an HTTP Bearer token).\n \"\"\"\n ),\n ] = True,\n ):\n self.model = HTTPBaseModel(scheme=\"basic\", description=description)\n self.scheme_name = scheme_name or self.__class__.__name__\n self.realm = realm\n self.auto_error = auto_error\n\n def make_authenticate_headers(self) -> dict[str, str]:\n if self.realm:\n return {\"WWW-Authenticate\": f'Basic realm=\"{self.realm}\"'}\n return {\"WWW-Authenticate\": \"Basic\"}\n\n async def __call__( # type: ignore\n self, request: Request\n ) -> HTTPBasicCredentials | None:\n authorization = request.headers.get(\"Authorization\")\n scheme, param = get_authorization_scheme_param(authorization)\n if not authorization or scheme.lower() != \"basic\":\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n try:\n data = b64decode(param).decode(\"ascii\")\n except (ValueError, UnicodeDecodeError, binascii.Error) as e:\n raise self.make_not_authenticated_error() from e\n username, separator, password = data.partition(\":\")\n if not separator:\n raise self.make_not_authenticated_error()\n return HTTPBasicCredentials(username=username, password=password)", "source_type": "code", "path": "fastapi/security/http.py", "symbol": "HTTPBasic", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/http.py#L105-L219", "start_line": 105, "end_line": 219} {"id": "fastapi/security/http.py::HTTPBearer::L222", "text": "# File: fastapi/security/http.py | Symbol: HTTPBearer\nclass HTTPBearer(HTTPBase):\n \"\"\"\n HTTP Bearer token authentication.\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 an `HTTPAuthorizationCredentials` object containing\n the `scheme` and the `credentials`.\n\n ## Example\n\n ```python\n from typing import Annotated\n\n from fastapi import Depends, FastAPI\n from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer\n\n app = FastAPI()\n\n security = HTTPBearer()\n\n\n @app.get(\"/users/me\")\n def read_current_user(\n credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]\n ):\n return {\"scheme\": credentials.scheme, \"credentials\": credentials.credentials}\n ```\n \"\"\"\n\n def __init__(\n self,\n *,\n bearerFormat: Annotated[str | None, Doc(\"Bearer token format.\")] = None,\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 HTTP Bearer token is not provided (in an\n `Authorization` header), `HTTPBearer` will automatically cancel the\n request and send the client an error.\n\n If `auto_error` is set to `False`, when the HTTP Bearer token\n is not available, instead of erroring out, the dependency result will\n be `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 an HTTP\n Bearer token or in a cookie).\n \"\"\"\n ),\n ] = True,\n ):\n self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)\n self.scheme_name = scheme_name or self.__class__.__name__\n self.auto_error = auto_error\n\n async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None:\n authorization = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n if scheme.lower() != \"bearer\":\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)", "source_type": "code", "path": "fastapi/security/http.py", "symbol": "HTTPBearer", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/http.py#L222-L316", "start_line": 222, "end_line": 316} {"id": "fastapi/security/http.py::HTTPDigest::L319", "text": "# File: fastapi/security/http.py | Symbol: HTTPDigest\nclass HTTPDigest(HTTPBase):\n \"\"\"\n HTTP Digest authentication.\n\n **Warning**: this is only a stub to connect the components with OpenAPI in FastAPI,\n but it doesn't implement the full Digest scheme, you would need to subclass it\n and implement it in your code.\n\n Ref: https://datatracker.ietf.org/doc/html/rfc7616\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 an `HTTPAuthorizationCredentials` object containing\n the `scheme` and the `credentials`.\n\n ## Example\n\n ```python\n from typing import Annotated\n\n from fastapi import Depends, FastAPI\n from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest\n\n app = FastAPI()\n\n security = HTTPDigest()\n\n\n @app.get(\"/users/me\")\n def read_current_user(\n credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]\n ):\n return {\"scheme\": credentials.scheme, \"credentials\": credentials.credentials}\n ```\n \"\"\"\n\n def __init__(\n self,\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 HTTP Digest is not provided, `HTTPDigest` will\n automatically cancel the request and send the client an error.\n\n If `auto_error` is set to `False`, when the HTTP Digest is not\n available, instead of erroring out, the dependency result will\n be `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 HTTP\n Digest or in a cookie).\n \"\"\"\n ),\n ] = True,\n ):\n self.model = HTTPBaseModel(scheme=\"digest\", description=description)\n self.scheme_name = scheme_name or self.__class__.__name__\n self.auto_error = auto_error\n\n async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None:\n authorization = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n if scheme.lower() != \"digest\":\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)", "source_type": "code", "path": "fastapi/security/http.py", "symbol": "HTTPDigest", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/http.py#L319-L417", "start_line": 319, "end_line": 417} {"id": "fastapi/security/http.py::", "text": "# File: fastapi/security/http.py | Symbol: \nimport binascii\nfrom base64 import b64decode\nfrom typing import Annotated\nfrom annotated_doc import Doc\nfrom fastapi.exceptions import HTTPException\nfrom fastapi.openapi.models import HTTPBase as HTTPBaseModel\nfrom fastapi.openapi.models import HTTPBearer as HTTPBearerModel\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.utils import get_authorization_scheme_param\nfrom pydantic import BaseModel\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_401_UNAUTHORIZED", "source_type": "code", "path": "fastapi/security/http.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/http.py#L1-L13", "start_line": 1, "end_line": 13} {"id": "fastapi/security/oauth2.py::OAuth2PasswordRequestForm::L14", "text": "# File: fastapi/security/oauth2.py | Symbol: OAuth2PasswordRequestForm\nclass OAuth2PasswordRequestForm:\n \"\"\"\n This is a dependency class to collect the `username` and `password` as form data\n for an OAuth2 password flow.\n\n The OAuth2 specification dictates that for a password flow the data should be\n collected using form data (instead of JSON) and that it should have the specific\n fields `username` and `password`.\n\n All the initialization parameters are extracted from the request.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n\n ## Example\n\n ```python\n from typing import Annotated\n\n from fastapi import Depends, FastAPI\n from fastapi.security import OAuth2PasswordRequestForm\n\n app = FastAPI()\n\n\n @app.post(\"/login\")\n def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):\n data = {}\n data[\"scopes\"] = []\n for scope in form_data.scopes:\n data[\"scopes\"].append(scope)\n if form_data.client_id:\n data[\"client_id\"] = form_data.client_id\n if form_data.client_secret:\n data[\"client_secret\"] = form_data.client_secret\n return data\n ```\n\n Note that for OAuth2 the scope `items:read` is a single scope in an opaque string.\n You could have custom internal logic to separate it by colon characters (`:`) or\n similar, and get the two parts `items` and `read`. Many applications do that to\n group and organize permissions, you could do it as well in your application, just\n know that it is application specific, it's not part of the specification.\n \"\"\"\n\n def __init__(\n self,\n *,\n grant_type: Annotated[\n str | None,\n Form(pattern=\"^password$\"),\n Doc(\n \"\"\"\n The OAuth2 spec says it is required and MUST be the fixed string\n \"password\". Nevertheless, this dependency class is permissive and\n allows not passing it. If you want to enforce it, use instead the\n `OAuth2PasswordRequestFormStrict` dependency.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ] = None,\n username: Annotated[\n str,\n Form(),\n Doc(\n \"\"\"\n `username` string. The OAuth2 spec requires the exact field name\n `username`.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ],\n password: Annotated[\n str,\n Form(json_schema_extra={\"format\": \"password\"}),\n Doc(\n \"\"\"\n `password` string. The OAuth2 spec requires the exact field name\n `password`.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ],\n scope: Annotated[\n str,\n Form(),\n Doc(\n \"\"\"\n A single string with actually several scopes separated by spaces. Each\n scope is also a string.\n\n For example, a single string with:\n\n ```python\n \"items:read items:write users:read profile openid\"\n ````\n\n would represent the scopes:\n\n * `items:read`\n * `items:write`\n * `users:read`\n * `profile`\n * `openid`\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ] = \"\",\n client_id: Annotated[\n str | None,\n Form(),\n Doc(\n \"\"\"\n If there's a `client_id`, it can be sent as part of the form fields.\n But the OAuth2 specification recommends sending the `client_id` and\n `client_secret` (if any) using HTTP Basic auth.\n \"\"\"\n ),\n ] = None,\n client_secret: Annotated[\n str | None,\n Form(json_schema_extra={\"format\": \"password\"}),\n Doc(\n \"\"\"\n If there's a `client_secret` (and a `client_id`), they can be sent\n as part of the form fields. But the OAuth2 specification recommends\n sending the `client_id` and `client_secret` (if any) using HTTP Basic\n auth.\n \"\"\"\n ),\n ] = None,\n ):\n self.grant_type = grant_type\n self.username = username\n self.password = password\n self.scopes = scope.split()\n self.client_id = client_id\n self.client_secret = client_secret", "source_type": "code", "path": "fastapi/security/oauth2.py", "symbol": "OAuth2PasswordRequestForm", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L14-L159", "start_line": 14, "end_line": 159} {"id": "fastapi/security/oauth2.py::OAuth2PasswordRequestFormStrict.__init__::L226", "text": "# File: fastapi/security/oauth2.py | Class: OAuth2PasswordRequestFormStrict | Symbol: OAuth2PasswordRequestFormStrict.__init__\ndef __init__(\n self,\n grant_type: Annotated[\n str,\n Form(pattern=\"^password$\"),\n Doc(\n \"\"\"\n The OAuth2 spec says it is required and MUST be the fixed string\n \"password\". This dependency is strict about it. If you want to be\n permissive, use instead the `OAuth2PasswordRequestForm` dependency\n class.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ],\n username: Annotated[\n str,\n Form(),\n Doc(\n \"\"\"\n `username` string. The OAuth2 spec requires the exact field name\n `username`.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ],\n password: Annotated[\n str,\n Form(),\n Doc(\n \"\"\"\n `password` string. The OAuth2 spec requires the exact field name\n `password`.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ],\n scope: Annotated[\n str,\n Form(),\n Doc(\n \"\"\"\n A single string with actually several scopes separated by spaces. Each\n scope is also a string.\n\n For example, a single string with:\n\n ```python\n \"items:read items:write users:read profile openid\"\n ````\n\n would represent the scopes:\n\n * `items:read`\n * `items:write`\n * `users:read`\n * `profile`\n * `openid`\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\n ] = \"\",\n client_id: Annotated[\n str | None,\n Form(),\n Doc(\n \"\"\"\n If there's a `client_id`, it can be sent as part of the form fields.\n But the OAuth2 specification recommends sending the `client_id` and\n `client_secret` (if any) using HTTP Basic auth.\n \"\"\"\n ),\n ] = None,\n client_secret: Annotated[\n str | None,\n Form(),\n Doc(\n \"\"\"\n If there's a `client_secret` (and a `client_id`), they can be sent\n as part of the form fields. But the OAuth2 specification recommends\n sending the `client_id` and `client_secret` (if any) using HTTP Basic\n auth.\n \"\"\"\n ),\n ] = None,\n ):\n super().__init__(\n grant_type=grant_type,\n username=username,\n password=password,\n scope=scope,\n client_id=client_id,\n client_secret=client_secret,\n )", "source_type": "code", "path": "fastapi/security/oauth2.py", "symbol": "OAuth2PasswordRequestFormStrict.__init__", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L226-L327", "start_line": 226, "end_line": 327} {"id": "fastapi/security/oauth2.py::OAuth2::L330", "text": "# File: fastapi/security/oauth2.py | Symbol: OAuth2\nclass OAuth2(SecurityBase):\n \"\"\"\n This is the base class for OAuth2 authentication, an instance of it would be used\n as a dependency. All other OAuth2 classes inherit from it and customize it for\n each OAuth2 flow.\n\n You normally would not create a new class inheriting from it but use one of the\n existing subclasses, and maybe compose them if you want to support multiple flows.\n\n Read more about it in the\n [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/).\n \"\"\"\n\n def __init__(\n self,\n *,\n flows: Annotated[\n OAuthFlowsModel | dict[str, dict[str, Any]],\n Doc(\n \"\"\"\n The dictionary of OAuth2 flows.\n \"\"\"\n ),\n ] = OAuthFlowsModel(),\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 no HTTP Authorization header is provided, required for\n OAuth2 authentication, it will automatically cancel the request and\n send the client an error.\n\n If `auto_error` is set to `False`, when the HTTP Authorization header\n is not available, instead of erroring out, the dependency result will\n be `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, with OAuth2\n or in a cookie).\n \"\"\"\n ),\n ] = True,\n ):\n self.model = OAuth2Model(\n flows=cast(OAuthFlowsModel, flows), description=description\n )\n self.scheme_name = scheme_name or self.__class__.__name__\n self.auto_error = auto_error\n\n def make_not_authenticated_error(self) -> HTTPException:\n \"\"\"\n The OAuth 2 specification doesn't define the challenge that should be used,\n because a `Bearer` token is not really the only option to authenticate.\n\n But declaring any other authentication challenge would be application-specific\n as it's not defined in the specification.\n\n For practical reasons, this method uses the `Bearer` challenge by default, as\n it's probably the most common one.\n\n If you are implementing an OAuth2 authentication scheme other than the provided\n ones in FastAPI (based on bearer tokens), you might want to override this.\n\n Ref: https://datatracker.ietf.org/doc/html/rfc6749\n \"\"\"\n return HTTPException(\n status_code=HTTP_401_UNAUTHORIZED,\n detail=\"Not authenticated\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n\n async def __call__(self, request: Request) -> str | None:\n authorization = request.headers.get(\"Authorization\")\n if not authorization:\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n return authorization", "source_type": "code", "path": "fastapi/security/oauth2.py", "symbol": "OAuth2", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L330-L430", "start_line": 330, "end_line": 430} {"id": "fastapi/security/oauth2.py::OAuth2PasswordBearer::L433", "text": "# File: fastapi/security/oauth2.py | Symbol: OAuth2PasswordBearer\nclass OAuth2PasswordBearer(OAuth2):\n \"\"\"\n OAuth2 flow for authentication using a bearer token obtained with a password.\n An instance of it would be used as a dependency.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n\n def __init__(\n self,\n tokenUrl: Annotated[\n str,\n Doc(\n \"\"\"\n The URL to obtain the OAuth2 token. This would be the *path operation*\n that has `OAuth2PasswordRequestForm` as a dependency.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n \"\"\"\n ),\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 scopes: Annotated[\n dict[str, str] | None,\n Doc(\n \"\"\"\n The OAuth2 scopes that would be required by the *path operations* that\n use this dependency.\n\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\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 no HTTP Authorization header is provided, required for\n OAuth2 authentication, it will automatically cancel the request and\n send the client an error.\n\n If `auto_error` is set to `False`, when the HTTP Authorization header\n is not available, instead of erroring out, the dependency result will\n be `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, with OAuth2\n or in a cookie).\n \"\"\"\n ),\n ] = True,\n refreshUrl: Annotated[\n str | None,\n Doc(\n \"\"\"\n The URL to refresh the token and obtain a new one.\n \"\"\"\n ),\n ] = None,\n ):\n if not scopes:\n scopes = {}\n flows = OAuthFlowsModel(\n password=cast(\n Any,\n {\n \"tokenUrl\": tokenUrl,\n \"refreshUrl\": refreshUrl,\n \"scopes\": scopes,\n },\n )\n )\n super().__init__(\n flows=flows,\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 authorization = request.headers.get(\"Authorization\")\n scheme, param = get_authorization_scheme_param(authorization)\n if not authorization or scheme.lower() != \"bearer\":\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n return param", "source_type": "code", "path": "fastapi/security/oauth2.py", "symbol": "OAuth2PasswordBearer", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L433-L544", "start_line": 433, "end_line": 544} {"id": "fastapi/security/oauth2.py::OAuth2AuthorizationCodeBearer::L547", "text": "# File: fastapi/security/oauth2.py | Symbol: OAuth2AuthorizationCodeBearer\nclass OAuth2AuthorizationCodeBearer(OAuth2):\n \"\"\"\n OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code\n flow. An instance of it would be used as a dependency.\n \"\"\"\n\n def __init__(\n self,\n authorizationUrl: str,\n tokenUrl: Annotated[\n str,\n Doc(\n \"\"\"\n The URL to obtain the OAuth2 token.\n \"\"\"\n ),\n ],\n refreshUrl: Annotated[\n str | None,\n Doc(\n \"\"\"\n The URL to refresh the token and obtain a new one.\n \"\"\"\n ),\n ] = None,\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 scopes: Annotated[\n dict[str, str] | None,\n Doc(\n \"\"\"\n The OAuth2 scopes that would be required by the *path operations* that\n use this dependency.\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 no HTTP Authorization header is provided, required for\n OAuth2 authentication, it will automatically cancel the request and\n send the client an error.\n\n If `auto_error` is set to `False`, when the HTTP Authorization header\n is not available, instead of erroring out, the dependency result will\n be `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, with OAuth2\n or in a cookie).\n \"\"\"\n ),\n ] = True,\n ):\n if not scopes:\n scopes = {}\n flows = OAuthFlowsModel(\n authorizationCode=cast(\n Any,\n {\n \"authorizationUrl\": authorizationUrl,\n \"tokenUrl\": tokenUrl,\n \"refreshUrl\": refreshUrl,\n \"scopes\": scopes,\n },\n )\n )\n super().__init__(\n flows=flows,\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 authorization = request.headers.get(\"Authorization\")\n scheme, param = get_authorization_scheme_param(authorization)\n if not authorization or scheme.lower() != \"bearer\":\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None # pragma: nocover\n return param", "source_type": "code", "path": "fastapi/security/oauth2.py", "symbol": "OAuth2AuthorizationCodeBearer", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L547-L650", "start_line": 547, "end_line": 650} {"id": "fastapi/security/oauth2.py::SecurityScopes::L653", "text": "# File: fastapi/security/oauth2.py | Symbol: SecurityScopes\nclass SecurityScopes:\n \"\"\"\n This is a special class that you can define in a parameter in a dependency to\n obtain the OAuth2 scopes required by all the dependencies in the same chain.\n\n This way, multiple dependencies can have different scopes, even when used in the\n same *path operation*. And with this, you can access all the scopes required in\n all those dependencies in a single place.\n\n Read more about it in the\n [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).\n \"\"\"\n\n def __init__(\n self,\n scopes: Annotated[\n list[str] | None,\n Doc(\n \"\"\"\n This will be filled by FastAPI.\n \"\"\"\n ),\n ] = None,\n ):\n self.scopes: Annotated[\n list[str],\n Doc(\n \"\"\"\n The list of all the scopes required by dependencies.\n \"\"\"\n ),\n ] = scopes or []\n self.scope_str: Annotated[\n str,\n Doc(\n \"\"\"\n All the scopes required by all the dependencies in a single string\n separated by spaces, as defined in the OAuth2 specification.\n \"\"\"\n ),\n ] = \" \".join(self.scopes)", "source_type": "code", "path": "fastapi/security/oauth2.py", "symbol": "SecurityScopes", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L653-L693", "start_line": 653, "end_line": 693} {"id": "fastapi/security/oauth2.py::", "text": "# File: fastapi/security/oauth2.py | Symbol: \nfrom typing import Annotated, Any, cast\nfrom annotated_doc import Doc\nfrom fastapi.exceptions import HTTPException\nfrom fastapi.openapi.models import OAuth2 as OAuth2Model\nfrom fastapi.openapi.models import OAuthFlows as OAuthFlowsModel\nfrom fastapi.param_functions import Form\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.utils import get_authorization_scheme_param\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_401_UNAUTHORIZED\nclass OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm):\n \"\"\"\n This is a dependency class to collect the `username` and `password` as form data\n for an OAuth2 password flow.\n The OAuth2 specification dictates that for a password flow the data should be\n collected using form data (instead of JSON) and that it should have the specific\n fields `username` and `password`.\n All the initialization parameters are extracted from the request.\n The only difference between `OAuth2PasswordRequestFormStrict` and\n `OAuth2PasswordRequestForm` is that `OAuth2PasswordRequestFormStrict` requires the\n client to send the form field `grant_type` with the value `\"password\"`, which\n is required in the OAuth2 specification (it seems that for no particular reason),\n while for `OAuth2PasswordRequestForm` `grant_type` is optional.\n Read more about it in the\n [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n ## Example\n ```python\n from typing import Annotated\n from fastapi import Depends, FastAPI\n from fastapi.security import OAuth2PasswordRequestForm\n app = FastAPI()\n @app.post(\"/login\")\n def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]):\n data = {}\n data[\"scopes\"] = []\n for scope in form_data.scopes:\n data[\"scopes\"].append(scope)\n if form_data.client_id:\n data[\"client_id\"] = form_data.client_id\n if form_data.client_secret:\n data[\"client_secret\"] = form_data.client_secret\n return data\n ```\n Note that for OAuth2 the scope `items:read` is a single scope in an opaque string.\n You could have custom internal logic to separate it by colon characters (`:`) or\n similar, and get the two parts `items` and `read`. Many applications do that to\n group and organize permissions, you could do it as well in your application, just\n know that it is application specific, it's not part of the specification.\n grant_type: the OAuth2 spec says it is required and MUST be the fixed string \"password\".\n This dependency is strict about it. If you want to be permissive, use instead the\n OAuth2PasswordRequestForm dependency class.\n username: username string. The OAuth2 spec requires the exact field name \"username\".\n password: password string. The OAuth2 spec requires the exact field name \"password\".\n scope: Optional string. Several scopes (each one a string) separated by spaces. E.g.\n \"items:read items:write users:read profile openid\"\n client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any)\n using HTTP Basic auth, as: client_id:client_secret\n client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any)\n using HTTP Basic auth, as: client_id:client_secret\n \"\"\"", "source_type": "code", "path": "fastapi/security/oauth2.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L1-L224", "start_line": 1, "end_line": 224} {"id": "fastapi/security/open_id_connect_url.py::OpenIdConnect::L11", "text": "# File: fastapi/security/open_id_connect_url.py | Symbol: OpenIdConnect\nclass OpenIdConnect(SecurityBase):\n \"\"\"\n OpenID Connect authentication class. An instance of it would be used as a\n dependency.\n\n **Warning**: this is only a stub to connect the components with OpenAPI in FastAPI,\n but it doesn't implement the full OpenIdConnect scheme, for example, it doesn't use\n the OpenIDConnect URL. You would need to subclass it and implement it in your\n code.\n \"\"\"\n\n def __init__(\n self,\n *,\n openIdConnectUrl: Annotated[\n str,\n Doc(\n \"\"\"\n The OpenID Connect URL.\n \"\"\"\n ),\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 no HTTP Authorization header is provided, required for\n OpenID Connect authentication, it will automatically cancel the request\n and send the client an error.\n\n If `auto_error` is set to `False`, when the HTTP Authorization header\n is not available, instead of erroring out, the dependency result will\n be `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, with OpenID\n Connect or in a cookie).\n \"\"\"\n ),\n ] = True,\n ):\n self.model = OpenIdConnectModel(\n openIdConnectUrl=openIdConnectUrl, description=description\n )\n self.scheme_name = scheme_name or self.__class__.__name__\n self.auto_error = auto_error\n\n def make_not_authenticated_error(self) -> HTTPException:\n return HTTPException(\n status_code=HTTP_401_UNAUTHORIZED,\n detail=\"Not authenticated\",\n headers={\"WWW-Authenticate\": \"Bearer\"},\n )\n\n async def __call__(self, request: Request) -> str | None:\n authorization = request.headers.get(\"Authorization\")\n if not authorization:\n if self.auto_error:\n raise self.make_not_authenticated_error()\n else:\n return None\n return authorization", "source_type": "code", "path": "fastapi/security/open_id_connect_url.py", "symbol": "OpenIdConnect", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/open_id_connect_url.py#L11-L94", "start_line": 11, "end_line": 94} {"id": "fastapi/security/open_id_connect_url.py::", "text": "# File: fastapi/security/open_id_connect_url.py | Symbol: \nfrom typing import Annotated\nfrom annotated_doc import Doc\nfrom fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel\nfrom fastapi.security.base import SecurityBase\nfrom starlette.exceptions import HTTPException\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_401_UNAUTHORIZED", "source_type": "code", "path": "fastapi/security/open_id_connect_url.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/open_id_connect_url.py#L1-L8", "start_line": 1, "end_line": 8} {"id": "fastapi/security/utils.py::get_authorization_scheme_param::L1", "text": "# File: fastapi/security/utils.py | Symbol: get_authorization_scheme_param\ndef get_authorization_scheme_param(\n authorization_header_value: str | None,\n) -> tuple[str, str]:\n if not authorization_header_value:\n return \"\", \"\"\n scheme, _, param = authorization_header_value.partition(\" \")\n return scheme, param.strip()", "source_type": "code", "path": "fastapi/security/utils.py", "symbol": "get_authorization_scheme_param", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/security/utils.py#L1-L7", "start_line": 1, "end_line": 7} {"id": "fastapi/sse.py::EventSourceResponse::L20", "text": "# File: fastapi/sse.py | Symbol: EventSourceResponse\nclass EventSourceResponse(StreamingResponse):\n \"\"\"Streaming response with `text/event-stream` media type.\n\n Use as `response_class=EventSourceResponse` on a *path operation* that uses `yield`\n to enable Server Sent Events (SSE) responses.\n\n Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible\n with protocols like MCP that stream SSE over `POST`.\n\n The actual encoding logic lives in the FastAPI routing layer. This class\n serves mainly as a marker and sets the correct `Content-Type`.\n \"\"\"\n\n media_type = \"text/event-stream\"", "source_type": "code", "path": "fastapi/sse.py", "symbol": "EventSourceResponse", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/sse.py#L20-L33", "start_line": 20, "end_line": 33} {"id": "fastapi/sse.py::_check_single_line::L36", "text": "# File: fastapi/sse.py | Symbol: _check_single_line\ndef _check_single_line(v: str | None, field_name: str) -> str | None:\n if v is not None and (\"\\r\" in v or \"\\n\" in v):\n raise ValueError(f\"SSE '{field_name}' must be a single line\")\n return v", "source_type": "code", "path": "fastapi/sse.py", "symbol": "_check_single_line", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/sse.py#L36-L39", "start_line": 36, "end_line": 39} {"id": "fastapi/sse.py::_check_event_single_line::L42", "text": "# File: fastapi/sse.py | Symbol: _check_event_single_line\ndef _check_event_single_line(v: str | None) -> str | None:\n return _check_single_line(v, \"event\")", "source_type": "code", "path": "fastapi/sse.py", "symbol": "_check_event_single_line", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/sse.py#L42-L43", "start_line": 42, "end_line": 43} {"id": "fastapi/sse.py::_check_id_valid::L46", "text": "# File: fastapi/sse.py | Symbol: _check_id_valid\ndef _check_id_valid(v: str | None) -> str | None:\n if v is not None and \"\\0\" in v:\n raise ValueError(\"SSE 'id' must not contain null characters\")\n return _check_single_line(v, \"id\")", "source_type": "code", "path": "fastapi/sse.py", "symbol": "_check_id_valid", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/sse.py#L46-L49", "start_line": 46, "end_line": 49} {"id": "fastapi/sse.py::ServerSentEvent::L52", "text": "# File: fastapi/sse.py | Symbol: ServerSentEvent\nclass ServerSentEvent(BaseModel):\n \"\"\"Represents a single Server-Sent Event.\n\n When `yield`ed from a *path operation function* that uses\n `response_class=EventSourceResponse`, each `ServerSentEvent` is encoded\n into the [SSE wire format](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream)\n (`text/event-stream`).\n\n If you yield a plain object (dict, Pydantic model, etc.) instead, it is\n automatically JSON-encoded and sent as the `data:` field.\n\n All `data` values **including plain strings** are JSON-serialized.\n\n For example, `data=\"hello\"` produces `data: \"hello\"` on the wire (with\n quotes).\n \"\"\"\n\n data: Annotated[\n Any,\n Doc(\n \"\"\"\n The event payload.\n\n Can be any JSON-serializable value: a Pydantic model, dict, list,\n string, number, etc. It is **always** serialized to JSON: strings\n are quoted (`\"hello\"` becomes `data: \"hello\"` on the wire).\n\n Mutually exclusive with `raw_data`.\n \"\"\"\n ),\n ] = None\n raw_data: Annotated[\n str | None,\n Doc(\n \"\"\"\n Raw string to send as the `data:` field **without** JSON encoding.\n\n Use this when you need to send pre-formatted text, HTML fragments,\n CSV lines, or any non-JSON payload. The string is placed directly\n into the `data:` field as-is.\n\n Mutually exclusive with `data`.\n \"\"\"\n ),\n ] = None\n event: Annotated[\n str | None,\n AfterValidator(_check_event_single_line),\n Doc(\n \"\"\"\n Optional event type name.\n\n Maps to `addEventListener(event, ...)` on the browser. When omitted,\n the browser dispatches on the generic `message` event. Must be a\n single line.\n \"\"\"\n ),\n ] = None\n id: Annotated[\n str | None,\n AfterValidator(_check_id_valid),\n Doc(\n \"\"\"\n Optional event ID.\n\n The browser sends this value back as the `Last-Event-ID` header on\n automatic reconnection. **Must be a single line** and must not contain\n null (`\\\\0`) characters.\n \"\"\"\n ),\n ] = None\n retry: Annotated[\n int | None,\n Field(ge=0),\n Doc(\n \"\"\"\n Optional reconnection time in **milliseconds**.\n\n Tells the browser how long to wait before reconnecting after the\n connection is lost. Must be a non-negative integer.\n \"\"\"\n ),\n ] = None\n comment: Annotated[\n str | None,\n Doc(\n \"\"\"\n Optional comment line(s).\n\n Comment lines start with `:` in the SSE wire format and are ignored by\n `EventSource` clients. Useful for keep-alive pings to prevent\n proxy/load-balancer timeouts.\n \"\"\"\n ),\n ] = None\n\n @model_validator(mode=\"after\")\n def _check_data_exclusive(self) -> \"ServerSentEvent\":\n if self.data is not None and self.raw_data is not None:\n raise ValueError(\n \"Cannot set both 'data' and 'raw_data' on the same \"\n \"ServerSentEvent. Use 'data' for JSON-serialized payloads \"\n \"or 'raw_data' for pre-formatted strings.\"\n )\n return self", "source_type": "code", "path": "fastapi/sse.py", "symbol": "ServerSentEvent", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/sse.py#L52-L156", "start_line": 52, "end_line": 156} {"id": "fastapi/sse.py::format_sse_event::L159", "text": "# File: fastapi/sse.py | Symbol: format_sse_event\ndef format_sse_event(\n *,\n data_str: Annotated[\n str | None,\n Doc(\n \"\"\"\n Pre-serialized data string to use as the `data:` field.\n \"\"\"\n ),\n ] = None,\n event: Annotated[\n str | None,\n Doc(\n \"\"\"\n Optional event type name (`event:` field).\n \"\"\"\n ),\n ] = None,\n id: Annotated[\n str | None,\n Doc(\n \"\"\"\n Optional event ID (`id:` field).\n \"\"\"\n ),\n ] = None,\n retry: Annotated[\n int | None,\n Doc(\n \"\"\"\n Optional reconnection time in milliseconds (`retry:` field).\n \"\"\"\n ),\n ] = None,\n comment: Annotated[\n str | None,\n Doc(\n \"\"\"\n Optional comment line(s) (`:` prefix).\n \"\"\"\n ),\n ] = None,\n) -> bytes:\n \"\"\"Build SSE wire-format bytes from **pre-serialized** data.\n\n The result always ends with `\\n\\n` (the event terminator).\n \"\"\"\n lines: list[str] = []\n\n if comment is not None:\n for line in comment.splitlines():\n lines.append(f\": {line}\")\n\n if event is not None:\n lines.append(f\"event: {event}\")\n\n if data_str is not None:\n for line in data_str.splitlines():\n lines.append(f\"data: {line}\")\n\n if id is not None:\n lines.append(f\"id: {id}\")\n\n if retry is not None:\n lines.append(f\"retry: {retry}\")\n\n lines.append(\"\")\n lines.append(\"\")\n return \"\\n\".join(lines).encode(\"utf-8\")", "source_type": "code", "path": "fastapi/sse.py", "symbol": "format_sse_event", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/sse.py#L159-L227", "start_line": 159, "end_line": 227} {"id": "fastapi/sse.py::", "text": "# File: fastapi/sse.py | Symbol: \nfrom typing import Annotated, Any\nfrom annotated_doc import Doc\nfrom pydantic import AfterValidator, BaseModel, Field, model_validator\nfrom starlette.responses import StreamingResponse\n# Canonical SSE event schema matching the OpenAPI 3.2 spec\n# (Section 4.14.4 \"Special Considerations for Server-Sent Events\")\n_SSE_EVENT_SCHEMA: dict[str, Any] = {\n \"type\": \"object\",\n \"properties\": {\n \"data\": {\"type\": \"string\"},\n \"event\": {\"type\": \"string\"},\n \"id\": {\"type\": \"string\"},\n \"retry\": {\"type\": \"integer\", \"minimum\": 0},\n },\n}\n# Keep-alive comment, per the SSE spec recommendation\nKEEPALIVE_COMMENT = b\": ping\\n\\n\"\n# Seconds between keep-alive pings when a generator is idle.\n# Private but importable so tests can monkeypatch it.\n_PING_INTERVAL: float = 15.0", "source_type": "code", "path": "fastapi/sse.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/sse.py#L1-L235", "start_line": 1, "end_line": 235} {"id": "fastapi/staticfiles.py::", "text": "# File: fastapi/staticfiles.py | Symbol: \nfrom starlette.staticfiles import StaticFiles as StaticFiles # noqa", "source_type": "code", "path": "fastapi/staticfiles.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/staticfiles.py#L1-L1", "start_line": 1, "end_line": 1} {"id": "fastapi/templating.py::", "text": "# File: fastapi/templating.py | Symbol: \nfrom starlette.templating import Jinja2Templates as Jinja2Templates # noqa", "source_type": "code", "path": "fastapi/templating.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/templating.py#L1-L1", "start_line": 1, "end_line": 1} {"id": "fastapi/testclient.py::", "text": "# File: fastapi/testclient.py | Symbol: \nfrom starlette.testclient import TestClient as TestClient # noqa", "source_type": "code", "path": "fastapi/testclient.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/testclient.py#L1-L1", "start_line": 1, "end_line": 1} {"id": "fastapi/types.py::", "text": "# File: fastapi/types.py | Symbol: \nimport types\nfrom collections.abc import Callable\nfrom enum import Enum\nfrom typing import Any, TypeVar, Union\nfrom pydantic import BaseModel\nfrom pydantic.main import IncEx as IncEx\nDecoratedCallable = TypeVar(\"DecoratedCallable\", bound=Callable[..., Any])\nUnionType = getattr(types, \"UnionType\", Union)\nModelNameMap = dict[type[BaseModel] | type[Enum], str]\nDependencyCacheKey = tuple[Callable[..., Any] | None, tuple[str, ...], str]", "source_type": "code", "path": "fastapi/types.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/types.py#L1-L12", "start_line": 1, "end_line": 12} {"id": "fastapi/utils.py::is_body_allowed_for_status_code::L26", "text": "# File: fastapi/utils.py | Symbol: is_body_allowed_for_status_code\ndef is_body_allowed_for_status_code(status_code: int | str | None) -> bool:\n if status_code is None:\n return True\n # Ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#patterned-fields-1\n if status_code in {\n \"default\",\n \"1XX\",\n \"2XX\",\n \"3XX\",\n \"4XX\",\n \"5XX\",\n }:\n return True\n current_status_code = int(status_code)\n return not (current_status_code < 200 or current_status_code in {204, 205, 304})", "source_type": "code", "path": "fastapi/utils.py", "symbol": "is_body_allowed_for_status_code", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L26-L40", "start_line": 26, "end_line": 40} {"id": "fastapi/utils.py::get_path_param_names::L43", "text": "# File: fastapi/utils.py | Symbol: get_path_param_names\ndef get_path_param_names(path: str) -> set[str]:\n return set(re.findall(\"{(.*?)}\", path))", "source_type": "code", "path": "fastapi/utils.py", "symbol": "get_path_param_names", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L43-L44", "start_line": 43, "end_line": 44} {"id": "fastapi/utils.py::create_model_field::L58", "text": "# File: fastapi/utils.py | Symbol: create_model_field\ndef create_model_field(\n name: str,\n type_: Any,\n default: Any | None = Undefined,\n field_info: FieldInfo | None = None,\n alias: str | None = None,\n mode: Literal[\"validation\", \"serialization\"] = \"validation\",\n) -> ModelField:\n if annotation_is_pydantic_v1(type_):\n raise PydanticV1NotSupportedError(\n \"pydantic.v1 models are no longer supported by FastAPI.\"\n f\" Please update the response model {type_!r}.\"\n )\n field_info = field_info or FieldInfo(annotation=type_, default=default, alias=alias)\n try:\n return v2.ModelField(mode=mode, name=name, field_info=field_info)\n except PydanticSchemaGenerationError:\n raise fastapi.exceptions.FastAPIError(\n _invalid_args_message.format(type_=type_)\n ) from None", "source_type": "code", "path": "fastapi/utils.py", "symbol": "create_model_field", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L58-L77", "start_line": 58, "end_line": 77} {"id": "fastapi/utils.py::generate_operation_id_for_path::L80", "text": "# File: fastapi/utils.py | Symbol: generate_operation_id_for_path\ndef generate_operation_id_for_path(\n *, name: str, path: str, method: str\n) -> str: # pragma: nocover\n warnings.warn(\n message=\"fastapi.utils.generate_operation_id_for_path() was deprecated, \"\n \"it is not used internally, and will be removed soon\",\n category=FastAPIDeprecationWarning,\n stacklevel=2,\n )\n operation_id = f\"{name}{path}\"\n operation_id = re.sub(r\"\\W\", \"_\", operation_id)\n operation_id = f\"{operation_id}_{method.lower()}\"\n return operation_id", "source_type": "code", "path": "fastapi/utils.py", "symbol": "generate_operation_id_for_path", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L80-L92", "start_line": 80, "end_line": 92} {"id": "fastapi/utils.py::generate_unique_id::L95", "text": "# File: fastapi/utils.py | Symbol: generate_unique_id\ndef generate_unique_id(route: \"APIRoute\") -> str:\n operation_id = f\"{route.name}{route.path_format}\"\n operation_id = re.sub(r\"\\W\", \"_\", operation_id)\n assert route.methods\n operation_id = f\"{operation_id}_{list(route.methods)[0].lower()}\"\n return operation_id", "source_type": "code", "path": "fastapi/utils.py", "symbol": "generate_unique_id", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L95-L100", "start_line": 95, "end_line": 100} {"id": "fastapi/utils.py::deep_dict_update::L103", "text": "# File: fastapi/utils.py | Symbol: deep_dict_update\ndef deep_dict_update(main_dict: dict[Any, Any], update_dict: dict[Any, Any]) -> None:\n for key, value in update_dict.items():\n if (\n key in main_dict\n and isinstance(main_dict[key], dict)\n and isinstance(value, dict)\n ):\n deep_dict_update(main_dict[key], value)\n elif (\n key in main_dict\n and isinstance(main_dict[key], list)\n and isinstance(update_dict[key], list)\n ):\n main_dict[key] = main_dict[key] + update_dict[key]\n else:\n main_dict[key] = value", "source_type": "code", "path": "fastapi/utils.py", "symbol": "deep_dict_update", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L103-L118", "start_line": 103, "end_line": 118} {"id": "fastapi/utils.py::get_value_or_default::L121", "text": "# File: fastapi/utils.py | Symbol: get_value_or_default\ndef get_value_or_default(\n first_item: DefaultPlaceholder | DefaultType,\n *extra_items: DefaultPlaceholder | DefaultType,\n) -> DefaultPlaceholder | DefaultType:\n \"\"\"\n Pass items or `DefaultPlaceholder`s by descending priority.\n\n The first one to _not_ be a `DefaultPlaceholder` will be returned.\n\n Otherwise, the first item (a `DefaultPlaceholder`) will be returned.\n \"\"\"\n items = (first_item,) + extra_items\n for item in items:\n if not isinstance(item, DefaultPlaceholder):\n return item\n return first_item", "source_type": "code", "path": "fastapi/utils.py", "symbol": "get_value_or_default", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L121-L136", "start_line": 121, "end_line": 136} {"id": "fastapi/utils.py::", "text": "# File: fastapi/utils.py | Symbol: \nimport re\nimport warnings\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Literal,\n)\nimport fastapi\nfrom fastapi._compat import (\n ModelField,\n PydanticSchemaGenerationError,\n Undefined,\n annotation_is_pydantic_v1,\n)\nfrom fastapi.datastructures import DefaultPlaceholder, DefaultType\nfrom fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError\nfrom pydantic.fields import FieldInfo\nfrom ._compat import v2\nif TYPE_CHECKING: # pragma: nocover\n from .routing import APIRoute\n_invalid_args_message = (\n \"Invalid args for response field! Hint: \"\n \"check that {type_} is a valid Pydantic field type. \"\n \"If you are using a return type annotation that is not a valid Pydantic \"\n \"field (e.g. Union[Response, dict, None]) you can disable generating the \"\n \"response model from the type annotation with the path operation decorator \"\n \"parameter response_model=None. Read more: \"\n \"https://fastapi.tiangolo.com/tutorial/response-model/\"\n)", "source_type": "code", "path": "fastapi/utils.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/utils.py#L1-L55", "start_line": 1, "end_line": 55} {"id": "fastapi/websockets.py::", "text": "# File: fastapi/websockets.py | Symbol: \nfrom starlette.websockets import WebSocket as WebSocket # noqa\nfrom starlette.websockets import WebSocketDisconnect as WebSocketDisconnect # noqa\nfrom starlette.websockets import WebSocketState as WebSocketState # noqa", "source_type": "code", "path": "fastapi/websockets.py", "symbol": "", "url": "https://github.com/fastapi/fastapi/blob/master/fastapi/websockets.py#L1-L3", "start_line": 1, "end_line": 3} {"id": "issue::10007", "text": "# Issue #10007: Pydantic v2, dataclasses, UUID, and `__annotations__`\nLabels: bug\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nThe combination of using:\r\n\r\n* Pydantic v2\r\n* dataclasses (instead of Pydantic models)\r\n* UUIDs\r\n* `from future import __annotations__`\r\n\r\nseems to break in a strange way.\r\n\r\nThis was original reported in this discussion by @sanzoghenzo: https://github.com/tiangolo/fastapi/discussions/9709#discussioncomment-6449458\r\n\r\nIn particular the comment by @raddevon with the minimal example by @fantix:\r\n\r\n```Python\r\nfrom __future__ import annotations\r\n\r\nimport uuid\r\nfrom dataclasses import dataclass, field\r\nfrom typing import List, Union\r\n\r\nfrom fastapi import FastAPI\r\n\r\n\r\n@dataclass\r\nclass Item:\r\n id: uuid.UUID\r\n name: str\r\n price: float\r\n tags: List[str] = field(default_factory=list)\r\n description: Union[str, None] = None\r\n tax: Union[float, None] = None\r\n\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/items/next\", response_model=Item)\r\nasync def read_next_item():\r\n return {\r\n \"name\": \"Island In The Moon\",\r\n \"price\": 12.99,\r\n \"description\": \"A place to be be playin' and havin' fun\",\r\n \"tags\": [\"breater\"],\r\n }\r\n```\r\n\r\nStarting FastAPI with that breaks with an error of:\r\n\r\n
\r\nlog\r\n\r\n```\r\nuvicorn main:app\r\nTraceback (most recent call last):\r\n File \"/Users/user/code/fastapi/env3.10/lib/python3.10/site-packages/pydantic/type_adapter.py\", line 165, in __init__\r\n core_schema = _getattr_no_parents(type, '__pydantic_core_schema__')\r\n File \"/Users/user/code/fastapi/env3.10/lib/python3.10/site-packages/pydantic/type_adapter.py\", line 97, in _getattr_no_parents\r\n raise AttributeError(attribute)\r\nAttributeError: __pydantic_core_schema__\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/Users/user/code/fastapi/env3.10/lib/python3.10/site-packages/pydantic/_internal/_generate_schema.py\", line 625, in _resolve_forward_ref\r\n obj = _typing_extra.evaluate_fwd_ref(obj, globalns=self._types_namespace)\r\n File \"/Users/user/code/fastapi/env3.10/lib/python3.10/site-packages/pydantic/_internal/_typing_extra.py\", line 423, in evaluate_fwd_ref\r\n return ref._evaluate(globalns=globalns, localns=localns, recursive_guard=frozenset())\r\n File \"/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/typing.py\", line 694, in _evaluate\r\n eval(self.__forward_code__, globalns, localns),\r\n File \"\", line 1, in \r\nNameError: name 'uuid' is not defined\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File \"/Users/user/code/fastapi/env3.10/bin/uvicorn\", line 8, in \r\n sys.exit(main())\r\n File \"/Users/user/code/fastapi/env3.10/lib/python3.10/site-packages/click/core.py\", line 1130, in __call__\r\n return self.main(*args, **kwargs)\r\n File \"/Users/user/code/fastapi/env3.10/lib/python3.10/site-packages/click/core.py\", line 1055, in main\r\n \n---\nComment: This would need to be handled on the Pydantic side (or at least require some input/changes from them). https://github.com/pydantic/pydantic/issues/7111\r\n\r\nAs @harunyasar mentions, there's a simple workaround, to use Pydantic's flavor of `dataclasses` instead of the standard library ones.\r\n\r\n```Python\r\nfrom pydantic.dataclasses import dataclass\r\n```\r\n\r\nI understand this is one of the things that begs for PEP 649 (Deferred Evaluation Of Annotations Using Descriptors) that will hopefully come to Python 3.13 🎉 \n---\nComment: This now works with the latest Pydantic versions (probably starting with 2.10), I believe since we refactored forward annotations evaluation.\n---\nComment: Maybe using an id of type str can solve the problem...\r\n\r\nclass Item:\r\n id: str # Using string instead of uuid.UUID\r\n name: str\r\n price: float\r\n tags: List[str] = field(default_factory=list)\r\n description: Union[str, None] = None\r\n tax: Union[float, None] = None\r\n", "source_type": "issue", "path": "issues/10007.json", "symbol": "Pydantic v2, dataclasses, UUID, and `__annotations__`", "url": "https://github.com/fastapi/fastapi/issues/10007", "start_line": null, "end_line": null} {"id": "issue::10127", "text": "# Issue #10127: Cannot use `Response` type hint as dependency annotation\n### Privileged issue\r\n\r\n- [ ] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\nFastAPI `0.95.0` introduced `Annotated` as a way to create dependencies (https://fastapi.tiangolo.com/release-notes/#0950).\r\n\r\nBefore `0.95.0`, it was possible to use `Response` as a type hint for dependencies. After that, it was not possible anymore.\r\n\r\n- See #9897 for more details - Thanks @holyoaks for the report.\r\n\r\nExample that worked before:\r\n\r\n```py\r\nfrom typing import Annotated\r\nfrom fastapi import FastAPI, Response, Depends\r\n\r\napp = FastAPI()\r\n\r\ndef set_no_cache_headers(response: Response) -> Response:\r\n response.headers[\"Potato\"] = \"potato\"\r\n return response\r\n\r\n@app.get(\"/\")\r\ndef testing_response(response: Response = Depends(set_no_cache_headers)):\r\n return {}\r\n```\r\n\r\nAs a workaround today, if you remove the `Response` type hint, it works as expected:\r\n\r\n```py\r\n@app.get(\"/\")\r\ndef testing_response(response = Depends(set_no_cache_headers)):\r\n return {}\r\n```\r\n\r\nThe `Annotated` way also doesn't work:\r\n\r\n```py\r\n@app.get(\"/\")\r\ndef testing_response(response: Annotated[Response, Depends(set_no_cache_headers)]):\r\n return {}\r\n```\n---\nComment: Given how obvious the block is in code, should we assume that it was intentional and update the docs?\n---\nComment: This should be solved by https://github.com/fastapi/fastapi/pull/14794 , it will be available in FastAPI 0.128.2, released in the next few hours. 🚀 \n---\nComment: ```python\r\nfrom typing import Annotated\r\nfrom fastapi import FastAPI, Response, Depends\r\n\r\napp = FastAPI()\r\n\r\ndef set_no_cache_headers(response: Response) -> Response:\r\n response.headers[\"Potato\"] = \"potato\"\r\n return response\r\n\r\n@app.get(\"/\")\r\ndef testing_response(response = Annotated[Response, Depends(set_no_cache_headers)]):\r\n return {}\r\n```\r\n \r\nThis works as well", "source_type": "issue", "path": "issues/10127.json", "symbol": "Cannot use `Response` type hint as dependency annotation", "url": "https://github.com/fastapi/fastapi/issues/10127", "start_line": null, "end_line": null} {"id": "issue::10177", "text": "# Issue #10177: HTTPBearer security scheme is returning 403 instead or 401\nLabels: bug\n### Discussed in https://github.com/tiangolo/fastapi/discussions/9130\r\n\r\n
\r\n\r\nOriginally posted by **aaaaahaaaaa** September 8, 2020\r\nHTTPBearer security scheme enabled as a dependency is returning a `403` when a request is unauthenticated because of a missing or a malformed `authorization` header. In those scenarios, a `401` should be returned instead.
\r\n\r\n## Related PRs\r\n- https://github.com/tiangolo/fastapi/pull/2120\r\n- https://github.com/tiangolo/fastapi/pull/5310\r\n- https://github.com/tiangolo/fastapi/pull/5332\r\n- https://github.com/tiangolo/fastapi/pull/9312\n---\nComment: This not only affects the `HTTPBearer`, but a lot of other classes in the `security` scope also return 403 in `\"Not authenticated\"` cases where they should return 401 instead, such as the `OAuth2` class (though strangely enough not the subclasses `OAuth2PasswordBearer` and `OAuth2AuthorizationCodeBearer`), the `HTTPBase` class and its sublasses (except for `HTTPBasic` for some reason), all classes in `api_key.py` and `OpenIdConnect`. Would probably be good if that could be straightened out for all occurrences there.\n---\nComment: Will there be any progress in the future? Will this error be fixed? I just hope that when the client receives a 403 response, it prompts the user that they do not have access to the corresponding resource, and when a 401 response is received, it redirects to the login page. It seems that this cannot be achieved with the current default implementation of FastAPI.\n---\nComment: Sorry, my misunderstanding. At any rate, I don't think it is necessary after reading section 3 again I realised they offered an example for this scenario.\r\n\r\n**tldr; 401 seems like the appropriate error code 👍** \r\n\r\n```\r\n If the request lacks any authentication information (e.g., the client\r\n was unaware that authentication is necessary or attempted using an\r\n unsupported authentication method), the resource server SHOULD NOT\r\n include an error code or other error information.\r\n\r\n For example:\r\n\r\n HTTP/1.1 401 Unauthorized\r\n WWW-Authenticate: Bearer realm=\"example\"\r\n```", "source_type": "issue", "path": "issues/10177.json", "symbol": "HTTPBearer security scheme is returning 403 instead or 401", "url": "https://github.com/fastapi/fastapi/issues/10177", "start_line": null, "end_line": null} {"id": "issue::10180", "text": "# Issue #10180: Mounting sub-applications under `APIRouter`\nLabels: bug\n### Discussed in https://github.com/tiangolo/fastapi/discussions/8682\r\n\r\n
\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom fastapi import FastAPI, APIRouter\r\nfrom starlette.testclient import TestClient\r\n\r\napp = FastAPI()\r\napi_router = APIRouter(prefix=\"/api\")\r\n\r\n\r\n@api_router.get(\"/app\")\r\ndef read_main():\r\n return {\"message\": \"Hello World from main app\"}\r\n\r\n\r\napp.include_router(api_router)\r\n\r\nsubapi = FastAPI()\r\n\r\n\r\n@subapi.get(\"/sub\")\r\ndef read_sub():\r\n return {\"message\": \"Hello World from sub API\"}\r\n\r\n\r\napi_router.mount(\"/subapi\", subapi)\r\n\r\nclient = TestClient(app)\r\n\r\nassert client.get('/api/app').status_code == 200\r\n\r\n# this next assert fails\r\nassert client.get('/api/subapi/sub').status_code == 200\r\n```\r\n\r\n\r\n### Description\r\n\r\nIs it possible to mount a sub-application under an APIRouter? APIRouter itself has a mount function and accepts similar arguments to mounting a sub-application on a FastAPI instance, but I can't get the routing to actually work (nor can i get the openapi docs or spec to come back from that I would assume are the correct URLs.\r\n\r\nThe docs for sub applications note that the sub-application will have it's root_path correctly set, and I've tried a few combinations of manually setting the root_path on the subapi instance, but to no avail.\r\n\r\n## Related\r\n- https://github.com/tiangolo/fastapi/discussions/9070\r\n- https://github.com/tiangolo/fastapi/pull/5373\n---\nComment: Here we should either raise on `APIRouter.mount` or make it work.\n---\nComment: this is a known limitation. While APIRouter inherits the .mount() method from Starlette, FastAPI's include_router logic is currently optimized to process APIRoute objects (standard endpoints). It doesn't correctly propagate Mount objects (sub-apps) when a router is included in a main app.\n\nCurrently, the best practice is to mount your sub-application directly to the main FastAPI instance using the full path prefix: app.mount(\"/api/v1/sub\", sub_app). This ensures that the routing table and the root_path (for Swagger UI) are handled correctly.\n---\nComment: I dont see a reason of binding two FastAPI instances, perhaps in your usecase you're trying to merge two applications, in this case you should have a service that extracts endpoints and mounts them into an APIRouter", "source_type": "issue", "path": "issues/10180.json", "symbol": "Mounting sub-applications under `APIRouter`", "url": "https://github.com/fastapi/fastapi/issues/10180", "start_line": null, "end_line": null} {"id": "issue::10236", "text": "# Issue #10236: Inconsistent add_api_route types\nLabels: bug, good first issue, confirmed, easy close\n### Discussed in https://github.com/tiangolo/fastapi/discussions/10235\r\n\r\n
\r\n\r\nOriginally posted by **sidekick-eimantas** September 12, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\n### Direct mounting of routes\r\nimport pathlib\r\n\r\nfrom fastapi import FastAPI, APIRouter\r\nimport uvicorn\r\nimport pydantic\r\n\r\nclass HelloRequest(pydantic.BaseModel):\r\n id: str\r\n\r\n\r\nclass HelloResponse(pydantic.BaseModel):\r\n hello: str\r\n\r\n\r\nclass Hello:\r\n def __init__(self, name: str) -> None:\r\n self.name = name\r\n\r\n async def handle(self, request: HelloRequest) -> HelloResponse:\r\n return HelloResponse(hello=self.name)\r\n\r\napp = FastAPI()\r\nhello_handler = Hello(name=\"test\")\r\napp.add_api_route(\"/hello\", hello_handler.handle, methods=[\"POST\"])\r\n\r\n\r\n\r\n\r\n\r\n\r\n### Mounting of paths via Router\r\nimport pathlib\r\n\r\nfrom fastapi import FastAPI, APIRouter\r\nimport uvicorn\r\nimport pydantic\r\n\r\nclass HelloRequest(pydantic.BaseModel):\r\n id: str\r\n\r\n\r\nclass HelloResponse(pydantic.BaseModel):\r\n hello: str\r\n\r\n\r\nclass Hello:\r\n def __init__(self, name: str) -> None:\r\n self.name = name\r\n\r\n async def handle(self, request: HelloRequest) -> HelloResponse:\r\n return HelloResponse(hello=self.name)\r\n\r\n\r\nclass RootRouter:\r\n def __init__(self, name: str):\r\n self.router = APIRouter()\r\n hello_handler = Hello(name=name)\r\n self.router.add_api_route(\"/hello\", hello_handler.handle, methods=[\"POST\"])\r\n\r\n\r\napp = FastAPI()\r\nroot_router = RootRouter(name=\"test\")\r\napp.include_router(root_router.router)\r\n```\r\n\r\n\r\n### Description\r\n\r\nFirst example produces a mypy error:\r\n```\r\nerror: Argument 2 to \"add_api_route\" of \"FastAPI\" has incompatible type \"Callable[[HelloRequest], Coroutine[Any, Any, HelloResponse]]\"; expected \"Callable[..., Coroutine[Any, Any, Response]]\" [arg-type]\r\n```\r\n\r\nSecond example does not.\r\n\r\nThe types of `endpoint` parameter in `FastAPI.add_api_route` and `APIRouter.add_api_route` are inconsistent.\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.103.1\r\n\r\n### Pydantic Version\r\n\r\n2.3.0\r\n\r\n### Python Version\r\n\r\n3.10.7\r\n\r\n### Additi\n---\nComment: This is a valid issue. The type hint of both `endpoint` parameters should match.\r\n\r\nShould be easy to fix - I don't know which one @tiangolo wants.\n---\nComment: Hey @Kludex \r\n\r\nI want to help on this issue if no one is interested, I have used FastAPI before in some hobby projects but this is my first OSS contribution! \n---\nComment: I'll take this if no one else is!\r\n\r\n> I don't know which one tiangolo wants.\r\n\r\nI would think `Callable[..., Any]` is preferred:\r\n\r\n- `FastAPI.add_api_route` makes a direct call to `APIRouter.add_api_route` anyways \r\n- `fastapi.dependencies.utils.get_typed_return_annotation` has signature `def get_typed_return_annotation(call: Callable[..., Any]) -> Any:`\r\n- A lot of other functions with similar parameters use the same typing (e.g. `FastAPI.add_api_websocket_route`)\r\n- The api router instantiates `route_class: Type[APIRoute]` of which `fastapi.routing.APIRoute` subclasses [`starlette.routing.Route` which also types `endpoint` with `Callable[..., typing.Any]`](https://github.com/encode/starlette/blob/master/starlette/routing.py#L211-L215)\r\n\r\nHappy to work with either", "source_type": "issue", "path": "issues/10236.json", "symbol": "Inconsistent add_api_route types", "url": "https://github.com/fastapi/fastapi/issues/10236", "start_line": null, "end_line": null} {"id": "issue::10259", "text": "# Issue #10259: How to define custom objects as query parameters in FastAPI (using PydanticV2 annotations)?\nLabels: question\n### Discussed in https://github.com/tiangolo/fastapi/discussions/10101\r\n\r\n
\r\n\r\nOriginally posted by **DSamuylov** August 17, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nimport bson\r\nfrom typing import Annotated\r\n\r\nfrom pydantic import (\r\n field_validator,\r\n PlainSerializer,\r\n WithJsonSchema,\r\n BeforeValidator,\r\n TypeAdapter,\r\n)\r\nfrom fastapi import FastAPI\r\n\r\n\r\nObjectId = Annotated[\r\n bson.ObjectId,\r\n BeforeValidator(lambda x: bson.ObjectId(x) if isinstance(x, str) else x),\r\n PlainSerializer(lambda x: f\"{x}\", return_type=str),\r\n WithJsonSchema({\"type\": \"string\"}, mode=\"validation\"),\r\n WithJsonSchema({\"type\": \"string\"}, mode=\"serialization\"),\r\n]\r\n\r\n# Casting from str to ObjectId - WORKS\r\nta = TypeAdapter(\r\n ObjectId,\r\n config=dict(arbitrary_types_allowed=True),\r\n)\r\nta.validate_python(\"5f7f9f0c2a0e0b0001d5b3d0\")\r\nta.json_schema()\r\n\r\n# Use ObjectId as a query parameter in FastAPI - FAILS:\r\napp = FastAPI()\r\n\r\n@app.get(\"/test\")\r\ndef test(id: ObjectId) -> bool:\r\n return True\r\n```\r\n\r\n\r\n### Description\r\n\r\nI am trying to figure out how to update my FastAPI app after from Pydantic v1 to Pydantic v2.\r\n\r\nBefore I had code that worked perfectly fine:\r\n\r\n\r\n```\r\nclass ObjectId(bson.ObjectId):\r\n @classmethod\r\n def __get_validators__(cls):\r\n yield cls.validate\r\n\r\n @classmethod\r\n def validate(cls, value):\r\n if isinstance(value, str):\r\n try:\r\n return bson.ObjectId(value)\r\n except bson.errors.InvalidId:\r\n raise ValueError(\"Invalid ObjectId\")\r\n elif isinstance(value, bson.ObjectId):\r\n return value\r\n else:\r\n raise TypeError(\"ObjectId required\")\r\n\r\n\r\napp = FastAPI()\r\n\r\n@app.get(\"/test\")\r\ndef test(id: ObjectId) -> bool:\r\n return True\r\n```\r\n\r\nWith the code that I provided above, I get the following error message:\r\n\r\n> fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that is a valid Pydantic field type. If you are using a return type annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can\n---\nComment: There's at least one issue here: the error message says there's a problem with the response field.\r\nAt least, the problem it should point out is on the request.\n---\nComment: Bumping this up, as is still an issue ; neither the error message nor the implementation have been fixed @tiangolo \n---\nComment: If that can help, I made a very small code to reproduce @Kludex \r\n\r\n```\r\nfrom fastapi import FastAPI\r\n\r\nclass MyType(int):\r\n ...\r\n\r\napp = FastAPI()\r\n@app.get(path=\"/async\")\r\nasync def get_test(\r\n int_input: MyType,\r\n) -> None:\r\n return None\r\n```\r\n\r\nThe work-around is to not create the type in the query parameters, but in the function.\r\n```\r\nasync def get_test(\r\n int_input: int,\r\n) -> None:\r\n my_input = MyType(int_input)\r\n return None\r\n```", "source_type": "issue", "path": "issues/10259.json", "symbol": "How to define custom objects as query parameters in FastAPI (using PydanticV2 annotations)?", "url": "https://github.com/fastapi/fastapi/issues/10259", "start_line": null, "end_line": null} {"id": "issue::10286", "text": "# Issue #10286: `Body` related parameters don't take `alias` in consideration\nLabels: bug\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nThe `Body`, `File`, and `Form` parameters don't support `alias`.\r\n\r\nThe following snippet demonstrates the issue: \r\n\r\n```py\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import Body, Cookie, FastAPI, Form, UploadFile, File, Query, Header, Path\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.post(\"/{path}\")\r\ndef endpoint(\r\n path: Annotated[int, Path(alias=\"PathAlias\")],\r\n cookie: Annotated[int, Cookie(alias=\"CookieAlias\")],\r\n header: Annotated[int, Header(alias=\"HeaderAlias\")],\r\n query: Annotated[int, Query(alias=\"QueryAlias\")],\r\n body: Annotated[int, Body(alias=\"BodyAlias\")],\r\n form: Annotated[int, Form(alias=\"FormAlias\")],\r\n file: Annotated[UploadFile, File(alias=\"FileAlias\")],\r\n):\r\n ...\r\n```\r\n\r\nIf you look at the generated Swagger you see that `alias` is only being used for `params.Param` related fields i.e. `Path`, `Cookie`, etc.\r\n\r\n\"Screenshot\r\n\r\nPeople can overcome this right now using `validation_alias` as follows:\r\n\r\n```py\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import Body, Cookie, FastAPI, Form, UploadFile, File, Query, Header, Path\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.post(\"/{path}\")\r\ndef endpoint(\r\n path: Annotated[int, Path(alias=\"PathAlias\")],\r\n cookie: Annotated[int, Cookie(alias=\"CookieAlias\")],\r\n header: Annotated[int, Header(alias=\"HeaderAlias\")],\r\n query: Annotated[int, Query(alias=\"QueryAlias\")],\r\n body: Annotated[int, Body(validation_alias=\"BodyAlias\")],\r\n form: Annotated[int, Form(validation_alias=\"FormAlias\")],\r\n file: Annotated[UploadFile, File(validation_alias=\"FileAlias\")],\r\n):\r\n ...\r\n```\r\n\r\nIn any case, this should be fixed in FastAPI.\n---\nComment: Any updates on this?\n---\nComment: **When I use only validation_alias in Form I can see alias in Swagger, but the validation is not working well.\r\nFor the moment I'm using both alias and validation_alias, It works.**\r\n\r\nI think issue is as FastAPI pass validation_alias to FieldInfo of Pydantic v2 in super().__init__ () inside class Body\n---\nComment: Hi, as @Kludex told me to watch this issue I wanted to make sure if I apply the workaround correctly as it is not (maybe no longer, not 100% sure on that) working. The context you can find in this discussion: https://github.com/tiangolo/fastapi/discussions/11004\r\n\r\nI tried:\r\n```python\r\nasync def upload_docs(\r\n files: list[UploadFile] = File(..., validation_alias=\"file\")\r\n) -> dict:\r\n```\r\nand this\r\n```python\r\nasync def upload_docs(\r\n files: list[UploadFile] = File(..., alias=\"file\", validation_alias=\"file\")\r\n) -> dict:\r\n```\r\nwithout success.\r\n\r\nI want my multipart form data file upload to allow for either file or files in the post body to be compatible with some legacy systems. ", "source_type": "issue", "path": "issues/10286.json", "symbol": "`Body` related parameters don't take `alias` in consideration", "url": "https://github.com/fastapi/fastapi/issues/10286", "start_line": null, "end_line": null} {"id": "issue::10322", "text": "# Issue #10322: Get the StringConstraints directly from the Identifier type\nLabels: feature, confirmed\n**Problem:**\r\nFastAPI does not validate custom string build using `Annotated[str, StringConstraints(...)]`\r\n\r\n**Temporary solution**\r\n_My solution is to annotate the constrained type with Path again, then it seems to work:_\r\n\r\n```python\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import FastAPI, Path\r\nfrom pydantic import StringConstraints\r\n\r\n# In my case this is imported from a lib with pydantic but without fastapi,\r\n# so it can't be changed to Annotated[str, Path(pattern=r\"^[a-fA-F0-9]+$\")]\r\nIdentifier = Annotated[str, StringConstraints(pattern=r\"^[a-fA-F0-9]+$\")]\r\n\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/{some_id}\")\r\nasync def get_something(some_id: Annotated[Identifier, Path()]):\r\n return some_id\r\n\r\n```\r\n\r\n**Feature request**\r\nWould be nice if fastapi would be able to get the constraint directly from the `Identifier` type without being required to add `Annotated[Identifier, Path()]`.\r\n\r\n_Originally posted by @JasperJuergensen in https://github.com/tiangolo/fastapi/discussions/10105#discussioncomment-6901418_\n---\nComment: What the OP wants is this:\r\n\r\n```py\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import FastAPI, Path\r\nfrom pydantic import StringConstraints\r\n\r\nIdentifier = Annotated[str, StringConstraints(pattern=r\"^[a-fA-F0-9]+$\")]\r\n\r\napp = FastAPI()\r\n\r\n@app.get(\"/{some_id}\")\r\nasync def get_something(some_id: Identifier):\r\n return some_id\r\n```\r\n\r\nA similar feature request is to use `pydantic.Field`.\n---\nComment: It is because missing the matadata when none of Annotated args is `FieldInfo` or `Depends`\r\nI've commit a fix pr #10356 . Hope it's work \n---\nComment: Isn't it pretty much the same as #10259 and #10109?", "source_type": "issue", "path": "issues/10322.json", "symbol": "Get the StringConstraints directly from the Identifier type", "url": "https://github.com/fastapi/fastapi/issues/10322", "start_line": null, "end_line": null} {"id": "issue::10360", "text": "# Issue #10360: Working with Pydantic v1 while having v2 installed\n### Discussed in https://github.com/tiangolo/fastapi/discussions/9966\r\n\r\n
\r\n\r\nOriginally posted by **slafs** July 29, 2023\r\nThis is a continuation of a topic introduced in https://github.com/tiangolo/fastapi/discussions/9709#discussioncomment-6449868 as requested by @Kludex. I've chosen the \"Show and tell\" category as the (lack of) template seems better for this discussion.\r\n\r\nIn the original thread I've asked if there's a way to work with pydantic v1 while having v2 installed:\r\n\r\nPydantic v2 ships the latest version of v1 for easier migration, so the pattern is to work with v1 via things like `from pydantic.v1 import BaseModel` etc. while having v2 installed.\r\n\r\nCurrently, this approach doesn't seem to work with FastAPI 0.100.0 and the following snippet:\r\n```py\r\nfrom fastapi import FastAPI\r\n\r\nfrom pydantic.v1 import BaseModel\r\n\r\n\r\nclass Model(BaseModel):\r\n foo: str = \"foo\"\r\n bar: int = 2\r\n\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/\")\r\ndef root(model: Model) -> Model:\r\n return model\r\n```\r\nproduces the following error:\r\n```\r\nTraceback (most recent call last):\r\n File \".../fiddles/fastapi_pydantic_v1_on_v2.py\", line 15, in \r\n def root(model: Model) -> Model:\r\n File \".../lib/python3.10/site-packages/fastapi/routing.py\", line 706, in decorator\r\n self.add_api_route(\r\n File \".../lib/python3.10/site-packages/fastapi/routing.py\", line 645, in add_api_route\r\n route = route_class(\r\n File \".../lib/python3.10/site-packages/fastapi/routing.py\", line 448, in __init__\r\n self.response_field = create_response_field(\r\n File \".../lib/python3.10/site-packages/fastapi/utils.py\", line 101, in create_response_field\r\n raise fastapi.exceptions.FastAPIError(\r\nfastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that is a valid Pydantic field type. If you are using a return type annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can disable generating the response model from the type annotation with the path operation decorator parameter response_model=None. Read more: https://fastapi.tiangolo.com/tutorial/response-model/\r\n```\r\n\r\nSwitching from `pydantic.v1` to just `pydantic` (v2) obviously works.\r\n\r\nI'm seeing there's `fastapi._compat` module and `PYDANTIC_V2` var, but I'm not sure if that's the right direction.\r\n\r\nFor reference, installed versions:\r\n```\r\nfastapi==0.100.0\r\npydantic==2.0.3\r\npydantic_core==2.3.0\r\n```\r\n\r\n----\r\n\r\nNow... that being said, I'm not even sure if this would be helpful to anyone even if FastAPI did support it. My initial thought was that this would ease the migration, but the reality seems more complicated. E.g. models are used by other models and even Pydantic itself doesn't support mixing v1 and v2 together. So given that the cost of figuring out the plan for the gradual migration seems comparable with doing the whole migration at once (at least for us).\r\n\r\nMaybe it would be useful if people co\n---\nComment: Any news about this? I thought that i could easily apply fastapi and pydantic v2 upgrade but this totally blocks me.\n---\nComment: Any way of getting some visibility here? It’s currently very hard to migrate for large code bases.\n---\nComment: A good compromise might be if the pydantic v1 vs v2 logic was applied per `APIRouter`.\r\nEach router can use either Pydantic V1 models or V2 models, but not use both simultaneously.\r\n\r\nDevs with a large codebase can then migrate per router (and, if need be, break up their app to use multiple routers).\r\n\r\nThis assumes that implementing this at the `APIRouter` level is easier/more maintainable. ", "source_type": "issue", "path": "issues/10360.json", "symbol": "Working with Pydantic v1 while having v2 installed", "url": "https://github.com/fastapi/fastapi/issues/10360", "start_line": null, "end_line": null} {"id": "issue::10424", "text": "# Issue #10424: RequestValidationError is **not** a sub-class of Pydantic's ValidationError\nLabels: question, docs\n### Discussed in https://github.com/tiangolo/fastapi/discussions/10421\r\n\r\n
\r\n\r\nOriginally posted by **valentinoli** October 10, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\n@app.exception_handler(ValidationError)\r\nasync def validation_exception_handler(request: Request, exc: ValidationError):\r\n return PlainTextResponse(\r\n str(exc), status_code=status.HTTP_500_INTERNAL_SERVER_ERROR\r\n )\r\n```\r\n\r\n\r\n### Description\r\n\r\nI was trying to handle both `RequestValidationError` and `ValidationError` by writing a custom handler for `ValidationError` but that doesn't work.\r\n\r\n[The docs](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions) state that \r\n\r\n> RequestValidationError is a sub-class of Pydantic's [ValidationError](https://pydantic-docs.helpmanual.io/usage/models/#error-handling)\r\n\r\nHowever, looking at [FastAPI source code](https://github.com/tiangolo/fastapi/blob/c1adce4fe93a0035e69988f7e051cfab97d8acef/fastapi/exceptions.py#L36) reveals that this is not the case.\r\n\r\n\r\n### Operating System\r\n\r\nLinux\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.101.0\r\n\r\n### Pydantic Version\r\n\r\n2.1.1\r\n\r\n### Python Version\r\n\r\n3.11.3\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: Documentation. But I'm just bringing it to @tiangolo 's attention.\n---\nComment: Should we fix the docs or the code? IMO having Pydantic's error makes more sense. \n---\nComment: hey Please choose this format\r\n\r\nHere is **main.py**\r\n```\r\nfrom app.infrastructure.exception import validation_exception_handler\r\n\r\napp = FastAPI(\r\n title=settings.PROJECT_NAME,\r\n openapi_url=f\"{settings.API_V1_STR}openapi.json\"\r\n)\r\n\r\n@app.exception_handler(RequestValidationError)\r\nasync def custom_validation_exception_handler(request, exc):\r\n return await validation_exception_handler(request, exc)\r\n```\r\n\r\nHere is exception.py\r\n```\r\nfrom fastapi.exceptions import RequestValidationError\r\nfrom fastapi.responses import JSONResponse\r\nfrom fastapi import Request\r\n\r\nasync def validation_exception_handler(request: Request, exc: RequestValidationError):\r\n error_messages = []\r\n for error in exc.errors():\r\n if error[\"type\"] == \"value_error.email\":\r\n error_messages.append({\"status_code\": 422, \"detail\": \"Invalid email address\"})\r\n else:\r\n error_messages.append({\"status_code\": 422, \"detail\": error[\"msg\"]})\r\n print(error_messages[0])\r\n return ", "source_type": "issue", "path": "issues/10424.json", "symbol": "RequestValidationError is **not** a sub-class of Pydantic's ValidationError", "url": "https://github.com/fastapi/fastapi/issues/10424", "start_line": null, "end_line": null} {"id": "issue::10719", "text": "# Issue #10719: `Annotated` dependencies are interpreted incorrectly when using `PEP 695`-style type alias.\nLabels: question\n### Discussed in https://github.com/tiangolo/fastapi/discussions/10662\r\n\r\n
\r\n\r\nOriginally posted by **Rockmizu** November 16, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom __future__ import annotations\r\n\r\nfrom typing import Annotated, TypeAlias\r\n\r\nfrom fastapi import Depends, FastAPI\r\n\r\napp = FastAPI()\r\n\r\n\r\n# dependency\r\nasync def some_value() -> int:\r\n return 123\r\n\r\n# This works.\r\nDependedValue: TypeAlias = Annotated[int, Depends(some_value)]\r\n\r\n# This won't work.\r\n# type DependedValue = Annotated[int, Depends(some_value)]\r\n\r\n\r\n@app.get('/')\r\nasync def get_with_dep(value: DependedValue) -> str:\r\n print(f'{type(value) = !r}')\r\n print(f'{value = !r}')\r\n\r\n assert isinstance(value, int), '`value` should be an integer.'\r\n assert value == 123, '`value` should be 123.'\r\n\r\n return f'value: {value}'\r\n```\r\n\r\n\r\n### Description\r\n\r\nWhen using the method in line 15:\r\n```python\r\nDependedValue: TypeAlias = Annotated[int, Depends(some_value)]\r\n```\r\nto declare a type alias, FastAPI correctly interprets it and fills the `value` with `123` for `get_with_dep`.\r\n\r\nHowever, when using the new type alias syntax introduced in Python 3.12 (line 18):\r\n```python\r\ntype DependedValue = Annotated[int, Depends(some_value)]\r\n```\r\nFastAPI interprets it as a URL query parameter and responds with HTTP 422 Unprocessable Entity when accessing `/`.\r\n\r\n\r\n## Expected Response\r\n\r\nHTTP 200 OK\r\n\r\n```\r\n\"value: 123\"\r\n```\r\n\r\n\r\n## Actual Response\r\n\r\nHTTP 422 Unprocessable Entity\r\n\r\n```\r\n{\"detail\":[{\"type\":\"missing\",\"loc\":[\"query\",\"value\"],\"msg\":\"Field required\",\"input\":null,\"url\":\"https://errors.pydantic.dev/2.5/v/missing\"}]}\r\n```\r\n\r\n\r\n### Operating System\r\n\r\nWindows\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.104.1\r\n\r\n### Pydantic Version\r\n\r\n2.5.1\r\n\r\n### Python Version\r\n\r\nPython 3.12.0\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: Confirm this issue.\r\n\r\nWith Python 3.12 new `type` syntax, FastAPI ignores the dependency annotation.\r\n\r\n```\r\nfrom typing import Annotated, TypeAlias\r\nfrom fastapi import FastAPI, Query, Depends\r\napp: FastAPI = FastAPI()\r\n\r\ndef get_name1(name1: Annotated[str, Query(title=\"Name\")]) -> str:\r\n return f\"Name: {name1}\"\r\n\r\ndef get_name2(name2: Annotated[str, Query(title=\"Name\")]) -> str:\r\n return f\"Name: {name2}\"\r\n\r\nName1: TypeAlias = Annotated[str, Depends(get_name1)]\r\ntype Name2 = Annotated[str, Depends(get_name2)]\r\n\r\n@app.get(\"/\")\r\nasync def test(name1: Name1, name2: Name2) -> dict[str, str]:\r\n return {\"name1\": name1, \"name2\": name2}\r\n```\r\n\r\nThe dependency `get_name2` is ignored.\r\n\r\n```\r\nuser@host ~ % curl -X 'GET' 'http://localhost:8000/?name1=betty1&name2=betty2' -H 'accept: application/json'\r\n{\"name1\":\"Name: betty1\",\"name2\":\"betty2\"}\r\nuser@host ~ %\r\n```\n---\nComment: For those still waiting for the official FastAPI fix - you can use `fastapi-backports` until the official release.\n\n```bash\npip install fastapi-backports\n```\n\nBrings multiple Query models and PEP 695 type alias support to `FastAPI` until it is officially supported:\n\nhttps://github.com/uriyyo/fastapi-backports\n\nUsage example:\n```py\nimport fastapi_backports.apply # noqa: F401\n\nfrom typing import Annotated, Any\n\nfrom fastapi import FastAPI, Query\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass UserFilters(BaseModel):\n min_age: int | None = None\n max_age: int | None = None\n\n\nclass GroupFilters(BaseModel):\n min_size: int | None = None\n max_size: int | None = None\n\n\ntype UserFiltersDependency = Annotated[\n UserFilters,\n Query(),\n]\n\ntype GroupFiltersDependency = Annotated[\n GroupFilters,\n Query(),\n]\n\n\n@app.get(\"/filters\")\nasync def get_filters(\n user_filters: UserFiltersDependency,\n group_filters: GroupFiltersDependency,\n) -> dict[str, Any]:\n return {\n---\nComment: I'm in search for my first fastapi contribution and as such I might ask some not so clever questions.\r\n\r\nTo this problem:\r\nWouldn't this be solved by unacking the `typing.TypeAliasType` via using it's `__value__` attribute?\r\n\r\nThis can done before [dependencies.utils:328](https://github.com/tiangolo/fastapi/blob/9f4db6d6d39f13cd80f2833ecf31ea5b17c43e07/fastapi/dependencies/utils.py#L328):\r\n\r\n```python\r\n if isinstance(annotation, TypeAliasType):\r\n annotation = annotation.__value__\r\n```\r\n\r\nI can work in python<3.12 with something like:\r\n```python\r\ntry:\r\n from typing import TypeAliasType\r\nexcept ImportError:\r\n TypeAliasType = type(\"TypeAliasType\", tuple(), dict(__value__=None)) # dict content needed?\r\n```\r\n(more elegant approach appreciated)\r\n\r\n\r\n1. Did I miss someting?\r\n2. Is this enough to create a PR?\r\n3. Is it enough when this doesn't break tests or should I add one test?\r\n\r\nBest regards and happy weekend,\r\n\r\nTorsten Zielke", "source_type": "issue", "path": "issues/10719.json", "symbol": "`Annotated` dependencies are interpreted incorrectly when using `PEP 695`-style type alias.", "url": "https://github.com/fastapi/fastapi/issues/10719", "start_line": null, "end_line": null} {"id": "issue::10720", "text": "# Issue #10720: functools.partial() does not work on an async dependable\nLabels: question, investigate\n### Discussed in https://github.com/tiangolo/fastapi/discussions/9744\r\n\r\n
\r\n\r\nOriginally posted by **lieryan** June 26, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom functools import partial\r\n\r\nfrom fastapi import FastAPI, Depends\r\n\r\n\r\napp = FastAPI()\r\n\r\ndef the_answer():\r\n return 42\r\n\r\n\r\nasync def dep1(\r\n n: int = Depends(the_answer),\r\n):\r\n return n + 1\r\n\r\n@app.get(\"/\")\r\ndef main(\r\n d1=Depends(partial(dep1, n=10)),\r\n):\r\n print(d1) # prints \"\"\r\n return {}\r\n\r\n\r\nif __name__ == '__main__':\r\n import uvicorn\r\n uvicorn.run(app, port=1122)\r\n```\r\n\r\n\r\n### Description\r\n\r\nI would've expected `d1` above to be the return value of the dependable, but it seems like fastapi didn't identify the partial as an coroutine function and instead passed the unawaited coroutine into the view function.\r\n\r\n`inspect.iscoroutinefunction()` and `inspect.signature()` were able to deconstruct the partial object to correctly identify whether a partial contains a coroutine or a regular function, so it seems like it should've been possible for FastAPI to use handle partial correctly:\r\n\r\n```\r\nIn [5]: def regular(a, b): pass\r\n\r\nIn [6]: async def coro(a, b): pass\r\n\r\nIn [7]: inspect.iscoroutinefunction(partial(regular, 1))\r\nOut[7]: False\r\n\r\nIn [8]: inspect.iscoroutinefunction(partial(coro, 1))\r\nOut[8]: True\r\n\r\nIn [20]: inspect.signature(partial(coro, 1))\r\nOut[20]: \r\n```\r\n \r\n\r\n### Operating System\r\n\r\nLinux\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.98.0\r\n\r\n### Python Version\r\n\r\nPython 3.10.6\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: > I understand that using an asynchronous function without `await` in a synchronous function will naturally result in a coroutine object. Could you please clarify the intention behind your question? It seems evident that this behavior is expected in Python's asynchronous programming model.\r\n\r\n\r\nIn my opinion,in FastAPI, dependency functions are automatically executed with await added.\r\nThis is based on the [documentation](https://fastapi.tiangolo.com/tutorial/dependencies/#to-async-or-not-to-async)\r\n\n---\nComment: There is a pull request that has the test cases and the fix for this issue: #9753.\r\n\r\n@atapin yeah, async generator dependency works, but it doesn't work for async regular function dependency.\n---\nComment: I understand that using an asynchronous function without `await` in a synchronous function will naturally result in a coroutine object. Could you please clarify the intention behind your question? It seems evident that this behavior is expected in Python's asynchronous programming model.", "source_type": "issue", "path": "issues/10720.json", "symbol": "functools.partial() does not work on an async dependable", "url": "https://github.com/fastapi/fastapi/issues/10720", "start_line": null, "end_line": null} {"id": "issue::10787", "text": "# Issue #10787: Old `HTTPValidationError` and `ValidationError` OpenAPI entry\nLabels: bug\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nThose lines need to be updated:\r\n\r\nhttps://github.com/tiangolo/fastapi/blob/36c26677682c4245183912e00fc057c05cc6cf7a/fastapi/openapi/utils.py#L36-L61\r\n\r\nThey reflect how it was before 0.100.0, but with Pydantic V2, that's no longer true.\n---\nComment: It would be cool to have an API to modify the `RequestValidationError` OpenAPI entry, and not only the `exception_handler`.\n---\nComment: ```\r\nvalidation_error_definition = {\r\n \"title\": \"ValidationError\",\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"loc\": {\r\n \"title\": \"Location\",\r\n \"type\": \"array\",\r\n \"items\": {\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]},\r\n },\r\n \"input\": {\"title\": \"Input\", \"type\": \"any\"},\r\n \"url\": {\"title\": \"URL\", \"type\": \"string\"},\r\n \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\r\n \"type\": {\"title\": \"Error Type\", \"type\": \"string\"},\r\n },\r\n \"required\": [\"loc\", \"msg\", \"type\"],\r\n}\r\n```\r\n\r\nThis is what we need right? But this change would require changing a lot of tests. \n---\nComment: `from` fastapi import FastAPI\r\n\r\napp = FastAPI()\r\n\r\n# Your existing OpenAPI definitions\r\nvalidation_error_definition = {...}\r\nvalidation_error_response_definition = {...}\r\n\r\n# Add the existing definitions to the app\r\napp.openapi_schema[\"components\"][\"schemas\"][\"ValidationError\"] = validation_error_definition\r\napp.openapi_schema[\"components\"][\"schemas\"][\"HTTPValidationError\"] = validation_error_response_definition\r\n\r\n# Define the new definition for HTTPValidationError (modify as needed)\r\nnew_http_validation_error_definition = {\r\n \"title\": \"ModifiedHTTPValidationError\",\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"detail\": {\r\n \"title\": \"Detail\",\r\n \"type\": \"array\",\r\n \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\r\n }\r\n },\r\n}\r\n\r\n# Update the OpenAPI entry\r\nupdate_openapi_entry(app, new_http_validation_error_definition)\r\n\r\n# Your FastAPI routes and other configurations go here\r\n\r\nusing this code stay happy 👍\r\n", "source_type": "issue", "path": "issues/10787.json", "symbol": "Old `HTTPValidationError` and `ValidationError` OpenAPI entry", "url": "https://github.com/fastapi/fastapi/issues/10787", "start_line": null, "end_line": null} {"id": "issue::10857", "text": "# Issue #10857: Passing UploadFile objects into a StreamingResponse closes it in v0.106.0 but not v0.105.0\nLabels: investigate\n### Discussed in https://github.com/tiangolo/fastapi/discussions/10856\r\n\r\n
\r\n\r\nOriginally posted by **adrwz** December 28, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nasync def upload_file_event(files: List[UploadFile]):\r\n print(\"2\", files[0].filename, files[0].file._file.closed)\r\n\r\n # ... more code ...\r\n\r\n\r\n@router.post(\"/upload_session_file\")\r\nasync def upload_file(files: List[UploadFile] = File(...)):\r\n print(\"1\", files[0].filename, files[0].file._file.closed)\r\n\r\n try:\r\n return StreamingResponse(\r\n upload_file_event(files),\r\n media_type=\"text/event-stream\",\r\n )\r\n except Exception as error:\r\n logging.error(error)\r\n raise HTTPException(status_code=500, detail=\"Internal Server Error\")\r\n```\r\n\r\n\r\n### Description\r\n\r\nHitting this endpoint with an uploaded file on v0.105.0 will print:\r\n\r\n```\r\n1 filename false\r\n2 filename false\r\n```\r\n\r\nHitting this endpoint with an uploaded file on v0.106.0 will print:\r\n\r\n```\r\n1 filename false\r\n2 filename true\r\n```\r\n\r\nUnfortunately this means I'm unable to upload files in a StreamingResponse with fastapi>=0.106.0\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.105.0\r\n\r\n### Pydantic Version\r\n\r\n2.5.3\r\n\r\n### Python Version\r\n\r\n3.11.4\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: Any updated on this?\n---\nComment: Is there any update on this issue? I have the same problem , just migrated from `v0.103.0` to `v0.108.0` and realized my tests are failing due the same issue. Is is related to [this breaking change](https://fastapi.tiangolo.com/release-notes/#01060)? \r\nIf yes, what is the proposed approach for handling the UploadFile in the background task?\r\nmy old practice is written below\r\n``` python\r\n\r\nasync def upload_csv_to_gcloud_blob_storage(\r\n self, file: UploadFile, bucket_name: str, blob_storage_path:str\r\n):\r\n \"\"\"write the data to a bucket with\"\"\"\r\n storage_client = storage.Client()\r\n csv_bucket = storage_client.bucket(bucket_name)\r\n blob = csv_bucket.blob(blob_storage_path)\r\n\r\n try:\r\n with blob.open(\"wb\") as buffer:\r\n shutil.copyfileobj(file.file, buffer)\r\n finally:\r\n file.file.close()\r\n \r\n@app.post( \"/csv_tables\" )\r\nasync def upload_csv(\r\n csv_file: Annotated[UploadFile, File()],\r\n background_tasks: BackgroundTasks,\r\n):\r\n \r\n \n---\nComment: > Another _\"solution\"_ you can consider is reading the file's content before initiating the `StreamingResponse` **if you have other logic despite uploading the files**. I know it does not solve your problem, but depending on your use case it might be useful.\r\n> \r\n> Here’s how you can do it:\r\n> \r\n> ```python\r\n> @my_router.post(\"/import_file\")\r\n> async def import_my_file(file: UploadFile):\r\n> content = await file.read() \r\n> return StreamingResponse(your_method(content), media_type=\"text/event-stream\")\r\n> ```\r\n> \r\n> In this example, `your_method` represents the logic that processes the file's content.\r\n> \r\n> I tested this approach with Python 3.11 and `fastapi==0.110.0`, and it worked successfully.\r\n\r\nYeah but then you have to read the entire file into memory.... ", "source_type": "issue", "path": "issues/10857.json", "symbol": "Passing UploadFile objects into a StreamingResponse closes it in v0.106.0 but not v0.105.0", "url": "https://github.com/fastapi/fastapi/issues/10857", "start_line": null, "end_line": null} {"id": "issue::10997", "text": "# Issue #10997: Using pydantic Json Type as Form data type doesn't work\nLabels: question\n### Discussed in https://github.com/tiangolo/fastapi/discussions/9305\r\n\r\n
\r\n\r\nOriginally posted by **harpaj** March 23, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import FastAPI, Form\r\nfrom pydantic import Json, BaseModel\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass JsonListModel(BaseModel):\r\n json_list: Json[list[str]]\r\n\r\n\r\n@app.post(\"/working\")\r\nasync def working(json_list: Annotated[str, Form()]) -> list[str]:\r\n model = JsonListModel(json_list=json_list)\r\n return model.json_list\r\n\r\n\r\n@app.post(\"/broken\")\r\nasync def broken(json_list: Annotated[Json[list[str]], Form()] ) -> list[str]:\r\n return json_list\r\n```\r\n\r\n\r\n### Description\r\n\r\nIn the example code above, I would expect `working` and `broken` to be approximately equivalent.\r\nHowever, while `working` returns the parsed json_list as expected, `broken` fails with \r\n\r\n```json\r\n{\"detail\":[{\"loc\":[\"body\",\"json_list\"],\"msg\":\"JSON object must be str, bytes or bytearray\",\"type\":\"type_error.json\"}]}\r\n```\r\n\r\n### Operating System\r\n\r\nLinux\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.95.0\r\n\r\n### Python Version\r\n\r\nPython 3.10.8\r\n\r\n### Additional Context\r\n\r\nsample request that fails with `broken` and works with `working`:\r\n```python\r\n\r\nimport requests\r\nimport json\r\n\r\nheaders = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\r\nresponse = requests.post(\r\n \"http://0.0.0.0:8000/broken\",\r\n data={\"json_list\": json.dumps([\"abc\", \"def\"])},\r\n headers=headers,\r\n)\r\n```
\n---\nComment: Hi @Kludex @harpaj\r\nAs I've been reviewing this issue, a few questions have arisen.\r\n\r\n1. Is the primary goal of this issue to enable the Form() function to directly receive data in JSON format? Or, is the focus more on providing documentation and examples for handling this indirectly?\r\n2. Is there a need for detailed documentation on this phenomenon and its causes? Is the goal to provide guidelines to help users understand and appropriately manage this issue?\n---\nComment: anybody working on this presently or is open for me to work on ? \r\n\n---\nComment: Could FastAPI be taking the string 'json_list' and seeing that it is only one string, coercing it into a list by wrapping it?\r\n\r\nThis seems to work\r\n\r\n```python\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import FastAPI, Form\r\nfrom pydantic import Json, BaseModel, BeforeValidator\r\nfrom pydantic_core import from_json\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass JsonListModel(BaseModel):\r\n json_list: Json[list[str]]\r\n\r\n\r\n@app.post(\"/working\")\r\nasync def working(json_list: Annotated[str, Form()]) -> list[str]:\r\n model = JsonListModel(json_list=json_list)\r\n return model.json_list\r\n\r\n@app.post(\"/broken\")\r\nasync def broken(json_list: Annotated[list[str], \r\n BeforeValidator(lambda v: from_json(v[0])),\r\n Form()]) -> list[str]:\r\n return json_list\r\n```\r\n\r\nI would have expected `from_json[v]` to do the trick, but instead I needed to use `from_json(v[0])`\r\n\r\nEdit to add: The test case program works, but the Swagger UI is wrong - it prompts you for a list of strings in", "source_type": "issue", "path": "issues/10997.json", "symbol": "Using pydantic Json Type as Form data type doesn't work", "url": "https://github.com/fastapi/fastapi/issues/10997", "start_line": null, "end_line": null} {"id": "issue::10998", "text": "# Issue #10998: Raw docstring (leading `r`) defeats form feed `\\f` truncation\nLabels: feature\n### Discussed in https://github.com/tiangolo/fastapi/discussions/10531\r\n\r\n
\r\n\r\nOriginally posted by **jamesbraza** October 26, 2023\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom fastapi import FastAPI\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.post(\"/lof\")\r\ndef foo(arg: int = 5) -> int:\r\n \"\"\"\r\n Some function.\r\n \r\n \\f\r\n \r\n Args:\r\n arg: Some argument\r\n\r\n Returns:\r\n Some integer.\r\n \"\"\"\r\n return arg\r\n```\r\n\r\n\r\n### Description\r\n\r\nRunning `ruff==0.1.3` on this, [`D301`](https://docs.astral.sh/ruff/rules/escape-sequence-in-docstring/) will autofix to make the docstring be a raw string (lead by `r`).\r\n\r\n```python\r\n@app.post(\"/lof\")\r\ndef foo(arg: int = 5) -> int:\r\n r\"\"\"\r\n Some function.\r\n \r\n \\f\r\n \r\n Args:\r\n arg: Some argument\r\n\r\n Returns:\r\n Some integer.\r\n \"\"\"\r\n return arg\r\n```\r\n\r\nHowever, this breaks the form feed `\\f` truncation from working, per https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#advanced-description-from-docstring\r\n\r\nI think form feed `\\f` truncation should still work even if the docstring is a raw string.\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\nn/a\r\n\r\n### FastAPI Version\r\n\r\n0.104.0\r\n\r\n### Pydantic Version\r\n\r\n2.4.2\r\n\r\n### Python Version\r\n\r\n3.11.5\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: Well, `r\"\\f\"` ==`\"\\\\f\"` != `\"\\f\"`\n\nWith change you propose to docstrings like `This endpoint saves data to C:\\files\\data` will be truncated to `This endpoint saves data to C:`\n---\nComment: I little bit handled this by adding some code.\r\nI don't know what you actually want, but you want like this code situation?\r\n\r\n![fast](https://github.com/tiangolo/fastapi/assets/19832624/37c7d54a-76ee-4af6-91d1-5a2587a523bc)\r\n\r\nAbove code is with raw string that print to normal string.\r\nAnd also here is my code changed version.\r\n\r\n![fastapi-code](https://github.com/tiangolo/fastapi/assets/19832624/38765c9b-b7d1-44d7-99a9-da2f7a135a05)\r\n\r\nHere is code about I write\r\n\r\n![carbon](https://github.com/tiangolo/fastapi/assets/19832624/abffea39-12bc-49b2-a611-fe92dc0841b1)\r\n\n---\nComment: opened the #11149 pr \r\nused codecs to convert rawstring so that it can be split on \\f\r\n```python\r\n self.description = codecs.decode(self.description, \"unicode_escape\")\r\n```", "source_type": "issue", "path": "issues/10998.json", "symbol": "Raw docstring (leading `r`) defeats form feed `\\f` truncation", "url": "https://github.com/fastapi/fastapi/issues/10998", "start_line": null, "end_line": null} {"id": "issue::10999", "text": "# Issue #10999: OpenAPI Example with multipart/form-data not showing up\nLabels: bug\n### Discussed in https://github.com/tiangolo/fastapi/discussions/10937\r\n\r\n
\r\n\r\nOriginally posted by **SeeRich** January 11, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom typing import Annotated\r\nfrom fastapi import FastAPI, UploadFile, Form, File\r\n\r\n# Run using uvicorn main:app --reload\r\n# Visit: http://127.0.0.1:8000/docs\r\n\r\napp = FastAPI()\r\n\r\n@app.post(\"/form-test\")\r\nasync def form_test(\r\n str_data: Annotated[str, Form(examples=[\"HELLO\"])],\r\n file: Annotated[UploadFile, File()]):\r\n return\r\n```\r\n\r\n\r\n### Description\r\n\r\nThe `HELLO` example is not shown in the docs.\r\n\r\n![fastapi](https://github.com/tiangolo/fastapi/assets/33664011/6b4deec4-c7bf-4d43-970c-25b30eacc376)\r\n\r\n\r\n### Operating System\r\n\r\nWindows\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.108.0\r\n\r\n### Pydantic Version\r\n\r\n2.5.3\r\n\r\n### Python Version\r\n\r\n3.11.3\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: > @Kludex Alias in `File(alias=\"someAlias\")` doesn't seem to work either, just ran into this in my codebase 🤔\r\n\r\n- https://github.com/tiangolo/fastapi/issues/10286\n---\nComment: Using `json_schema_extra` works as expected:\r\n```py\r\nfrom typing import Annotated\r\nfrom fastapi import FastAPI, UploadFile, Form, File\r\n\r\n# Run using uvicorn main:app --reload\r\n# Visit: http://127.0.0.1:8000/docs\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.post(\"/form-test\")\r\nasync def form_test(\r\n str_data: Annotated[str, Form(json_schema_extra={\"example\": \"test\"})],\r\n file: Annotated[UploadFile, File()],\r\n):\r\n return\r\n```\r\n\r\nBut using only `Form(example=...)` doesn't.\n---\nComment: @Kludex Alias in `File(alias=\"someAlias\")` doesn't seem to work either, just ran into this in my codebase 🤔 ", "source_type": "issue", "path": "issues/10999.json", "symbol": "OpenAPI Example with multipart/form-data not showing up", "url": "https://github.com/fastapi/fastapi/issues/10999", "start_line": null, "end_line": null} {"id": "issue::11037", "text": "# Issue #11037: [BUG] Using Nested Pydantic models and `params: MyModel = Depends()` forces OpenAPI docs GET methods to require a request body.\n### First check\r\n\r\n* [x] I added a very descriptive title to this issue.\r\n* [x] I used the GitHub search to find a similar issue and didn't find it.\r\n* [ ] I searched the FastAPI documentation, with the integrated search.\r\n * Not familiar with the \"integrated search\".\r\n* [x] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n* [x] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n* [x] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n* [x] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n* [x] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n* [x] After submitting this, I commit to:\r\n * Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.\r\n * Or, I already hit the \"watch\" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.\r\n * Implement a Pull Request for a confirmed bug.\r\n\r\n### Example\r\n\r\nHere's a self-contained [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with my use case:\r\n\r\n\r\n```Python\r\nfrom fastapi import APIRouter, Depends, FastAPI, Query\r\nfrom fastapi.responses import JSONResponse\r\nfrom typing import List, Optional\r\nfrom pydantic import BaseModel, Field\r\nimport uvicorn\r\n\r\nclass MyModelData1(BaseModel):\r\n archive: Optional[str] = Field(None, description=\"Archive name\")\r\n archive_type: Optional[str] = Field(None, description=\"Archive type\")\r\n\r\nclass MetadataGet(BaseModel):\r\n id: Optional[str] = Field(None, alias=\"_id\")\r\n foreign_key: Optional[str] = Field(None, alias=\"_foreign_key\")\r\n\r\nclass DeepNestedModelGet(BaseModel):\r\n name: Optional[str]\r\n version: Optional[str]\r\n\r\nclass DetailsModelGet(BaseModel):\r\n some_data: Optional[List[Optional[DeepNestedModelGet]]]\r\n some_data2: Optional[List[Optional[str]]]\r\n\r\nclass MyModelData2(BaseModel):\r\n id: Optional[str] = Field(None, alias=\"_id\")\r\n details: Optional[DetailsModelGet]\r\n meta: Optional[MetadataGet]\r\n\r\ndef get_documents(collection, sort_by, sort_order, page, page_size, **additional_filters):\r\n return {\r\n \"collection\": collection,\r\n }\r\n\r\napp = FastAPI()\r\nrouter1 = APIRouter(prefix=\"/data1\", tags=[\"Data1\"])\r\nrouter2 = APIRouter(prefix=\"/data2\", tags=[\"Data2\"])\r\n\r\n@router1.get(\"/\", description=\"Retrieve all documents.\")\r\ndef get_data1(\r\n sort_by: str = Query(None, description=\"Sort by this field\"),\r\n sort_order: str = Query(None, description=\"Sort order\"),\r\n page: int = Query(1, description=\"Page number\"),\r\n page_size: int = Query(100, description=\"Number of documents per page\"),\r\n params: MyModelData1 = Depends(),\r\n):\r\n document = get_documents(\r\n \"data1\",\r\n sort_by,\r\n sort_orde\n---\nComment: Since this comes up so often (judging by the number of issues and discussions), maybe it would be good to explicitly mention in the [Query Parameters docs](https://fastapi.tiangolo.com/tutorial/query-params/) that using Pydantic models is not yet supported?\n---\nComment: **Update:** As of https://github.com/fastapi/fastapi/releases/tag/0.115.0 what I wrote below is no longer the case.\r\n\r\n---\r\n\r\nI believe using Pydantic models for GET params is not officially supported, and whatever of it works is only the case by accident. Using nested Pydantic models to define GET params is particularly problematic; there are many mentions of this if you search the issues and discussions. See [this comment](https://github.com/tiangolo/fastapi/discussions/9709#discussioncomment-6640931) by @tiangolo.\r\n\r\nThe [roadmap](https://github.com/tiangolo/fastapi/issues/10370#issue-1922795955) has plans for official support:\r\n> Support for Pydantic models for Query(), Form(), etc.\r\n\r\nhttps://github.com/tiangolo/fastapi/discussions/10556#discussioncomment-7429554\r\nhttps://github.com/tiangolo/fastapi/issues/318#issuecomment-584087181\n---\nComment: @TrevorBenson \r\n\r\nHere is a way to think about what you are trying to do in your code and what the workaround might look like:\r\nIt is important to understand that you are **not**\r\nspecifying a pydantic model as an HTTP query parameter here: Your backend function is receiving a Pydantic model as an \r\nargument that was generated via a dependency injection. \r\n\r\nIt's important to keep the concepts of \"query parameters\" and \"results of a dependency injection function\" separate \r\nin your head: Query parameters at the HTTP level can only be types allowed by OpenAPI which is the specification underneath FastAPI. Dependency injection, on the other hand, can create whatever complicated object you want. \r\n\r\nWhat's happening here is the default dependency injection function is not doing what you expected for deeply nested \r\nmodels. What is that dependency function doing? It's basically just looking at the type hint and seeing what fields the constructor needs \r\nand pulling them out of the HTTP", "source_type": "issue", "path": "issues/11037.json", "symbol": "[BUG] Using Nested Pydantic models and `params: MyModel = Depends()` forces OpenAPI docs GET methods to require a request body.", "url": "https://github.com/fastapi/fastapi/issues/11037", "start_line": null, "end_line": null} {"id": "issue::11134", "text": "# Issue #11134: Use `RootModel` as query parameter\nLabels: question\n### Discussed in https://github.com/tiangolo/fastapi/discussions/11101\r\n\r\n
\r\n\r\nOriginally posted by **WarpedPixel** February 6, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\n# fail.py\r\n# uvicorn fail:app --reload\r\n\r\nfrom fastapi import FastAPI\r\nfrom pydantic import RootModel\r\n\r\nSimpleID = RootModel[str]\r\n\r\napp = FastAPI()\r\n\r\n@app.get(\"/test1\")\r\nasync def t1(param1: SimpleID): # BUG: expected to be query param, but it is body\r\n return {\"message\": f\"Hello {param1}\"}\r\n\r\n# @app.get(\"/test2\")\r\n# async def t2(param1: Annotated[SimpleID, Query()]): # this workaround does NOT work\r\n# return {\"message\": f\"Hello {param1}\"}\r\n\r\n@app.get(\"/test3\")\r\nasync def t3(param1: SimpleID, param2: str): # param2 is query param as expected, param1 is NOT\r\n return {\"message\": f\"Hello {param1} {param2}\"}\r\n```\r\n\r\n\r\n### Description\r\n\r\nSimple types should be usable as query params. Pydantic provides `RootModel` (instead of `BaseModel`) precisely to implement types with rich validation based on native types like `list` or `str` (instead of the more typical object/dict). Types built with `RootModel` do not seem to work as query params, *even if it is functionally equivalent* to a simple type like `str`.\r\nFurthermore, we cannot force them to work as query params with `Query()` annotations either.\r\n**NOTE:** the example is overly simplified, my RootModel-derived types do much more in terms of validation.\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.108.0\r\n\r\n### Pydantic Version\r\n\r\n2.5.3\r\n\r\n### Python Version\r\n\r\nPython 3.11.4\r\n\r\n### Additional Context\r\n\r\nI am not sure this is possible, but I would like for FastAPI to understand RootModel derived types, if the root type is one of the types that can be used as query param, then it should work as such.\r\nThe workaround in my case is to use `str` parameters in my FastAPI calls then manually convert to the rich Pydantic type that does validation. Which kind of defeats the purpose of FastAPI rich type annotations.
\n---\nComment: Stumbled upon this today, I was quite surprised this is not possible, this feels very FastAPI-like 😄 Is this feature difficult to implement?\r\n\r\nI get the feeling that running validations on such query fields can be problematic. That's was btw my primary motivation to do this.\r\n\r\nJust to provide another example, this is my use-case I wanted to originally implement. The idea was to have consistent validator for this type, and to have convenience methods on top of this value.\r\n\r\n```python\r\nclass BoundingBox(RootModel[str]):\r\n root: str = Field(pattern=BBOX_REGEX)\r\n\r\n def expand_values(self):\r\n ...\r\n\r\n @root_validator\r\n def validate_number_ranges(cls, value):\r\n ...\r\n\r\n@router.get(\"/\")\r\ndef foo(\r\n bbox: BoundingBox | None,\r\n):\r\n exapnded_values = bbox.expand_values()\r\n```\n---\nComment: @Kludex, @marianhlavac adding support is easy so I did it here: https://github.com/tiangolo/fastapi/pull/11306\n---\nComment: These two alternative implementations also work: \r\n\r\nBoth alternatives require you to declare the parameter as it's \"root\" type. \r\n\r\nValidation option 1 constructs the class (forcing the validators to run) then returns just the root portion.\r\nValidation option 2 just validates the input with a simple function.\r\n\r\n```python\r\nfrom fastapi import FastAPI\r\nfrom pydantic import RootModel, AfterValidator, model_validator\r\nfrom typing import Annotated\r\n\r\nclass SimpleID(RootModel[str]):\r\n # Simulate work to validate the string here\r\n @model_validator(mode='after')\r\n @classmethod\r\n def check_my_string(cls, data: str):\r\n print(f\"Validation of {data} passed!\")\r\n return data\r\n\r\ndef string_checker(data: str) -> str:\r\n print(f\"Validation of {data} passed!\")\r\n return data\r\n\r\n\r\napp = FastAPI()\r\n\r\n@app.get(\"/test1\")\r\nasync def t1(param1: Annotated[str, AfterValidator(lambda v: SimpleID(v).root)]):\r\n return {\"message\": f\"Hello {param1}\"}\r\n \r\n@app.get(\"/test2\")\r\nasyn", "source_type": "issue", "path": "issues/11134.json", "symbol": "Use `RootModel` as query parameter", "url": "https://github.com/fastapi/fastapi/issues/11134", "start_line": null, "end_line": null} {"id": "issue::11143", "text": "# Issue #11143: Context managers in `Depends` are broken after 0.106\nLabels: bug\n### Discussed in https://github.com/tiangolo/fastapi/discussions/11107\r\n\r\n
\r\n\r\nOriginally posted by **FeeeeK** February 7, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom fastapi import Depends, FastAPI, Request\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass Session:\r\n def __init__(self):\r\n print(\"creating session\")\r\n\r\n async def __aenter__(self):\r\n print(\"opening session\")\r\n return self\r\n\r\n async def __aexit__(self, exc_type, exc, tb):\r\n print(\"closing session\")\r\n\r\n async def commit(self):\r\n print(\"committing session\")\r\n\r\n async def rollback(self):\r\n print(\"rolling back session\")\r\n\r\n\r\n@app.middleware(\"http\")\r\nasync def commit_session(request: Request, call_next):\r\n # minimalistic middleware for example, my code uses ASGI middleware\r\n response = await call_next(request)\r\n db_session = request.scope.get(\"db_session\")\r\n if not db_session:\r\n return response\r\n\r\n if response.status_code // 200 != 1:\r\n await db_session.rollback()\r\n else:\r\n await db_session.commit()\r\n\r\n return response\r\n\r\n\r\nasync def get_db_session(request: Request):\r\n async with Session() as session:\r\n request.scope[\"db_session\"] = session\r\n yield session\r\n\r\n\r\n@app.get(\"/\")\r\nasync def root(session: Session = Depends(get_db_session)):\r\n return {\"message\": \"Hello World\"}\r\n\r\n\r\n# Pre 0.106 behaviour:\r\n\r\n# creating session\r\n# opening session\r\n# committing session\r\n# closing session\r\n\r\n# Post 0.106 behaviour:\r\n# creating session\r\n# opening session\r\n# closing session\r\n# committing session\r\n\r\n# The session is not committed, because it's closed before the middleware is called.\r\n```\r\n\r\n\r\n### Description\r\n\r\nBefore `0.106`, Depends execution after yield was after middlewares, which allowed to access resources created for a route (e.g. sessions) and do something with them depending on the response (which cannot be done with Depends), but after 0.106, the behavior has changed and this feature is no longer available. The documentation only talks about background tasks, but not a word about middlewares. Was this behavior change intentional?\r\n\r\n### Operating Syst\n---\nComment: > I think Depends should accept a flag where you can specify when the dependency should be closed, before or after the response.\n> \n> Closing before is useful if you want to raise HTTPExceptions from the cleanup step of your dependencies. Not something I've ever done but maybe if I was just getting started with FastAPI and and learning about that feature, I would find it useful.\n> \n> Closing after is useful with streamsresponses, if you need the dependencies in background tasks, or when you want to perform slowish operations in the cleanup to be able to send the response faster.\n\nand since this was a breaking change, I'd make it \"after\" by default for backwards compatibility.\n\nI'm personally still locked to .105 and missing security updates cause of this.\n---\nComment: I think Depends should accept a flag where you can specify when the dependency should be closed, before or after the response.\r\n\r\nClosing before is useful if you want to raise HTTPExceptions from the cleanup step of your dependencies. Not something I've ever done but maybe if I was just getting started with FastAPI and and learning about that feature, I would find it useful.\r\n\r\nClosing after is useful with streamsresponses, if you need the dependencies in background tasks, or when you want to perform slowish operations in the cleanup to be able to send the response faster.\n---\nComment: I [commented](https://github.com/tiangolo/fastapi/discussions/11107#discussioncomment-8459459) in the Discussion that `StreamingResponse`'s no longer work with `Depends` resources. Since this is a pretty large change in behavior, and wasn't called out in the release notes, I wonder if this is intended. Should this be a separate Issue?", "source_type": "issue", "path": "issues/11143.json", "symbol": "Context managers in `Depends` are broken after 0.106", "url": "https://github.com/fastapi/fastapi/issues/11143", "start_line": null, "end_line": null} {"id": "issue::11215", "text": "# Issue #11215: Potential footgun when using custom `Response(background=)` in conjunction with injected `BackgroundTasks` - the custom response overwrites the tasks\nLabels: question\n### Discussed in https://github.com/tiangolo/fastapi/discussions/11214\r\n\r\n
\r\n\r\nOriginally posted by **netanel-haber** February 28, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom fastapi import FastAPI, BackgroundTasks\r\nfrom starlette.responses import Response, BackgroundTask\r\nimport uvicorn\r\n\r\napp = FastAPI()\r\n\r\n@app.get(\"/\")\r\nasync def endpoint(tasks: BackgroundTasks):\r\n tasks.add_task(lambda: print(\"This won't be printed\"))\r\n return Response(content=\"Custom response\", background=BackgroundTask(lambda: print(\"Only this will be printed\")))\r\n\r\nuvicorn.run(app)\r\n```\r\n\r\n\r\n### Description\r\n\r\nHey! Thanks for the best framework in Python and generally ❤️ \r\n\r\nBasically, passing a background task to a custom response overwrites any other tasks added to the injected `BackgroundTasks`.\r\n\r\nI'm not sure this is considered a bug, but I think it's confusing and can at least be clarified in the [Return a Response Directly](https://fastapi.tiangolo.com/advanced/response-directly/) docs, for example. Other solutions can be actually changing this behavior (I guess that's a breaking change), or printing a warning/throwing [throwing is also a breaking change] if both mechanisms are used at once. But I can't imagine a user desiring this behavior. To be clear, this tripped us up when we couldn't figure out why some of our tasks were being swallowed. \r\n\r\nI'd be happy to work on either solution, obviously adding a docs pr would be the easiest first step.\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.97.0\r\n\r\n### Pydantic Version\r\n\r\n1.10.7\r\n\r\n### Python Version\r\n\r\n3.9\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: I've created the issue because I think we can do better than just ignoring those background tasks. Maybe we can add them to the returned `Response` object?\n---\nComment: That's what I alluded to when I mentioned:\n\n> ...actually changing this behavior\n\nMeaning, somehow making it so both the injected tasks, and the passed background are executed as expected. For example, is it possible to append thebackground task to the injected tasks? Does FastAPI/Starlette provide a way to get the injections for a given request? Is that available to the Response class (and inheritors like StreamingResponse)?\n\nThis is a breaking change because existing apps might find that behavior suddenly changes (=tasks that weren't running before due to this overwrite suddenly run) - like I mentioned, this \"breaking change\" is really fixing a behavior that doesn't really make sense. But it kind of depends on the repo's policy, I think.\n\nI'd be happy to contribute a pr for this, either way.\n---\nComment: Adding this because it seems related. It is certainly a source of an incredibly obscure bug that had me scratching my head for days. There's nothing in FastAPI that stops you caching a frequently used `Response` in a variable:\r\n```python\r\nRESPONSE = HTMLResponse('ok')\r\n```\r\nIf you return such a response from an endpoint that adds a background task you get a very obscure bug. This particular task takes a string argument. The first time you call the endpoint everything seems ok. The second time you call it, the background task is invoked with the same argument value as first time. I presume this is because of the same smoke and mirrors noted by @netanel-haber, whereby the `Response` is actually used to stash the background task context.\r\n\r\nHere's a fully worked example:\r\n\r\n```python\r\n# wtest.py\r\nimport uvicorn\r\nfrom fastapi import FastAPI, BackgroundTasks\r\nfrom fastapi.responses import HTMLResponse\r\nimport random\r\nimport string\r\n\r\nRESPONSE = HTMLResponse('ok')\r\n\r\napp = FastAPI()\r\n\r\ndef r", "source_type": "issue", "path": "issues/11215.json", "symbol": "Potential footgun when using custom `Response(background=)` in conjunction with injected `BackgroundTasks` - the custom response overwrites the tasks", "url": "https://github.com/fastapi/fastapi/issues/11215", "start_line": null, "end_line": null} {"id": "issue::11251", "text": "# Issue #11251: Breaking change with path parameters when updating to pydantic>=2 from pydantic<2\nLabels: question\n### Discussed in https://github.com/tiangolo/fastapi/discussions/11250\r\n\r\n
\r\n\r\nOriginally posted by **ThirVondukr** March 5, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom uuid import UUID\r\n\r\nfrom fastapi import FastAPI\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/int/{path}\")\r\nasync def int_(path: int | str):\r\n return str(type(path))\r\n\r\n\r\n@app.get(\"/uuid/{path}\")\r\nasync def uuid_(path: UUID | str):\r\n return str(type(path))\r\n```\r\n\r\n\r\n### Description\r\n\r\nWith pydantic<2 parameters are correctly parsed as int and UUID if an appropriate string is passed, with pydantic 2 they're always interpreted as str, I presume this will work the same way with all other types that you can pass into path parameters.\r\nI also observed the same behavior with query, so I assume it behaves the same way with all FastAPI parameters (headers, body, etc).\r\n\r\n### Operating System\r\n\r\nWindows\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.110.0\r\n\r\n### Pydantic Version\r\n\r\n1.10.14 / 2.6.3\r\n\r\n### Python Version\r\n\r\nPython 3.11.5\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: A workaround for anyone facing this (NB: this assumes availability of typing.Annotated and pydantic.Field):\r\n```diff\r\n@app.get(\"/uuid/{path}\")\r\n-async def uuid_(path: UUID | str):\r\n+async def uuid_(path: Annotated[UUID | str, Field(union_mode='left_to_right')]):\r\n return str(type(path))\r\n```\r\n\r\nPydantic v2 switched to union_mode='smart' as the default, which in cases like this will always prefer str (since it's an exact type match).\r\n\r\nIt's also necessary to do this in any dependencies (as far as I can tell, type annotations set on direct path parameters and function parameters of dependencies aren't shared).\n---\nComment: Based on the GitHub issue, the problem is:\n\nIn Pydantic v1 (version 1.10.14 mentioned in the details), path parameters with type annotations like int and UUID would correctly parse string inputs into those types when passed through URL paths.\nAfter upgrading to Pydantic v2 (version 2.6.3), all path parameters are always interpreted as strings, regardless of the type annotation.\n\nLooking at the example code:\n\n`@app.get(\"/int/{path}\")\nasync def int_(path: int | str):\n return str(type(path))\n\n@app.get(\"/uuid/{path}\")\nasync def uuid_(path: UUID | str):\n return str(type(path))`\n\nWith Pydantic v1, if you called /int/123, the path parameter would be parsed as an integer. With Pydantic v2, it's always a string.\nThis is indeed a breaking change that affects type validation and conversion in FastAPI applications. The issue reporter suspects this behavior applies to all FastAPI parameters (path, query, headers, body, etc.).\nThe most direct solution would be to manually convert the types in \n---\nComment: As I see it, we don't need to fix this (that would cause even more confusion, and this will be breaking change), but we should add a note about this with a [solution suggested by **H-Plus-Time**](https://github.com/fastapi/fastapi/issues/11251#issuecomment-2024267760) to docs.\nProbably [here](https://fastapi.tiangolo.com/python-types/#union), but maybe better add a dedicated _\"Input parameters type validation\"_ section in Tutorial (I guess there are other specific cases we can describe there as well)", "source_type": "issue", "path": "issues/11251.json", "symbol": "Breaking change with path parameters when updating to pydantic>=2 from pydantic<2", "url": "https://github.com/fastapi/fastapi/issues/11251", "start_line": null, "end_line": null} {"id": "issue::1131", "text": "# Issue #1131: Include documentation for other types of security\nLabels: feature, investigate, reviewed\nDocs Link: https://fastapi.tiangolo.com/tutorial/security/\r\n\r\nWe have explained in detail about OAuth2 with password. However, there are no documentation links about other types like APIKeyHeader, HTTPHeader, etc. There is a very hidden mention https://fastapi.tiangolo.com/tutorial/security/#fastapi-utilities about the existence of other module. It took me a lot of time to find this. I feel it would be time-saving if we were to include these in the documentation itself.\r\n\r\nAlso, I feel that we should give option to add a global custom checking tool for security types, like the way `@app.middleware` does for wrapping custom logic. Currently, we can only check with tokenUrls, authenticationUrls, or defining custom functions that have to then be added as a dependency.\r\n\r\nSomething like this:\r\n```py\r\nauth_token = HTTPBearer(auto_error=False)\r\n@app.check_security(auth_token)\r\ndef check_token(token):\r\n # Include code to check the token\r\n pass\r\n```\r\n\r\nThanks!! 😄 \n---\nComment: Hi @tiangolo,\r\n\r\nI am interested in working on this issue. Please assign this to me. Thanks!\n---\nComment: Hi,\n\nThank you for raising this — I completely agree with the points mentioned. The limited visibility of other authentication classes like `HTTPBearer`, `APIKeyHeader`, and `APIKeyQuery` in the documentation can make onboarding and discovery a bit challenging. Also, the idea of a global security handler similar to `@app.middleware` is quite valuable.\n\nI'd love to take this issue forward and contribute to:\n1. Enhancing the documentation for the lesser-known security utilities (`HTTPBearer`, `APIKeyHeader`, etc.), with clear examples and links.\n2. Exploring potential implementation (or at least a proposed pattern) for a `@check_security`-like approach, or officially recommending a best practice using `APIRouter(dependencies=[...])` for global security application.\n\nLet me know if this direction aligns with your vision. If yes, I can begin working on a draft and open a PR soon.\n\nThanks again!\n– Sagar Ahire\n\n---\nComment: I intend to add more docs about security, I'm tracking that internally.\n\nAbout the decorator with `check_security`, it would be equivalent to the `dependencies=[]` parameter, so I wouldn't think it's necessary.\n\n---\n\nHaving issues open for specific things is becoming problematic as they attract AI slop PRs, so I'm closing this for cleanup. ☕ ", "source_type": "issue", "path": "issues/1131.json", "symbol": "Include documentation for other types of security", "url": "https://github.com/fastapi/fastapi/issues/1131", "start_line": null, "end_line": null} {"id": "issue::11573", "text": "# Issue #11573: fastapi dev runs stuck\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nThe first time I ran fastapi dev, there was no problem, but I encountered a code error. Then after I modified the code and saved it, a WARNING: WatchFiles detected changes in 'tool/index.py'. Reloading... then got stuck and could not exit.\r\n\r\n\"image\"\r\n\n---\nComment: do not use the fastapi dev to run your application just use uvicorn instead, i do not face any issue with uvicorn \n---\nComment: can confirm. win 11. \r\nissue present at least month. \r\n\r\n```WARNING: WatchFiles detected changes in 'config.py'. Reloading...``` and its stuck. \r\nIts works fine until certain moment but hard to debug when exactly. after kill and start new it can stuck again.\r\n\r\nNo pycharm, vscode + .venv, server started by hand in terminal (❯ fastapi dev webserver.py --port 8080)\r\n\r\nUPDATE:\r\n\r\n> do not use the fastapi dev to run your application just use uvicorn instead, i do not face any issue with uvicorn\r\n\r\nrelating to the comments, this doesnt look to help aswell. \r\n![image](https://github.com/user-attachments/assets/da8d07e1-cb27-4e33-babc-3a99c1c237c6)\r\n\n---\nComment: I'm having the same issue here on windows 10. \r\nI think this is related: https://www.reddit.com/r/FastAPI/comments/13oynf6/keeps_old_routes_after_changing_cache_problem/\r\n\r\nIt is like fastapi keeps an old version of the code cached somewhere. Even if I force kill fastpi and restart it, it loads an old version of my code.\r\n\r\nIt works (for a while) if I change port.\r\n\r\nedit: this seems to be a uvicorn [open issue](https://github.com/encode/uvicorn/issues/1972) which in turn is caused by a bug in cpython ([open issue](https://github.com/python/cpython/issues/80116))", "source_type": "issue", "path": "issues/11573.json", "symbol": "fastapi dev runs stuck", "url": "https://github.com/fastapi/fastapi/issues/11573", "start_line": null, "end_line": null} {"id": "issue::11580", "text": "# Issue #11580: Query fields with numeric types appear not to enforce allow_inf_nan=False, whereas gt=0, etc are enforced\nLabels: bug\n### Discussed in https://github.com/tiangolo/fastapi/discussions/11577\r\n\r\n
\r\n\r\nOriginally posted by **pat-lasswell** May 14, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nimport aiohttp\r\nimport asyncio\r\nimport math\r\nimport uvicorn\r\n\r\nfrom fastapi import FastAPI, Query, Request, Response\r\nfrom http import HTTPStatus\r\nfrom typing import Annotated\r\n\r\napp = FastAPI()\r\n\r\n@app.get('/')\r\nasync def get(\r\n x: Annotated[float | None, Query(gt=0, description='x')] = 1,\r\n y: Annotated[float | None, Query(allow_inf_nan=False, description='y')] = 0) -> str:\r\n\r\n assert x > 0\r\n assert not math.isnan(y) and not math.isinf(y)\r\n\r\n return 'OK'\r\n\r\n\r\nasync def main():\r\n\r\n config = uvicorn.Config(app, host='127.0.0.1', port=8001)\r\n server = uvicorn.Server(config)\r\n task = asyncio.create_task(server.serve())\r\n \r\n await asyncio.sleep(.1)\r\n\r\n async with aiohttp.ClientSession() as session:\r\n\r\n async with session.get('http://127.0.0.1:8001/?x=-1') as response:\r\n\r\n assert response.status == HTTPStatus.UNPROCESSABLE_ENTITY\r\n \r\n async with session.get('http://127.0.0.1:8001/?y=inf') as response:\r\n\r\n assert response.status == HTTPStatus.UNPROCESSABLE_ENTITY\r\n \r\n await server.shutdown()\r\n\r\nif __name__ == '__main__':\r\n asyncio.get_event_loop().run_until_complete(main())\r\n```\r\n\r\n\r\n### Description\r\n\r\nI would expect the `allow_inf_nan` parameter to `Query` to restrict valid values in the same way that `gt`, etc do, resulting in a HTTP 422 status code when the constraint is violated. Instead, `inf` and `nan` values are passed to the route handler. \r\n\r\nTo reproduce, save the example code above in the current directory in a file named `bug.py`, then \r\n \r\n docker run -it --rm -w `pwd` -v `pwd`:`pwd` python:3.10 bash\r\n\r\nand in the bash prompt inside the container \r\n\r\n pip install aiohttp==3.9.5 fastapi==0.111.0 uvicorn==0.29.0\r\n python bug.py\r\n\r\nThe output will be similar to \r\n\r\n INFO: Started server process [4301]\r\n INFO: Waiting for application startup.\r\n INFO: Application startup complete.\r\n INFO: Uvicorn runni\n---\nComment: I made a PR for that at #11867\r\nThere was a little typo I suppose when passing the parameters to the pydantic object\n---\nComment: This should be solved by https://github.com/fastapi/fastapi/pull/11867, the fix will be available in FastAPI `0.112.2` released in the next few hours. :tada: ", "source_type": "issue", "path": "issues/11580.json", "symbol": "Query fields with numeric types appear not to enforce allow_inf_nan=False, whereas gt=0, etc are enforced", "url": "https://github.com/fastapi/fastapi/issues/11580", "start_line": null, "end_line": null} {"id": "issue::11812", "text": "# Issue #11812: I have many routes that need to use \"page\" and \"page_size\". Is there a solution with class inheritance for Query ?\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nI have many routes that need to use \"page\" and \"page_size\". Is there a solution with class inheritance for Query ?", "source_type": "issue", "path": "issues/11812.json", "symbol": "I have many routes that need to use \"page\" and \"page_size\". Is there a solution with class inheritance for Query ?", "url": "https://github.com/fastapi/fastapi/issues/11812", "start_line": null, "end_line": null} {"id": "issue::11873", "text": "# Issue #11873: fastapi nonsupport python 3.12 ? \n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nfastapi nonsupport python 3.12 ? \n---\nComment: FastAPI supports Python 3.12.", "source_type": "issue", "path": "issues/11873.json", "symbol": "fastapi nonsupport python 3.12 ? ", "url": "https://github.com/fastapi/fastapi/issues/11873", "start_line": null, "end_line": null} {"id": "issue::11892", "text": "# Issue #11892: How to distinguish None value sent by user and default None value for an optional argument in a API\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nI have a API with 3 arguments, one of them is Optional with default value as None.\r\nWhen user send a post request without this argument -> ok, continue to process this argument with None value.\r\nBut when user send None value for this argument, I want to detect and return error\n---\nComment: I'm not sure I understand what you're asking. Do you have three different pydantic-models as input arguments? Do you have one pydantic-model with three properties? Or do you have three query-parameters?\r\n\r\nThe following (using the \"arguments\" as query parameters) works as you expect:\r\n\r\n```python\r\nfrom fastapi import APIRouter, FastAPI\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.post(\"/hello\")\r\nasync def hello_world(a: int, b: int, c: int | None = None) -> dict[str, str]:\r\n return {\r\n \"message\": f\"Hello, World! The sum of {a} and {b} is {a + b}, {c} is optional\"\r\n }\r\n```\n---\nComment: If you instead wanted to prevent the user from inputting \"none\" into the body of a post-request, you can do it this way (note, that this is not a FastAPI issue, but a validation-constraint):\r\n\r\n```python\r\nimport pydantic\r\nfrom fastapi import APIRouter, FastAPI\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass Test(pydantic.BaseModel):\r\n a: int\r\n b: int\r\n c: int | None = None\r\n\r\n @pydantic.field_validator(\"c\", mode=\"before\")\r\n @classmethod\r\n def test_input(cls, v: int | None) -> int | None:\r\n if v is None:\r\n raise ValueError(\"You're not allowed to input None\")\r\n return v\r\n\r\n\r\n@app.post(\"/hello\")\r\nasync def hello_world(test: Test) -> dict[str, str]:\r\n return {\r\n \"message\": f\"Hello, World! The sum of {test.a} and {test.b} is {test.a + test.b}, {test.c} is optional\"\r\n }\r\n```\n---\nComment: You should move your question to the discussion area. This space is for tracking issues. There will be more people paying attention to your question there.", "source_type": "issue", "path": "issues/11892.json", "symbol": "How to distinguish None value sent by user and default None value for an optional argument in a API", "url": "https://github.com/fastapi/fastapi/issues/11892", "start_line": null, "end_line": null} {"id": "issue::11941", "text": "# Issue #11941: thanks for the effoer\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nthanks", "source_type": "issue", "path": "issues/11941.json", "symbol": "thanks for the effoer", "url": "https://github.com/fastapi/fastapi/issues/11941", "start_line": null, "end_line": null} {"id": "issue::11989", "text": "# Issue #11989: ASGI Error\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n Error loading ASGI app. Could not import module \"main\".", "source_type": "issue", "path": "issues/11989.json", "symbol": "ASGI Error", "url": "https://github.com/fastapi/fastapi/issues/11989", "start_line": null, "end_line": null} {"id": "issue::11993", "text": "# Issue #11993: Using fast API's multi-value Query parameters, but only receiving the last value\nI followed the method in the document (https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values-with-defaults)and the parameters of the interface list, but the data obtained is always only the last data. \r\nlike this:\r\nlocalhost:8000/path/getList?q=Value1&q=Value2\r\n\r\n@router.get(\"/path/getList\")\r\nasync def get_list(\r\n command: Union[list[str], None] = Query(default=None)\r\n):\r\n for item in command:\r\n print(item)\r\n\r\nconsole only log one data: Value2, Is there any way to troubleshoot?\n---\nComment: Please create a discussion.", "source_type": "issue", "path": "issues/11993.json", "symbol": "Using fast API's multi-value Query parameters, but only receiving the last value", "url": "https://github.com/fastapi/fastapi/issues/11993", "start_line": null, "end_line": null} {"id": "issue::12010", "text": "# Issue #12010: Problem where scheduled tasks will be executed repeatedly when starting with multiple workders\n### Privileged issue\r\n\r\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\ni use this command to start my application \r\n`\r\nnohup uvicorn app:app --host 0.0.0.0 --port 8000 --workers 5 > ../app.log 2>&1 &`\r\nmy task code \r\n`async def my_task():\r\n do some curd code \r\n\r\ntrigger = CronTrigger(hour=18, minute=35)\r\n\r\nscheduler.add_job(my_task, trigger)\r\n\r\nscheduler.start()\r\n`\r\n\r\nThis task will be executed repeatedly, resulting in duplicate data\r\n", "source_type": "issue", "path": "issues/12010.json", "symbol": "Problem where scheduled tasks will be executed repeatedly when starting with multiple workders", "url": "https://github.com/fastapi/fastapi/issues/12010", "start_line": null, "end_line": null} {"id": "issue::12017", "text": "# Issue #12017: 👷🏻 Recently, the CI is failing due to docs building failures\nLabels: bug, internal\n### Discussed in https://github.com/fastapi/fastapi/discussions/12011\r\n\r\n
\r\n\r\nOriginally posted by **svlandeg** August 14, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Description\r\n\r\nRecently, PRs have started failing the CI due to failing some of the document building checks. It looks like a regression may have been introduced on `master` causing this.\r\n\r\nExample PRs that failed today:\r\n * https://github.com/fastapi/fastapi/pull/11876\r\n * https://github.com/fastapi/fastapi/pull/11515\r\n\r\nThe error is caused by the following error:\r\n```\r\nNo such file or directory: '/home/runner/work/fastapi/fastapi/docs/de/docs/img/icon-white.svg'\r\n```\r\n\r\nAnd the same thing in other languages:\r\n```\r\nNo such file or directory: '/home/runner/work/fastapi/fastapi/docs/bn/docs/img/icon-white.svg'\r\n```\r\n
\n---\nComment: This was handled in https://github.com/fastapi/fastapi/pull/12016 :rocket: ", "source_type": "issue", "path": "issues/12017.json", "symbol": "👷🏻 Recently, the CI is failing due to docs building failures", "url": "https://github.com/fastapi/fastapi/issues/12017", "start_line": null, "end_line": null} {"id": "issue::12039", "text": "# Issue #12039: FastAPI does not allow to send a \"None\" UploadFile\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nI have a POST method with FastAPI which has 2 params with UploadFile type. But one of them is required and one of them is Optional. When I send required param with None value, I got 422 error relating to \"Field required\". But if I send Optional param with None value, it's acceptable.\r\nWhen I use:\r\nfrom fastapi import Request\r\nAnd add:\r\nrequest: Request as extra param, then log request.form(), I don't see Optional param.\r\nIt seems to FastAPI ignored it?\r\n\r\nMy code is below:\r\nfrom fastapi import File, Request, UploadFile\r\nfrom typing import Annatoted\r\n\r\napp: FastAPI = FastAPI()\r\n\r\n@app.post(/test)\r\nasync def test(\r\n request: Request,\r\n firstFile: Annatoted[UploadFile, File(...)],\r\n secondFile: Annatoted[UploadFile | None, File(...)] = None):\r\n logger.debug(await request.form())", "source_type": "issue", "path": "issues/12039.json", "symbol": "FastAPI does not allow to send a \"None\" UploadFile", "url": "https://github.com/fastapi/fastapi/issues/12039", "start_line": null, "end_line": null} {"id": "issue::1204", "text": "# Issue #1204: Class based dependencies with __call__ don't work with yield\nLabels: bug, answered, reviewed\n### Describe the bug\r\n\r\nClass based callable dependencies (https://fastapi.tiangolo.com/advanced/advanced-dependencies/) don't work when used as generators with yield keyword.\r\n\r\n### To Reproduce\r\n\r\n```Python\r\nclass SessionScope:\r\n\r\n def __init__(self, uri):\r\n self.engine = create_engine(uri)\r\n self.session_maker = scoped_session(sessionmaker(bind=self.engine))\r\n\r\n def __call__(self):\r\n session = self.session_maker()\r\n try:\r\n yield session\r\n except:\r\n session.rollback()\r\n raise\r\n finally:\r\n self.session_maker.remove()\r\n\r\nget_db = SessionScope('postgresql://postgres:mypass@127.0.0.1:5432/my_db')\r\n\r\n@router.get('/', response_model=List[User])\r\ndef read_users(\r\n db: Session = Depends(get_db),\r\n skip: int = 0,\r\n limit: int = 100,\r\n):\r\n \"\"\"\r\n Retrieve users.\r\n \"\"\"\r\n users = crud.user.get_multi(db, skip=skip, limit=limit)\r\n return users\r\n```\r\n\r\n### Expected behavior\r\n\r\nDependency must return yielded session, but now it returns \\_\\_call\\_\\_ generator instance\r\n\r\n### Additional context\r\n\r\nThe problem lies in /fastapi/dependencies/utils.py file on line 498:\r\n```Python\r\n elif inspect.isgeneratorfunction(call) or inspect.isasyncgenfunction(call):\r\n stack = request.scope.get(\"fastapi_astack\")\r\n if stack is None:\r\n raise RuntimeError(\r\n async_contextmanager_dependencies_error\r\n ) # pragma: no cover\r\n solved = await solve_generator(\r\n call=call, stack=stack, sub_values=sub_values\r\n )\r\n```\r\nParamter _call_ passed to _inspect.isgeneratorfunction_ is instance of a class instead of it's \\_\\_call\\_\\_ method and this function always returns False. \n---\nComment: Thanks for the discussion here everyone! :coffee: \r\n\r\nThis was solved in https://github.com/tiangolo/fastapi/pull/1365 by @mrosales :heavy_check_mark: :tada: \r\n\r\nIt will be available in version `0.56.1` (in a couple of hours).\n---\nComment: Maybe you will find a better solution, but replacing all calls to _inspect.isgeneratorfunction_ and inspect.isasyncgenfunction_ to:\r\n```Python\r\ndef is_generator_callable(call: Callable) -> bool:\r\n if inspect.ismethod(call.__call__):\r\n call = call.__call__\r\n return inspect.isgeneratorfunction(call)\r\n\r\ndef is_async_generator_callable(call: Callable) -> bool:\r\n if inspect.ismethod(call.__call__):\r\n call = call.__call__\r\n return inspect.isasyncgenfunction(call)\r\n```\r\nreturns correct results.\n---\nComment: Got bitten by this one as well, @neriusmika would you mind making a PR with suggested changes?", "source_type": "issue", "path": "issues/1204.json", "symbol": "Class based dependencies with __call__ don't work with yield", "url": "https://github.com/fastapi/fastapi/issues/1204", "start_line": null, "end_line": null} {"id": "issue::12055", "text": "# Issue #12055: Why can't the key of the returned value start with “_sa”?\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n```\r\nimport uvicorn\r\nfrom fastapi import FastAPI\r\n\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/\")\r\ndef root():\r\n return {\"_sa\": \"Hello World\", \"status\": \"OK\"}\r\n\r\n\r\nif __name__ == '__main__':\r\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\r\n```\r\nThe result of the above code is:\r\n```\r\n{\r\n \"status\": \"OK\"\r\n}\r\n```\n---\nComment: If I'm not mistaken this is not a FastAPI issue, but rather a Pydantic feature.\r\nAccording to [this stackoverflow thread](https://stackoverflow.com/a/75712642) Pydantic V2 considers parameters prefixed with an underscore as \"PrivateAttr\", i.e., private attributes.\n---\nComment: > 如果我没记错的话,这不是 FastAPI 问题,而是 Pydantic 功能。根据[这个 stackoverflow 线程](https://stackoverflow.com/a/75712642),Pydantic V2 将带有下划线前缀的参数视为“PrivateAttr”,即私有属性。\r\n\r\n可以修改以上代码做个实验:\r\n```\r\ndef root():\r\n result = {\"_private\": \"test\", \"_sa\": \"Hello World\", \"status\": \"OK\"}\r\n print(result)\r\n return result\r\n```\r\n我测试的结果是:\r\n```\r\n{\r\n \"_private\": \"test\",\r\n \"status\": \"OK\"\r\n}\r\n```", "source_type": "issue", "path": "issues/12055.json", "symbol": "Why can't the key of the returned value start with “_sa”?", "url": "https://github.com/fastapi/fastapi/issues/12055", "start_line": null, "end_line": null} {"id": "issue::12111", "text": "# Issue #12111: Here is the starter kit for fast api forked original one but only included the backend part it take me so much time to clean up the code and only keep the backend part so i hope it helps you guys \n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n https://github.com/bibektimilsina00/FastAPI-PgStarterKit", "source_type": "issue", "path": "issues/12111.json", "symbol": "Here is the starter kit for fast api forked original one but only included the backend part it take me so much time to clean up the code and only keep the backend part so i hope it helps you guys ", "url": "https://github.com/fastapi/fastapi/issues/12111", "start_line": null, "end_line": null} {"id": "issue::12133", "text": "# Issue #12133: Your upgrade of 113 broken all gradio apps - a fix needed ASAP this is devastating \nLabels: answered\na very basic just gradio having app\r\n\r\nfast api 111 fixes issue\r\n\r\nall of my followers now reporting errors and so hard to fix all\r\n\r\ni don't know how can you publish such a devastating bug having version please fix it ASAP\r\n\r\n\r\n```\r\n2024-09-06 00:12:20,515 - INFO - HTTP Request: GET https://api.gradio.app/gradio-messaging/en \"HTTP/1.1 200 OK\"\r\nRunning on local URL: http://127.0.0.1:7860\r\n2024-09-06 00:12:20,542 - INFO - HTTP Request: GET http://127.0.0.1:7860/startup-events \"HTTP/1.1 200 OK\"\r\n2024-09-06 00:12:20,552 - INFO - HTTP Request: HEAD http://127.0.0.1:7860/ \"HTTP/1.1 200 OK\"\r\n\r\nTo create a public link, set `share=True` in `launch()`.\r\n2024-09-06 00:12:20,673 - INFO - HTTP Request: GET https://checkip.amazonaws.com/ \"HTTP/1.1 200 \"\r\n2024-09-06 00:12:21,337 - INFO - HTTP Request: GET https://api.gradio.app/pkg-version \"HTTP/1.1 200 OK\"\r\nERROR: Exception in ASGI application\r\nTraceback (most recent call last):\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\pydantic\\type_adapter.py\", line 209, in __init__\r\n core_schema = _getattr_no_parents(type, '__pydantic_core_schema__')\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\pydantic\\type_adapter.py\", line 98, in _getattr_no_parents\r\n raise AttributeError(attribute)\r\nAttributeError: __pydantic_core_schema__\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\uvicorn\\protocols\\http\\h11_impl.py\", line 406, in run_asgi\r\n result = await app( # type: ignore[func-returns-value]\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\uvicorn\\middleware\\proxy_headers.py\", line 70, in __call__\r\n return await self.app(scope, receive, send)\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\fastapi\\applications.py\", line 1054, in __call__\r\n await super().__call__(scope, receive, send)\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\starlette\\applications.py\", line 113, in __call__\r\n await self.middleware_stack(scope, receive, send)\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\starlette\\middleware\\errors.py\", line 187, in __call__\r\n raise exc\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\starlette\\middleware\\errors.py\", line 165, in __call__\r\n await self.app(scope, receive, _send)\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\gradio\\route_utils.py\", line 766, in __call__\r\n await self.simple_response(scope, receive, send, request_headers=headers)\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\gradio\\route_utils.py\", line 782, in simple_response\r\n await self.app(scope, receive, send)\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\starlette\\middleware\\exceptions.py\", line 62, in __call__\r\n await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)\r\n File \"R:\\Image_Caption_Editor_v6\\venv\\lib\\site-packages\\starlette\\_exception_handler.py\",\n---\nComment: @FurkanGozukara please share a self-contained [minimal self-contained example](https://stackoverflow.com/help/minimal-reproducible-example) that replicates the issue so that I can copy-paste it, run it, and see your error. I just tried with the getting-started Gradio app, and it all seems to work.\r\n\r\nNow, the right place to start would have been a GitHub Discussion, filling the form, that would have guided you to provide a reproducible example.\r\n\r\nAnd then, please be kind, your post is aggressive and demeaning, this is open source, you get it for free, you are not paying nor contributing anything here, so at least, be kind.\n---\nComment: > I don't know how many open source ai apps you used but there are countless amazing apps made by researchers and not maintained anymore or rarely maintained\r\n\r\n> So becuase of this reason I have to manually fix my installers for 10s of such apps and re-upload them and if I miss it will be broken next time a user uses it\r\n\r\nSure, there are lots of good projects out there. And if they're not maintained and you took on the burden of maintenance for your users, then there are steps you can take to make installs reproducible. Try poetry lockfiles.\r\n\r\nYelling at maintainers of projects that you use isn't productive. Did you just expect the alternative that gradio would pin all dependencies to specific versions so that nothing could ever break? Then you'd have to bug them for a new release every time you need a new version of a dependency 🙃 \r\n\r\n> I have a c# background I hate python because of this. 0 backwards. With Microsoft I can load 12 years old project and it will compile straight in l\n---\nComment: > all apps that uses specific gradio before to 4.43.0 broken right at this moment :/\r\n\r\n@FurkanGozukara There's no need to be dramatic. Installing dependencies is the responsibility of the application, not the libraries it consumes. If you wrote an app and didn't ensure it has reproducible builds, that's on you", "source_type": "issue", "path": "issues/12133.json", "symbol": "Your upgrade of 113 broken all gradio apps - a fix needed ASAP this is devastating ", "url": "https://github.com/fastapi/fastapi/issues/12133", "start_line": null, "end_line": null} {"id": "issue::12198", "text": "# Issue #12198: Some Bugs Regarding File Upload Functionality in FastAPI and Testing with Swagger UI\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nfrom fastapi import FastAPI, UploadFile, File, Form\r\nfrom typing import List, Optional\r\n\r\napp = FastAPI()\r\n\r\n@app.post(\"/upload/\")\r\nasync def upload_files(\r\n required_files: List[UploadFile] = File(...), \r\n optional_files: List[Optional[UploadFile]] = File(None), \r\n string_list: List[str] = Form(...) \r\n):\r\n return \r\n\r\nThis code is an example, but I combined it with Swagger UI and found multiple problems, The following questions are respectively.\r\n1. When the file list is defined as optional, if no optional files are selected in the Swagger UI, the backend code will report an error 422, indicating that the passed parameters cannot be received.\r\n2. form-data type data cannot be passed together with the file type, and the back-end code cannot accept both types of data at the same time.\r\n3. File type cannot be verified in pydantic model, but this does not seem to be a bug.\r\n4. When receiving string types, adding multiple strings in Swagger UI, in the back-end code, using List[str] to receive will treat all strings as a larger string, resulting in only one string in the List. a string.\r\n\r\n\r\n\r\n\n---\nComment: @ShengWei42 ,I have encountered a similar issue. Regarding the 422 error you mentioned, I used your code to create an endpoint. When making a request directly through Swagger, it results in a 422 error. However, when using an API testing tool (I used Apifox) to request this endpoint, it is successful. I did not encounter the issue where multiple strings become one long string. It seems like a frontend Swagger parsing issue. I have also experienced 422 errors with similar endpoints, but there are no issues when not using Swagger. I hope the official team can address this problem when they have time,think.\r\n![image](https://github.com/user-attachments/assets/3c5d6353-916f-49de-be2a-6bff40c7312f)\r\n![image](https://github.com/user-attachments/assets/79082153-c7dc-4694-9f70-48a5c39e16d7)\r\n\r\n![image](https://github.com/user-attachments/assets/4baa847e-5bc6-421e-b39e-63516cfc0838)\r\n\n---\nComment: Hey there, although you checked that box, it seems you're not @tiangolo, and I didn't ask you to create this issue. :sweat_smile: \r\n\r\nSo, please open a GitHub Discussion following all the template step by step. That will allow me or others to properly help you. :coffee: \r\n\r\nGiven that, I'm gonna close this one.\n---\nComment: I hope you can consider the questions I raised carefully, which can help more people.", "source_type": "issue", "path": "issues/12198.json", "symbol": "Some Bugs Regarding File Upload Functionality in FastAPI and Testing with Swagger UI", "url": "https://github.com/fastapi/fastapi/issues/12198", "start_line": null, "end_line": null} {"id": "issue::12239", "text": "# Issue #12239: Sponsor Badge CSS overflow issue on the docs\nLabels: question\n### Discussed in https://github.com/fastapi/fastapi/discussions/12218\r\n\r\n
\r\n\r\nOriginally posted by **nat236919** September 19, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nannounce-wrapper .sponsor-badge {\r\n display: block;\r\n position: absolute;\r\n top: -10px;\r\n right: 0;\r\n font-size: 0.5rem;\r\n color: #999;\r\n background-color: #666;\r\n border-radius: 10px;\r\n padding: 0 10px;\r\n z-index: 10;\r\n}\r\n```\r\n\r\n\r\n### Description\r\n\r\n![image](https://github.com/user-attachments/assets/0b9cc528-d268-4e2f-b073-0988228ebd55)\r\n\r\nDue to its absolute position and overflow setting, the text is trailing down creating an expected scroll. I think we can simply solve the issue by removing **position: absolute;**\r\n\r\n### Operating System\r\n\r\nWindows\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\nNA\r\n\r\n### Pydantic Version\r\n\r\nNA\r\n\r\n### Python Version\r\n\r\nNA\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: Well... Not a big issue... But transferring to issues for team visibility.\n---\nComment: Hi. I was able to replicate the error (I see this is an old issue but it is opened 😅 )\n\"Image\"\nIf an Ad blocker extension is enabled, the banner is blocked/hidden. I see a couple of options\n\n1. Search a way to avoid the blocker \n2. Hide the seccion if the Ad blocker is enabled \n---\nComment: Should we even care about this?\n* As I understand this only happens if (any of):\n * people use AD blockers. They can always add `tiangolo.com` to exceptions and look at our beautifull sponsors, right?\n * the URL of the image is broken - I believe this will be reported and fixed quickly.\n * connection error - this should happen often.\n* This doesn't look aweful. I believe people who are using AD blockers are tolerant to such things\n* People who are using AD-blockers can just add `tiangolo.com` to the list of exceptions and enjoy our beutifull sponsors :)\n\n", "source_type": "issue", "path": "issues/12239.json", "symbol": "Sponsor Badge CSS overflow issue on the docs", "url": "https://github.com/fastapi/fastapi/issues/12239", "start_line": null, "end_line": null} {"id": "issue::12240", "text": "# Issue #12240: Regression between 0.113.0 and 0.114.0: OAuth2PasswordRequestForm used to accept grant_type=\"\"\nLabels: question\n### Discussed in https://github.com/fastapi/fastapi/discussions/12182\r\n\r\n
\r\n\r\nOriginally posted by **rbubley** September 10, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\n# This is just the code from https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/#update-the-dependencies\r\n\r\nfrom datetime import datetime, timedelta, timezone\r\nfrom typing import Annotated\r\n\r\nimport jwt\r\nfrom fastapi import Depends, FastAPI, HTTPException, status\r\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\r\nfrom jwt.exceptions import InvalidTokenError\r\nfrom passlib.context import CryptContext\r\nfrom pydantic import BaseModel\r\n\r\n# to get a string like this run:\r\n# openssl rand -hex 32\r\nSECRET_KEY = \"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\"\r\nALGORITHM = \"HS256\"\r\nACCESS_TOKEN_EXPIRE_MINUTES = 30\r\n\r\n\r\nfake_users_db = {\r\n \"johndoe\": {\r\n \"username\": \"johndoe\",\r\n \"full_name\": \"John Doe\",\r\n \"email\": \"johndoe@example.com\",\r\n \"hashed_password\": \"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW\",\r\n \"disabled\": False,\r\n }\r\n}\r\n\r\n\r\nclass Token(BaseModel):\r\n access_token: str\r\n token_type: str\r\n\r\n\r\nclass TokenData(BaseModel):\r\n username: str | None = None\r\n\r\n\r\nclass User(BaseModel):\r\n username: str\r\n email: str | None = None\r\n full_name: str | None = None\r\n disabled: bool | None = None\r\n\r\n\r\nclass UserInDB(User):\r\n hashed_password: str\r\n\r\n\r\npwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\r\n\r\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\r\n\r\napp = FastAPI()\r\n\r\n\r\ndef verify_password(plain_password, hashed_password):\r\n return pwd_context.verify(plain_password, hashed_password)\r\n\r\n\r\ndef get_password_hash(password):\r\n return pwd_context.hash(password)\r\n\r\n\r\ndef get_user(db, username: str):\r\n if username in db:\r\n user_dict = db[username]\r\n return UserInDB(**user_dict)\r\n\r\n\r\ndef authenticate_user(fake_db, username: str, password: str):\r\n user = get_user(fake_db, username)\r\n if not user:\r\n return False\r\n if not verify_password(password, user.hashed_password):\r\n \n---\nComment: This was fixed by https://github.com/fastapi/fastapi/pull/13537 and available in FastAPI 0.123.2 🎉\n---\nComment: @Kludex I don't know if this is the correct way, but we can change [this code](https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L64-L75) by replacing the form pattern with the default value. Something like this\r\n\r\n```python\r\ngrant_type: Annotated[\r\n Union[str, None],\r\n Form(),\r\n Doc(\r\n \"\"\"\r\n The OAuth2 spec says it is required and MUST be the fixed string\r\n \"password\". Nevertheless, this dependency class is permissive and\r\n allows not passing it. If you want to enforce it, use instead the\r\n `OAuth2PasswordRequestFormStrict` dependency.\r\n \"\"\"\r\n ),\r\n] = \"password\",\r\n```\r\n\r\nAfter that change, everything works with the default or empty value.\n---\nComment: Is there any objection to this proposed fix?", "source_type": "issue", "path": "issues/12240.json", "symbol": "Regression between 0.113.0 and 0.114.0: OAuth2PasswordRequestForm used to accept grant_type=\"\"", "url": "https://github.com/fastapi/fastapi/issues/12240", "start_line": null, "end_line": null} {"id": "issue::12245", "text": "# Issue #12245: Optional form field not working with test client\nLabels: question\n### Discussed in https://github.com/fastapi/fastapi/discussions/12227\r\n\r\n
\r\n\r\nOriginally posted by **MartinAchtnerAA** September 19, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom typing import Annotated, Literal, Optional\r\n\r\nfrom fastapi import FastAPI, Form\r\nfrom fastapi.testclient import TestClient\r\n\r\napp = FastAPI()\r\n\r\n@app.post(\"/\")\r\nasync def read_main(\r\n attribute : Annotated[Optional[Literal[\"abc\", \"def\"]], Form()]\r\n):\r\n print(attribute)\r\n\r\n\r\nclient = TestClient(app)\r\n\r\n\r\ndata = {}\r\ndata[\"attribute\"] = None\r\n\r\nresponse = client.post(\"/\", data=data)\r\nprint(response.content)\r\nassert response.status_code == 200\r\n```\r\n\r\n\r\n### Description\r\n\r\nIn FastAPI 0.113 .0 the above code passes.\r\nSince version 0.114.0 the response is a 422 status code with error message '{\"detail\":[{\"type\":\"literal_error\",\"loc\":[\"body\",\"attribute\"],\"msg\":\"Input should be \\'abc\\' or \\'def\\'\",\"input\":\"\",\"ctx\":{\"expected\":\"\\'abc\\' or \\'def\\'\"}}]}'\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.114.0\r\n\r\n### Pydantic Version\r\n\r\n2.9.1\r\n\r\n### Python Version\r\n\r\n3.12.3\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: I proposed a pull request here trying to differentiate between None and not specified: https://github.com/fastapi/fastapi/pull/12502\n---\nComment: My notes about this issue are written here: https://github.com/fastapi/fastapi/discussions/12227#discussioncomment-10716549\n---\nComment: @Kludex I extended your example to add some more context to the issue in https://github.com/fastapi/fastapi/discussions/12227#discussioncomment-10749794", "source_type": "issue", "path": "issues/12245.json", "symbol": "Optional form field not working with test client", "url": "https://github.com/fastapi/fastapi/issues/12245", "start_line": null, "end_line": null} {"id": "issue::12246", "text": "# Issue #12246: OpenAPI servers not being returned according how the docs say they should be\nLabels: question\n### Discussed in https://github.com/fastapi/fastapi/discussions/12226\r\n\r\n
\r\n\r\nOriginally posted by **mzealey** September 19, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom fastapi import FastAPI\r\n\r\napp = FastAPI()\r\n\r\n# you can add a test endpoint here or not - same bug either way\r\n```\r\n\r\n\r\n### Description\r\n\r\n```\r\n$ curl localhost:8$ curl localhost:8000/openapi.json\r\n{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"FastAPI\",\"version\":\"0.1.0\"},\"paths\":{}}\r\n```\r\n\r\nAccording to the documentation of the `servers` parameter in FastAPI:\r\n\r\n> If the servers list is not provided, or is an empty list, the default value would be a dict with a url value of /.\r\n\r\n(assuming that `root_path_in_servers = True` (the default))\r\n\r\nClearly this is not happening.\r\n\r\n### Operating System\r\n\r\nLinux\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.110.3 (but according to github code seems to be in latest also)\r\n\r\n### Pydantic Version\r\n\r\n2.5.3\r\n\r\n### Python Version\r\n\r\nPython 3.10.12\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: Relevant part of the docstrings: https://github.com/fastapi/fastapi/blob/9606b916ef7c883f5ebeac1bf3db9adf5ae646a9/fastapi/applications.py#L299-L300\n---\nComment: @Kludex I don't know if this is the correct way, but we can add default value of `[{\"url\": \"/\"}]` instead of `None`. Something like this\r\n```python\r\nservers: Annotated[\r\n Optional[List[Dict[str, Union[str, Any]]]],\r\n Doc(\r\n \"\"\"\r\n # unchanged docstring\r\n \"\"\"\r\n ),\r\n] = [{\"url\": \"/\"}],\r\n```\r\nResult for default:\r\n```python\r\nfrom fastapi import FastAPI\r\n\r\napp = FastAPI()\r\n```\r\nis \r\n```bash\r\n> curl localhost:8000/openapi.json\r\n{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"FastAPI\",\"version\":\"0.1.0\"},\"servers\":[{\"url\":\"/\"}],\"paths\":{}}\r\n```\r\nResult for provided urls:\r\n```python\r\nfrom fastapi import FastAPI\r\n\r\napp = FastAPI(\r\n servers=[\r\n {\"url\": \"https://stag.example.com\", \"description\": \"Staging environment\"},\r\n {\"url\": \"https://prod.example.com\", \"description\": \"Production environment\"},\r\n ]\r\n)\r\n```\r\nis\r\n\r\n```bash\r\n> curl localhost:8000/openapi.json\r\n{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"FastAPI\",\"version\":\"0.1.0\"},\"servers\":[{\"url\":\"https://stag.exampl\n---\nComment: Interestingly I see at https://swagger.io/docs/specification/api-host-and-base-path/:\r\n\r\n> If the servers array is not provided or is empty, the server URL defaults to /:\r\n\r\nBut a lot of readers don't seem to do this so probably worth fully specifying it in FastAPI.", "source_type": "issue", "path": "issues/12246.json", "symbol": "OpenAPI servers not being returned according how the docs say they should be", "url": "https://github.com/fastapi/fastapi/issues/12246", "start_line": null, "end_line": null} {"id": "issue::12290", "text": "# Issue #12290: Chrome does not display Swagger UI\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n![image](https://github.com/user-attachments/assets/0a5523b2-3727-4e33-8590-e13b5a7c7126)\r\n\r\nChrome does not display Swagger UI, but Edge can. \r\nIs this a bug?\r\n\n---\nComment: @soevai you marked this as completed, but did you find a resolution, or did it resolve itself? I have been asked to look at an endpoint today and I am seeing it error on Chrome but not Firefox. ", "source_type": "issue", "path": "issues/12290.json", "symbol": "Chrome does not display Swagger UI", "url": "https://github.com/fastapi/fastapi/issues/12290", "start_line": null, "end_line": null} {"id": "issue::12313", "text": "# Issue #12313: Required with Ellipsis may not work\nLabels: docs, confirmed\n### Privileged issue\n\n- [ ] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nhttps://fastapi.tiangolo.com/tutorial/query-params-str-validations/#required-parameters\r\n![QQ_1727594279276](https://github.com/user-attachments/assets/86d8893a-4c3f-45cb-8fc3-7f97cad6ac00)\r\npython interpreter:3.12.4\r\nfastapi version:0.115.0\r\n\r\nmy codes:\r\n```\r\nfrom __future__ import annotations\r\nfrom typing import Annotated\r\nimport uvicorn\r\nfrom fastapi import FastAPI, Query\r\napp = FastAPI()\r\n@app.get(\"/items/\")\r\nasync def read_items(q: Annotated[str, Query(min_length = 3)] = ...):\r\n \"\"\"\r\n curl -X 'GET' 'http://127.0.0.1:18081/items/' -H 'accept: application/json'\r\n ValueError: [TypeError(\"'ellipsis' object is not iterable\"), TypeError('vars() argument must have __dict__ attribute')]\r\n \"\"\"\r\n results = {\"items\": [{\"item_id\": \"Foo\"}, {\"item_id\": \"Bar\"}]}\r\n if q:\r\n results.update({\"q\": q})\r\n return results\r\n\r\n\r\nif __name__ == '__main__':\r\n uvicorn.run(app, host = '127.0.0.1', port = 18081)\r\n```\r\nswagger docs:\r\n![QQ_1727594546393](https://github.com/user-attachments/assets/c1b94031-5145-4f27-981a-6d35f6cc2fe2)\r\n\r\n![QQ_1727594603897](https://github.com/user-attachments/assets/4d370afd-5642-4948-8521-65483a460514)\r\n\r\nValueError: [TypeError(\"'ellipsis' object is not iterable\"), TypeError('vars() argument must have __dict__ attribute')]\r\n \r\n \n---\nComment: - Given https://github.com/fastapi/fastapi/issues/10360, I don't think it makes sense for FastAPI to support V1 anymore.\n---\nComment: This is the part that reproduces the warning:\r\n\r\n```py\r\nfrom typing import Annotated\r\n\r\nimport uvicorn\r\nfrom fastapi import FastAPI, Query\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/prepare\")\r\nasync def prepare(str_param: Annotated[str, Query()] = ...):\r\n return {\"str_param\": str_param}\r\n\r\n\r\nif __name__ == \"__main__\":\r\n uvicorn.run(app, host=\"127.0.0.1\", port=18081)\r\n```\r\n\r\nIt makes sense, but we already said that this is not needed. You can just do:\r\n```py\r\n@app.get(\"/prepare\")\r\nasync def prepare(str_param: Annotated[str, Query()]):\r\n return {\"str_param\": str_param}\r\n```\r\n\r\nYou only see the issue on the first time you call `/docs` because that's when the OpenAPI is generated. After that, the OpenAPI object is cached.\n---\nComment: Note that in Pydantic, we recently moved away from using the ellipsis, and we now recommend against using it: https://github.com/pydantic/pydantic/pull/10661.", "source_type": "issue", "path": "issues/12313.json", "symbol": "Required with Ellipsis may not work", "url": "https://github.com/fastapi/fastapi/issues/12313", "start_line": null, "end_line": null} {"id": "issue::12323", "text": "# Issue #12323: Should the alias parameter in the Path method be removed?\n### Privileged issue\n\n- [ ] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nThis is my MRE code:\r\n```python\r\nfrom __future__ import annotations\r\n\r\nfrom typing import Annotated\r\n\r\nimport uvicorn\r\nfrom fastapi import FastAPI, Path\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get('/{item_id}')\r\nasync def async_root(item_id: Annotated[int, Path(title = 'Item ID', alias = 'xid')]):\r\n return {'item_id': item_id}\r\n\r\n\r\nif __name__ == '__main__':\r\n uvicorn.run(app, host = '127.0.0.1', port = 18081)\r\n```\r\nand I got the swagger docs:\r\nhttp://127.0.0.1:18081/docs#/default/async_root__item_id__get\r\n![QQ_1727667100103](https://github.com/user-attachments/assets/fbc42966-eba6-4f96-aa4f-bb85243022f7)\r\n\r\nQuestion:\r\n1. Why is the content of the title field not displayed in the documentation?\r\n2. \r\n![QQ_1727667237322](https://github.com/user-attachments/assets/22d006f8-7ddc-4175-b7d9-1da86b55628b)\r\nThe generated curl request is incorrect; the placeholder {item_id} has not been replaced with the value 123 for xid\r\n3. When I try to manually send a curl request to access it, I still get an error:\r\n```python\r\ncurl http://127.0.0.1:18081/123\r\n{\"detail\":[{\"type\":\"missing\",\"loc\":[\"path\",\"xid\"],\"msg\":\"Field required\",\"input\":null}]}\r\n```\r\n4. When I remove the alias field from the Path method, it works normally:\r\n```python\r\n@app.get('/{item_id}')\r\nasync def async_root(item_id: Annotated[int, Path(title = 'Item ID')]):\r\n return {'item_id': item_id}\r\n```\r\n![QQ_1727667506471](https://github.com/user-attachments/assets/d64fa7d2-e704-4ccd-82cf-37505b37c043)\r\n```python\r\n curl http://127.0.0.1:18081/123\r\n{\"item_id\":123}\r\n```\r\nthe `alias` field description:\r\n![QQ_1727667820560](https://github.com/user-attachments/assets/1f8eb781-0092-4189-96a9-4e24397ec520)\r\n\r\nMy Environment:\r\nPython 3.12.4\r\nFastAPI 0.115.0\r\nmacOS M2 Max 14.6.1\r\nPyCharm 2024.2.3 (Professional Edition)\n---\nComment: @bowenerchen I think `alias` is useful for passing a Python reserved keyword or similar as a path parameter (as noted in the FastAPI docs). You must pass an `alias` to a path operation decorator like this\r\n```python\r\n@app.get(\"/{xid}\") # <- here\r\nasync def async_root(item_id: Annotated[int, Path(alias=\"xid\")]):\r\n return {\"item_id\": item_id}\r\n```\r\nAfter that everything works. \r\n```bash\r\n> curl http://127.0.0.1:18018/123\r\n{\"item_id\":123}\r\n```\r\nSorry if I missed your point.", "source_type": "issue", "path": "issues/12323.json", "symbol": "Should the alias parameter in the Path method be removed?", "url": "https://github.com/fastapi/fastapi/issues/12323", "start_line": null, "end_line": null} {"id": "issue::12382", "text": "# Issue #12382: HTML WEB SAMPLES FOR TOKEN AUTH\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nEverything demo, o smal sample is oriented to json, not web templates,\r\n\r\ncould u include samples with html samples, about login jwt many concurrent users.\r\n\r\npls ", "source_type": "issue", "path": "issues/12382.json", "symbol": "HTML WEB SAMPLES FOR TOKEN AUTH", "url": "https://github.com/fastapi/fastapi/issues/12382", "start_line": null, "end_line": null} {"id": "issue::12402", "text": "# Issue #12402: [BUG] In version 0.115.0 of FastAPI, the pydantic model that has declared an alias cannot correctly receive query parameters\nThank you for all the work you have done. I have initiated the [discussion ](https://github.com/fastapi/fastapi/discussions/12401)as requested, but I think this issue is quite important. Initiating this issue is just to prevent the discussion from being drowned out, and I apologize for any offense.\r\n\r\n### Example Code\r\n\r\n```python\r\nimport uvicorn\r\nfrom typing import Literal\r\n\r\nfrom fastapi import FastAPI, Query\r\nfrom pydantic import BaseModel, ConfigDict, Field\r\nfrom pydantic.alias_generators import to_camel\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass FilterParams(BaseModel):\r\n model_config = ConfigDict(alias_generator=to_camel)\r\n\r\n limit: int = Field(100, gt=0, le=100)\r\n offset: int = Field(0, ge=0)\r\n order_by: Literal['created_at', 'updated_at'] = 'created_at'\r\n tags: list[str] = []\r\n\r\n\r\n@app.get('/items/')\r\nasync def read_items(filter_query: FilterParams = Query()):\r\n return filter_query\r\n\r\n\r\nif __name__ == '__main__':\r\n uvicorn.run(app='app:app')\r\n```\r\n\r\n\r\n### Description\r\n\r\nRunning the code in the example above, I encountered an incorrect result when accessing http://127.0.0.1:8000/items/?offset=1&orderBy=updated_at in the browser, orderBy did not receive successfully.\r\n```\r\n{\r\n \"limit\": 100,\r\n \"offset\": 1,\r\n \"orderBy\": \"created_at\",\r\n \"tags\": []\r\n}\r\n```\r\nThe correct result should be as follows\r\n```\r\n{\r\n \"limit\": 100,\r\n \"offset\": 1,\r\n \"orderBy\": \"updated_at\",\r\n \"tags\": []\r\n}\r\n```\r\n\r\n### Operating System\r\n\r\nWindows\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.115.0\r\n\r\n### Pydantic Version\r\n\r\n2.9.2\r\n\r\n### Python Version\r\n\r\n3.9.19\r\n\r\n### Additional Context\r\n\r\n_No response_\n---\nComment: Hello everyone! Can you confirm that it is not possible to have other query params along with the pydantic model ?\r\n```\r\nfrom typing import Annotated, Literal\r\n\r\nimport uvicorn\r\nfrom fastapi import FastAPI, Query\r\nfrom pydantic import BaseModel, Field\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass FilterParams(BaseModel):\r\n limit: int = Field(100, gt=0, le=100)\r\n offset: int = Field(0, ge=0)\r\n order_by: Literal[\"created_at\", \"updated_at\"] = \"created_at\"\r\n tags: list[str] = []\r\n\r\n\r\n@app.get(\"/items/\")\r\nasync def read_items(\r\n filter_query: Annotated[FilterParams, Query()],\r\n another_param: Annotated[int, Query()]\r\n):\r\n print(filter_query, another_param)\r\n```\r\n\r\nThe generated swagger looks like a bit messy in this case \r\n![image](https://github.com/user-attachments/assets/22127fd4-cc7a-4dd0-807c-0c47a6416b9c)\r\n\n---\nComment: It seems to me, that this bug has been fixed here: https://github.com/fastapi/fastapi/commit/88d4f2cb1814392f54011b2bbd3fe55c5f2a3278 but this commit re-introduced it: https://github.com/fastapi/fastapi/commit/55035f440bf852f739e3ccd71b67034016ae9bba#diff-aef3dac481b68359f4edd6974fa3a047cfde595254a4567a560cebc9ccb0673fR765\n\nFor me changing [this Line](https://github.com/fastapi/fastapi/blob/master/fastapi/dependencies/utils.py#L783) to \n\n```python\nvalues[field.alias] = value\n```\n\n(as it was done by the first mentioned commit) makes everything work as expected using the `Annotated[FilterParams, Query()]`-syntax\n\n---\nComment: It seems this was solved in https://github.com/fastapi/fastapi/pull/14360, available in FastAPI 0.123.3 🎉 ", "source_type": "issue", "path": "issues/12402.json", "symbol": "[BUG] In version 0.115.0 of FastAPI, the pydantic model that has declared an alias cannot correctly receive query parameters", "url": "https://github.com/fastapi/fastapi/issues/12402", "start_line": null, "end_line": null} {"id": "issue::12419", "text": "# Issue #12419: Question about \"Required, can be None\" parameter\nLabels: docs\n### Discussed in https://github.com/fastapi/fastapi/discussions/12418\r\n\r\n
\r\n\r\nOriginally posted by **bowenerchen** October 10, 2024\r\n### First Check\r\n\r\n- [X] I added a very descriptive title here.\r\n- [X] I used the GitHub search to find a similar question and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import FastAPI, Query\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.get(\"/items/\")\r\nasync def read_items(q: Annotated[str | None, Query(min_length=3)] = ...):\r\n results = {\"items\": [{\"item_id\": \"Foo\"}, {\"item_id\": \"Bar\"}]}\r\n if q:\r\n results.update({\"q\": q})\r\n return results\r\n```\r\n\r\n\r\n### Description\r\n\r\nhttps://fastapi.tiangolo.com/tutorial/query-params-str-validations/#required-can-be-none\r\n![QQ_1728534861112](https://github.com/user-attachments/assets/95e967aa-ea9f-46c1-80c8-f13dc7c52e6c)\r\nhow to pass a None value to the required query parameter q?\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\nSonoma 14.7 M2 Max\r\n\r\n### FastAPI Version\r\n\r\n0.115.0\r\n\r\n### Pydantic Version\r\n\r\n2.5.3\r\n\r\n### Python Version\r\n\r\nPython 3.12.4\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: This may be the same as https://github.com/fastapi/fastapi/issues/12245\n---\nComment: The documentation is wrong.\r\n\r\nThis is the file that is testing that part of the documentation: https://github.com/fastapi/fastapi/blob/529155e72e196f82e0289f173a185e8ddb2888ce/tests/test_tutorial/test_query_params/test_tutorial006_py310.py\r\n\r\nAs we can see, it doesn't pass the `None`...\n---\nComment: Hi @Kludex, should i open a PR to `improve documentation` like below one, this will be my first open source contribution?\n\n```\n@app.get(\"/items/\")\nasync def read_items(q: Annotated[str | None, Query()]): # required\n if q == \"null\":\n q = None\n\n results = {\"items\": [{\"item_id\": \"Foo\"}, {\"item_id\": \"Bar\"}]}\n if q is not None:\n results.update({\"q\": q})\n return results\n```", "source_type": "issue", "path": "issues/12419.json", "symbol": "Question about \"Required, can be None\" parameter", "url": "https://github.com/fastapi/fastapi/issues/12419", "start_line": null, "end_line": null} {"id": "issue::12425", "text": "# Issue #12425: python3.13 install uvicorn fault\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\no activate this project's virtualenv, run pipenv shell.\r\nAlternatively, run a command inside the virtualenv with pipenv run.\r\nInstalling dependencies from Pipfile.lock (527371)...\r\n: Collecting click==8.1.7 (from -r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 1))\r\n: Using cached click-8.1.7-py3-none-any.whl (97 kB)\r\n: Collecting h11==0.14.0 (from -r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 2))\r\n: Using cached h11-0.14.0-py3-none-any.whl (58 kB)\r\n: Collecting httptools==0.6.1 (from -r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 3))\r\n: Using cached httptools-0.6.1.tar.gz (191 kB)\r\n: Preparing metadata (setup.py): started\r\n: Preparing metadata (setup.py): finished with status 'done'\r\n: Collecting python-dotenv==1.0.1 (from -r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 4))\r\n: Using cached python_dotenv-1.0.1-py3-none-any.whl (19 kB)\r\n: Collecting pyyaml==6.0.2 (from -r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 5))\r\n: Using cached PyYAML-6.0.2-cp313-cp313-win_amd64.whl (156 kB)\r\n: Collecting uvicorn==0.31.1 (from uvicorn==0.31.1->-r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 6))\r\n: Using cached uvicorn-0.31.1-py3-none-any.whl (63 kB)\r\n: Collecting watchfiles==0.24.0 (from -r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 7))\r\n: Using cached watchfiles-0.24.0-cp313-none-win_amd64.whl (276 kB)\r\n: Collecting websockets==13.1 (from -r c:\\users\\starlee\\appdata\\local\\temp\\pipenv-dbv5y_0a-requirements\\pipenv-2599a94r-hashed-reqs.txt (line 8))\r\n: Using cached websockets-13.1-cp313-cp313-win_amd64.whl (159 kB)\r\n: Building wheels for collected packages: httptools\r\n: Building wheel for httptools (setup.py): started\r\n: Building wheel for httptools (setup.py): finished with status 'error'\r\n: Running setup.py clean for httptools\r\n: Failed to build httptools\r\n: error: subprocess-exited-with-error\r\n:\r\n: × python setup.py bdist_wheel did not run successfully.\r\n: │ exit code: 1\r\n: ╰─> [66 lines of output]\r\n: C:\\Users\\starlee\\.virtualenvs\\test-uSjHFhYi\\Lib\\site-packages\\setuptools\\_distutils\\dist.py:261: UserWarning: Unknown distribution option: 'test_suite'\r\n: warnings.warn(msg)\r\n: running bdist_wheel\r\n: running build\r\n: running build_py\r\n: creating build\\lib.win-amd64-cpython-313\\httptools\r\n: copying httptools\\_version.py -> build\\lib.win-amd64-cpython-313\\httptools\r\n: copying httptools\\__init__.py -> build\\lib.win-amd64-cpython-313\\httptools\r\n: creating build\\lib", "source_type": "issue", "path": "issues/12425.json", "symbol": "python3.13 install uvicorn fault", "url": "https://github.com/fastapi/fastapi/issues/12425", "start_line": null, "end_line": null} {"id": "issue::12426", "text": "# Issue #12426: Docs run script error\n### Privileged issue\r\n\r\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\nI cloned the project and installed requirements.txt. When I run ```python ./scripts/docs.py live az```, I get the following error.\r\n\r\nOS: Windows 10 \r\nPython version 3.12.5\r\n\r\n![image](https://github.com/user-attachments/assets/665db120-5d1e-4256-8430-cee023023916)\r\n\n---\nComment: No need to ping. It's already marked as issue.\n---\nComment: @tiangolo Please look at this\n---\nComment: Hey @vahidzhe, have you tried these, they solve this problem for me\n```\npip install \\\n \"mkdocstrings[python]>=0.18\" \\\n griffe-typingdoc \\\n mkdocs-material \\\n mkdocs-macros-plugin \\\n mkdocs-redirects \\\n mdx_include \\\n mkdocs-markdownextradata-plugin\n```\nAnd I also comment out this line in file docs/en/mkdocs.yml\n`markdown_include_variants:`\n", "source_type": "issue", "path": "issues/12426.json", "symbol": "Docs run script error", "url": "https://github.com/fastapi/fastapi/issues/12426", "start_line": null, "end_line": null} {"id": "issue::12459", "text": "# Issue #12459: \"Cookies with a Pydantic Model\" the demo codes cannot run properly\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nhttps://fastapi.tiangolo.com/tutorial/cookie-param-models/#cookies-with-a-pydantic-model\r\n```python\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import Cookie, FastAPI\r\nfrom pydantic import BaseModel\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass Cookies(BaseModel):\r\n session_id: str\r\n fatebook_tracker: str | None = None\r\n googall_tracker: str | None = None\r\n\r\n\r\n@app.get(\"/items/\")\r\nasync def read_items(cookies: Annotated[Cookies, Cookie()]):\r\n return cookies\r\n```\r\n![QQ_1728967103087](https://github.com/user-attachments/assets/5de19020-653c-471f-8b75-b6933e5ab32b)\r\n![QQ_1728967116921](https://github.com/user-attachments/assets/984079b5-58fd-4e55-bb92-eba18b68edd5)\r\n![QQ_1728967226720](https://github.com/user-attachments/assets/738d45d6-3c32-4519-a35e-4e50f23c8fb5)\r\n\r\n\r\n\r\n\r\n\n---\nComment: Seems like an issue with the generated OpenAPI, or Swagger. I'm not sure which. Nonetheless, an issue.\r\n\r\n```py\r\nfrom __future__ import annotations\r\n\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import Cookie, FastAPI\r\nfrom pydantic import BaseModel\r\n\r\napp = FastAPI()\r\n\r\n\r\nclass Cookies(BaseModel):\r\n session_id: str\r\n fatebook_tracker: str | None = None\r\n googall_tracker: str | None = None\r\n\r\n\r\n@app.get(\"/items/\")\r\nasync def read_items(cookies: Annotated[Cookies, Cookie()]):\r\n return cookies\r\n```\r\nIt works without Swagger context (HTTPie):\r\n```bash\r\nhttp :9000/items/ \"Cookie: session_id=value1; fatebook_tracker=value2; googall_tracker=haha\"\r\n```\n---\nComment: > Seems like an issue with the generated OpenAPI, or Swagger. I'm not sure which. Nonetheless, an issue.\r\n> \r\n> ```python\r\n> from __future__ import annotations\r\n> \r\n> from typing import Annotated\r\n> \r\n> from fastapi import Cookie, FastAPI\r\n> from pydantic import BaseModel\r\n> \r\n> app = FastAPI()\r\n> \r\n> \r\n> class Cookies(BaseModel):\r\n> session_id: str\r\n> fatebook_tracker: str | None = None\r\n> googall_tracker: str | None = None\r\n> \r\n> \r\n> @app.get(\"/items/\")\r\n> async def read_items(cookies: Annotated[Cookies, Cookie()]):\r\n> return cookies\r\n> ```\r\n> \r\n> It works without Swagger context (HTTPie):\r\n> \r\n> ```shell\r\n> http :9000/items/ \"Cookie: session_id=value1; fatebook_tracker=value2; googall_tracker=haha\"\r\n> ```\r\n\r\nHaha, I am really a careful document reader.\n---\nComment: Try it with the testclient, there is an issue affecting all of the objects passed in like this, Cookies, Queries etc - seems to work fine when ran normally.", "source_type": "issue", "path": "issues/12459.json", "symbol": "\"Cookies with a Pydantic Model\" the demo codes cannot run properly", "url": "https://github.com/fastapi/fastapi/issues/12459", "start_line": null, "end_line": null} {"id": "issue::12497", "text": "# Issue #12497: Use Request in Fastapi to get post json data request, it throw a error : exception in asgi application\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\ncode:\r\n![image](https://github.com/user-attachments/assets/57cba8ee-0b23-41b9-bc65-5061680dca19)\r\nerror:\r\n![image](https://github.com/user-attachments/assets/68b08ec8-d54a-40dc-9d69-e75b19862cde)\r\n", "source_type": "issue", "path": "issues/12497.json", "symbol": "Use Request in Fastapi to get post json data request, it throw a error : exception in asgi application", "url": "https://github.com/fastapi/fastapi/issues/12497", "start_line": null, "end_line": null} {"id": "issue::12554", "text": "# Issue #12554: Update docs include syntax for source examples\nLabels: good first issue\n### Privileged issue\r\n\r\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\nThis is a good first contribution. :nerd_face: \r\n\r\nThe code examples shown in the docs are actual Python files. They are even tested in CI, that's why you can always copy paste an example and it will always work, the example is tested.\r\n\r\nThe way those examples are included in the docs used a specific format. But now there's a new format available that is much simpler and easier to use than the previous one, in particular in complex cases, for example when there are examples in multiple versions of Python.\r\n\r\nBut not all the docs have the new format yet. The docs should use the new format to include examples. That is the task. :nerd_face: \r\n\r\n**It should be done as one PR per page updated.**\r\n\r\n## Simple Example\r\n\r\nBefore, the format was like:\r\n\r\n````markdown\r\n```Python hl_lines=\"3\"\r\n{!../../docs_src/first_steps/tutorial001.py!}\r\n```\r\n````\r\n\r\nNow the new format looks like:\r\n\r\n````markdown\r\n{* ../../docs_src/first_steps/tutorial001.py hl[3] *}\r\n````\r\n\r\n* Instead of `{!` and `!}` it uses `{*` and `*}`\r\n* It no longer has a line above with:\r\n\r\n````markdown\r\n```Python\r\n````\r\n\r\n* And it no longer has a line below with:\r\n\r\n````markdown\r\n```\r\n````\r\n\r\n* The highlight is no longer a line with e.g. `hl_lines=\"3\"` (to highlight line 3), but instead in the same line there's a `hl[3]`.\r\n\r\nAn example PR: https://github.com/fastapi/fastapi/pull/12552\r\n\r\n## Multiple Python Versions\r\n\r\nThere are some cases where there are variants of the same example for multiple versions of Python, or for using `Annotated` or not.\r\n\r\nIn those cases, the current include examples have syntax for tabs, and notes saying `Annotated` should be preferred. For example:\r\n\r\n````markdown\r\n//// tab | Python 3.9+\r\n\r\n```Python hl_lines=\"4 8 12\"\r\n{!> ../../docs_src/security/tutorial006_an_py39.py!}\r\n```\r\n\r\n////\r\n\r\n//// tab | Python 3.8+\r\n\r\n```Python hl_lines=\"2 7 11\"\r\n{!> ../../docs_src/security/tutorial006_an.py!}\r\n```\r\n\r\n////\r\n\r\n//// tab | Python 3.8+ non-Annotated\r\n\r\n/// tip\r\n\r\nPrefer to use the `Annotated` version if possible.\r\n\r\n///\r\n\r\n```Python hl_lines=\"2 6 10\"\r\n{!> ../../docs_src/security/tutorial006.py!}\r\n```\r\n\r\n////\r\n````\r\n\r\nIn these cases, it should be updated to only include the first one (the others will be included automatically :sunglasses: ):\r\n\r\n````markdown\r\n{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *}\r\n````\r\n\r\n* The syntax for tabs is also removed, all the other variants are included automatically.\r\n* The highlight lines are included for that same first file, the fragment with `hl_lines=\"4 8 12\"` is replaced with `hl[4,8,12]`\r\n\r\nAn example PR: https://github.com/fastapi/fastapi/pull/12553\r\n\r\n## Highlight Lines\r\n\r\n### Simple Lines\r\n\r\nWhen there's a fragment like:\r\n\r\n````markdown\r\nhl_lines=\"4 8 12\"\r\n````\r\n\r\nThat means it is highlighting the lines 4, 8, and 12.\r\n\r\nThe new syntax is on the same include line:\r\n\r\n````markdown\r\nhl[4,8,12]\r\n---\nComment: @FarhanAliRaza the issue is not assigned, there are many PRs that would come out of this, one PR per page fixed, so, you can just take a page that has the old syntax, check there are no other PRs handling it, then update the syntax, and make a PR for it.\n---\nComment: > Hi @krishnamadhavan\r\n> \r\n> so when tabs were used above some code was deleted. is this the expected contribution. example\r\n> \r\n> ```\r\n> \r\n> You would do the same to declare `tuple`s and `set`s:\r\n> \r\n> //// tab | Python 3.9+\r\n> \r\n> {* ../../docs_src/python_types/tutorial007_py39.py hl[1] *}\r\n> \r\n> \r\n> ////\r\n> \r\n> //// tab | Python 3.8+\r\n> \r\n> \r\n> {* ../../docs_src/python_types/tutorial007.py hl[1,4] *}\r\n> \r\n> ////```\r\n> \r\n> \r\n> \r\n> \r\n> unlike the example above there was a tutorial for py 3.10\r\n> ```\r\n\r\n@philipokiokio I believe you're talking about [this PR](https://github.com/fastapi/fastapi/pull/12555/files) from @tiangolo . If you're mentioning about the `
` and `` block, it was used to collapse and expand.\r\n\r\nBut since we're combining the different version definitions into a single line, I think we should be good there.\n---\nComment: @FarhanAliRaza As suggested by @tiangolo, it'd be easier for everyone to understand which pages you're working on, if you can set the title of your PR with the file path.\r\n\r\nThanks for understanding.\r\n\r\nA reference PR from @tiangolo for your perusal: https://github.com/fastapi/fastapi/pull/12552", "source_type": "issue", "path": "issues/12554.json", "symbol": "Update docs include syntax for source examples", "url": "https://github.com/fastapi/fastapi/issues/12554", "start_line": null, "end_line": null} {"id": "issue::1273", "text": "# Issue #1273: Use TestClient in an async fashion\nLabels: feature, good first issue, answered, reviewed\n### Is your feature request related to a problem\n\nUnfortunately, test client runs it's own event loop. This causes an issue when attempting to do other async operations in the background.\nRunning it inside an executor will cause it to run in a different threat, which in turn causes issues with other async libraries a they're calling coroutines from a different thread.\n\n### The solution you would like\n\nMake a TestClient that doesn't create it's own loop. Just have it async. \n\n### Describe alternatives you've considered\n\nOther than executor or partching fastapi, there are no alternatives. \n\n---\nComment: I think it's a good feature request to let devs write application tests in async functions with websocket support. Why it's closed?\r\n\r\nE.g. I want to make an integration test with 2 servers running during the tests and I can't use sync tests (because `TestClient` blocks the thread). The good alternative is `AsyncClient` but it doesn't support websockets.\n---\nComment: As @empicano mentioned using httpx directly works great. Here's a little example \"workaround\" by using the `httpx.AsyncClient` and it's working quite well\r\n\r\nin your conftest.py\r\n\r\n```python\r\n\r\nfrom typing import Generator\r\nimport pytest\r\nfrom httpx import AsyncClient\r\nfrom asyncio import get_event_loop\r\n\r\nfrom app.main import app\r\nfrom app.db.session import SessionLocal\r\n \r\n\r\n@pytest.fixture(scope=\"session\")\r\ndef db() -> Generator:\r\n\r\n yield SessionLocal()\r\n\r\n\r\n@pytest.fixture(scope=\"module\")\r\nasync def async_client() -> Generator:\r\n\r\n async with AsyncClient(app=app, base_url=\"http://testserver\") as client:\r\n\r\n yield client\r\n\r\n\r\n@pytest.fixture(scope=\"module\")\r\ndef event_loop():\r\n\r\n loop = get_event_loop()\r\n\r\n yield loop\r\n\r\n```\r\n\r\nin a test file\r\n\r\n```python\r\n\r\nimport pytest\r\nfrom httpx import AsyncClient\r\nfrom fastapi import status\r\nfrom sqlalchemy.orm import Session\r\n\r\n\r\n@pytest.mark.asyncio\r\nasync def test_get_something(async_client: AsyncClient, db: Session) -> \n---\nComment: Is there an AsyncClient equivalent for websockets?", "source_type": "issue", "path": "issues/1273.json", "symbol": "Use TestClient in an async fashion", "url": "https://github.com/fastapi/fastapi/issues/1273", "start_line": null, "end_line": null} {"id": "issue::12765", "text": "# Issue #12765: error\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nINFO: Will watch for changes in these directories: ['C:\\\\Users\\\\wangy']\r\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\r\nINFO: Started reloader process [20616] using WatchFiles\r\nERROR: Error loading ASGI app. Could not import module \"main\".\r\n", "source_type": "issue", "path": "issues/12765.json", "symbol": "error", "url": "https://github.com/fastapi/fastapi/issues/12765", "start_line": null, "end_line": null} {"id": "issue::12780", "text": "# Issue #12780: Dependency Injection and Field Validation\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\ncode\r\n```\r\ndef get_db():\r\n db = SessionLocal2()\r\n try:\r\n yield db\r\n except Exception as e:\r\n logger.exception(e)\r\n db.rollback() \r\n raise e\r\n finally:\r\n db.close()\r\nclass NurseNewSchema(BaseModel):\r\n family_user_id: str\r\n time_day: int\r\n nurse_master: str\r\n nurse_remarks: str | None\r\n nurse_title: str\r\n\r\nasync def post_new_nurse(item: NurseNewSchema, db=Depends(get_db)):\r\n pass\r\n```\r\nWhen nurse_master is not filled in, data verification fails, but the interface executes to get_db, and when yielding db, it reports data verification failure.\r\n\r\n2024-11-06 09:58:29.965 | ERROR | core:get_db:59 - [{'loc': ('body', 'nurse_master'), 'msg': 'field required', 'type': 'value_error.missing'}]\r\nTraceback (most recent call last):\r\n\r\n File \"/usr/lib/python3.10/threading.py\", line 973, in _bootstrap\r\n self._bootstrap_inner()\r\n │ └ \r\n └ \r\n File \"/usr/lib/python3.10/threading.py\", line 1016, in _bootstrap_inner\r\n self.run()\r\n │ └ \r\n └ \r\n File \"/home/ouyang/.env/paper/lib/python3.10/site-packages/anyio/_backends/_asyncio.py\", line 807, in run\r\n result = context.run(func, *args)\r\n │ │ │ └ (, RequestValidationError([{'loc': ('body', 'nurse_master'), 'msg': 'field...\r\n │ │ └ >\r\n │ └ \r\n └ <_contextvars.Context object at 0x7fd6d9e22700>\r\n File \"/usr/lib/python3.10/contextlib.py\", line 153, in __exit__\r\n self.gen.throw(typ, value, traceback)\r\n │ │ │ │ │ └ None\r\n │ │ │ │ └ RequestValidationError([{'loc': ('body', 'nurse_master'), 'msg': 'field required', 'type': 'value_error.missing'}])\r\n │ │ │ └ \r\n │ │ └ \r\n │ └ \r\n └ \r\n\r\n> File \"/home/ouyang/Desktop/poc/core.py\", line 55, in get_db\r\n yield db\r\n └ \r\nfastapi.exceptions.RequestValidationError: [{'loc': ('body', 'nurse_master'), 'msg': 'field required', 'type': 'value_error.missing'}]\r\n\r\n \n---\nComment: The error is happening because FastAPI is trying to yield the db session in get_db() before it handles the validation error. By ensuring that the validation happens before calling the dependency (get_db), the session will only be created if the input is valid. This prevents unnecessary database connections in case of invalid input. \r\n\r\n1)Refactor get_db() as a Context Manager: This keeps the session logic clear and prevents unnecessary session creation before validation.\r\n2)Ensure Validation Happens First: FastAPI will validate item (which is the body input) before get_db is even called. So if there’s any validation failure, it will happen before the DB session is created.\r\n3)Error Handling in get_db(): If an exception is raised (such as a validation error), get_db() will log and handle it without impacting the database session.\n---\nComment: > This prevents unnecessary database connections in case of invalid input.\n\nIn production applications it is common to create SQLAlchemy's Engine, and then use it so create sessions. Engine is a connection pool, so it doesn't really create new session each time, but reuses already opened session from the pool.", "source_type": "issue", "path": "issues/12780.json", "symbol": "Dependency Injection and Field Validation", "url": "https://github.com/fastapi/fastapi/issues/12780", "start_line": null, "end_line": null} {"id": "issue::12901", "text": "# Issue #12901: Upcoming Pydantic 2.10 is going to break version comparison checks\nLabels: bug\n### Privileged issue\r\n\r\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\nThe following check:\r\n\r\nhttps://github.com/fastapi/fastapi/blob/5a48c37056397e47ab164ba4430807aa6fc9a710/fastapi/params.py#L108-L109\r\n\r\nis going to be flawed when we release Pydantic 2.10 (in a week):\r\n\r\n```python\r\n\"2.10.0\" > \"2.7.0\"\r\n#> False\r\n```\n---\nComment: Thanks for the report @Viicos! I handled it in https://github.com/fastapi/fastapi/pull/12914, it will be released in the next hours. :nerd_face: ", "source_type": "issue", "path": "issues/12901.json", "symbol": "Upcoming Pydantic 2.10 is going to break version comparison checks", "url": "https://github.com/fastapi/fastapi/issues/12901", "start_line": null, "end_line": null} {"id": "issue::12924", "text": "# Issue #12924: Do you have a performance checker for FaskAPI? The problem is that when you make 100 concurrent requests, the API returns are slow. How do you solve it?\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n![image](https://github.com/user-attachments/assets/531ebf3c-0d76-4241-a742-b9286e20736d)\r\n![image](https://github.com/user-attachments/assets/7942db47-2a25-4af7-aaa1-4a6c40ccd735)\r\n![image](https://github.com/user-attachments/assets/c91ae68c-e57c-471b-a182-b0a49dea3df6)\r\nIs there a problem with the code, is there any code to refer to, or is there a health monitoring tool to check the FaskAPI", "source_type": "issue", "path": "issues/12924.json", "symbol": "Do you have a performance checker for FaskAPI? The problem is that when you make 100 concurrent requests, the API returns are slow. How do you solve it?", "url": "https://github.com/fastapi/fastapi/issues/12924", "start_line": null, "end_line": null} {"id": "issue::12936", "text": "# Issue #12936: Starting multiple processes within multiple processes in Python\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nI defined a multiprocessing pool in the initialization function, and then started multiple processes within a single process, resulting in an error.::AssertionError: daemonic processes are not allowed to have children\r\nThe code works fine outside of your framework, so is it due to some limitations in your framework or another reason?", "source_type": "issue", "path": "issues/12936.json", "symbol": "Starting multiple processes within multiple processes in Python", "url": "https://github.com/fastapi/fastapi/issues/12936", "start_line": null, "end_line": null} {"id": "issue::12963", "text": "# Issue #12963: Fastapi performance issue not responding important \n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nHai \r\nWe using fastapi last 1.5 Yr we facing daily issues on that on performance like 100 to 200 clients requesting every 5 sec some time not responding some time totally hanging we restarting the services \r\nAdditional information we used mysql", "source_type": "issue", "path": "issues/12963.json", "symbol": "Fastapi performance issue not responding important ", "url": "https://github.com/fastapi/fastapi/issues/12963", "start_line": null, "end_line": null} {"id": "issue::12965", "text": "# Issue #12965: Will FastAPI support QUERY http method? \"app.query\"\nLabels: feature\n### Discussed in https://github.com/fastapi/fastapi/discussions/6049\r\n\r\n
\r\n\r\nOriginally posted by **FilipeMarch** December 16, 2022\r\n### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom fastapi import FastAPI\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.query('/query/subjects')\r\ndef query_subjects(schema: ArbitrarySchema):\r\n with Session(engine) as db:\r\n subjects = db.query(Subject).all()\r\n return schema(**subjects)\r\n\r\n# something like this\r\n```\r\n\r\n\r\n### Description\r\n\r\nThere is a new HTTP method called QUERY, I discovered it this week and it is super interesting!\r\n\r\nhttps://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html\r\n\r\nI was trying to make a GET route that would accept a request body, but started receiving an error on Swagger UI:\r\n\r\n[TypeError: Request has method 'GET' and cannot have a body](https://github.com/swagger-api/swagger-ui/issues/5891#issuecomment-1340591857)\r\n\r\nThe idea is that sometimes we need to make a big or complex query, and this is the scenario in which we can see the advantages of GraphQL, and although I have seen that [we can integrate FastAPI with GraphQL](https://fastapi.tiangolo.com/advanced/graphql/), I was wondering if FastAPI will ever be able to simply accept a QUERY method like, for example, `app.query(\"/query/subjects\")`.\r\n\r\nFor example, suppose I have this object:\r\n```yml\r\n{\r\n \"id\": 1,\r\n \"name\": \"Math\"\r\n \"tags\": [\r\n {\r\n \"id\": 1,\r\n \"name\": \"Algebra\",\r\n \"number_of_clicks\": 1,\r\n \"number_of_questions\": 7,\r\n \"number_of_answers\": 3,\r\n \"number_of_comments\": 2,\r\n \"number_of_votes\": 1,\r\n }]\r\n \"topics\": [\r\n {\r\n \"id\": 1,\r\n \"name\": \"Linear Equations\",\r\n \"likes\": 1,\r\n \"dislikes\": 0,\r\n \"number_of_clicks\": 1,\r\n \"number_of_tutorials\": 1,\r\n \"number_of_questions\": 7,\r\n \"posts\": [\r\n {\r\n \"id\": 1,\r\n \"title\": \"How to solve linear equations?\",\r\n \"likes\": 1,\r\n \"dislikes\": 0,\r\n \"number_of_clicks\": 1,\r\n---\nComment: We should wait OpenAPI to support it.\n---\nComment: I think https://github.com/OAI/OpenAPI-Specification/issues/1747 needs to happen before this issue.\n---\nComment: Forgive me if this is premature, but it looks like the [v3.2-dev branch](https://github.com/OAI/OpenAPI-Specification/tree/v3.2-dev) has the feature this was waiting on in it. [The fix was merged back in April](https://github.com/OAI/OpenAPI-Specification/pull/4514).", "source_type": "issue", "path": "issues/12965.json", "symbol": "Will FastAPI support QUERY http method? \"app.query\"", "url": "https://github.com/fastapi/fastapi/issues/12965", "start_line": null, "end_line": null} {"id": "issue::12987", "text": "# Issue #12987: FastApi website issue\n### Privileged issue\r\n\r\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\nIssue in Fastapi website in ubuntu-mint flavor\r\n\r\nLook at the top of the menu bar\r\n\r\n![image](https://github.com/user-attachments/assets/ffe82cdf-2e9f-4d49-bef8-6ceea8c57e85)\r\n", "source_type": "issue", "path": "issues/12987.json", "symbol": "FastApi website issue", "url": "https://github.com/fastapi/fastapi/issues/12987", "start_line": null, "end_line": null} {"id": "issue::13019", "text": "# Issue #13019: Multipart upload is not working without a trailing slash\n```\r\nExpected boundary character 45, got 20 at index 2\r\n```\r\n\r\nRelated: \r\nhttps://github.com/fastapi/fastapi/discussions/7062#discussioncomment-6090647_\n---\nComment: How can I reproduce?\n---\nComment: ```py\r\n@app.post(\"/search/\")\r\nasync def search(file: UploadFile = File(...)):\r\n image = Image.open(io.BytesIO(await file.read()))\r\n```\n---\nComment: Please create a discussion with a code that can be easily reproducible - including imports, and how to call this code.", "source_type": "issue", "path": "issues/13019.json", "symbol": "Multipart upload is not working without a trailing slash", "url": "https://github.com/fastapi/fastapi/issues/13019", "start_line": null, "end_line": null} {"id": "issue::13022", "text": "# Issue #13022: Traceback stack does not show exact place of error\nLabels: question, question-migrate\n### Discussed in https://github.com/fastapi/fastapi/discussions/8428\r\n\r\n
\r\n\r\nOriginally posted by **NewSouthMjos** December 5, 2022\r\n### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [x] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nimport uvicorn\r\nfrom fastapi import FastAPI, Depends\r\n\r\n\r\napp = FastAPI()\r\n\r\n\r\ndef get_something_sync():\r\n yield True\r\n\r\n\r\nasync def get_something_async():\r\n yield True\r\n\r\n\r\n@app.get('/1')\r\ndef router_func(dependency=Depends(get_something_sync)):\r\n raise ValueError\r\n return\r\n\r\n\r\n@app.get('/2')\r\ndef router_func(dependency=Depends(get_something_async)):\r\n raise ValueError\r\n return\r\n\r\n\r\nif __name__ == \"__main__\":\r\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=5600, workers=1)\r\n```\r\n\r\n\r\n### Description\r\n\r\nIf dependency function uses yield, injecting dependency with sync def function (get_something_sync), the error traceback will broke - it doesn't locate the place where it was rise (should be \"/app/main.py\", line 24)\r\ncalling endpoint /1:\r\n```\r\nfastapi_dependency | INFO: 10.77.78.83:60070 - \"GET /1 HTTP/1.1\" 500 Internal Server Error\r\nfastapi_dependency | ERROR: Exception in ASGI application\r\nfastapi_dependency | Traceback (most recent call last):\r\nfastapi_dependency | File \"/usr/local/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py\", line 419, in run_asgi\r\nfastapi_dependency | result = await app( # type: ignore[func-returns-value]\r\nfastapi_dependency | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\nfastapi_dependency | File \"/usr/local/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py\", line 78, in __call__\r\nfastapi_dependency | return await self.app(scope, receive, send)\r\nfastapi_dependency | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\nfastapi_dependency | File \"/usr/local/lib/python3.11/site-packages/fastapi/applications.py\", line 270, in __call__\r\nfastapi_dependency | await super().__call__(scope, receive, send)\r\nfastapi_dependency | File \"/usr/local/lib/python3.11/site-packages/starlette/applications.py\", line 124, in __call__\r\nfastapi_dependency | await self.middleware_stack(scope, receive, send)\r\nfastapi_dep\n---\nComment: I've simplified a bit the PR that solves this: https://github.com/fastapi/fastapi/pull/5823\n---\nComment: I think the issue is not what it's described here, but I'll not spam another one to not create confusion.\r\n\r\nThe issue is actually this one: https://github.com/fastapi/fastapi/discussions/12999\r\n\r\nThe one mentioned in this issue is very similar, but it was solved.", "source_type": "issue", "path": "issues/13022.json", "symbol": "Traceback stack does not show exact place of error", "url": "https://github.com/fastapi/fastapi/issues/13022", "start_line": null, "end_line": null} {"id": "issue::13023", "text": "# Issue #13023: StreamingResponse was block my program???\n### Privileged issue\n\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nasync def generate_predictions(model_name):\r\n global stop_flag\r\n mean, std, labels, model, pca_model = get_init(model_name) \r\n async for prediction in collect_predict(mean, std, labels, model, pca_model):\r\n if stop_flag == True:\r\n stop_flag = False \r\n break\r\n yield json.dumps({\"prediction\": prediction}) + \"\\n\"\r\n\r\n@router.get(\"/end_predict\")\r\ndef end_predict():\r\n global stop_flag\r\n stop_flag = True\r\n return {'message' : 'End predict'}\r\n\r\n@router.post(\"/predict\")\r\ndef predict_func(data: predict):\r\n model_name = data.name_predict\r\n return StreamingResponse(\r\n generate_predictions(model_name), \r\n media_type=\"application/json\"\r\n )\r\n", "source_type": "issue", "path": "issues/13023.json", "symbol": "StreamingResponse was block my program???", "url": "https://github.com/fastapi/fastapi/issues/13023", "start_line": null, "end_line": null} {"id": "issue::13056", "text": "# Issue #13056: Can't use `Annotated` with `ForwardRef`\nLabels: bug\n### Issue Content\r\n\r\nThe following code doesn't generate the correct OpenAPI json:\r\n\r\n```py\r\nfrom __future__ import annotations\r\n\r\nfrom dataclasses import dataclass\r\nfrom typing import Annotated\r\n\r\nfrom fastapi import Depends, FastAPI\r\n\r\napp = FastAPI()\r\n\r\n\r\ndef get_potato() -> Potato:\r\n return Potato(color='red', size=10)\r\n\r\n\r\n@app.get('/')\r\nasync def read_root(potato: Annotated[Potato, Depends(get_potato)]):\r\n return {'Hello': 'World'}\r\n\r\n\r\n@dataclass\r\nclass Potato:\r\n color: str\r\n size: int\r\n```\r\n\r\nIf we move the `Potato` up, or remove the `Annotated`, then it works as expected.\n---\nComment: > [...] I think you'll get the same error if Potato was defined earlier.\r\n\r\nNo, the problem here is `Potato` after.\r\n\r\n> What does the generated json look like? Do we get 'Annotated[Potato, Depends(get_potato)]' rather than the actual type?\r\n\r\nThe `potato` is a query parameter on the generated OpenAPI. But you can run it, and check by yourself... 👀 \n---\nComment: I ran into this issue with caused debugging hell, there's a function already part of the standard library that solves most of the complicated logic: https://typing-extensions.readthedocs.io/en/latest/index.html#typing_extensions.get_annotations. \n---\nComment: I've explored the codebase, and although it seems #14557 and #14703 were associated with this issue to attempt to fix. I have some ideas on making the check a bit more robust so we can cover variations such as `typing.Annotated` or even type aliasing.\n\nIf there is interest, I can take a stab and open a PR in the next day or so?", "source_type": "issue", "path": "issues/13056.json", "symbol": "Can't use `Annotated` with `ForwardRef`", "url": "https://github.com/fastapi/fastapi/issues/13056", "start_line": null, "end_line": null} {"id": "issue::13067", "text": "# Issue #13067: poor quality traceback / useful stack frames not present when exceptions raised in sync dependencies\n### Privileged issue\r\n\r\n- [X] I'm ~@tiangolo or he asked me directly to create an issue here~ a liar, but the discussion template was crazy onerous, and I'm confident I can write a decent, succinct issue description that's worth reading here ;-)\r\n\r\n### Issue Content\r\n\r\nIf I apply this diff to the [full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template/blob/88c83cc06ccab67efa839c2c0994435b727986a3/backend/app/api/deps.py#L21-L23):\r\n\r\n```diff\r\ndiff --git a/backend/app/api/deps.py b/backend/app/api/deps.py\r\nindex c2b83c8..c99cdb2 100644\r\n--- a/backend/app/api/deps.py\r\n+++ b/backend/app/api/deps.py\r\n@@ -19,6 +19,7 @@ reusable_oauth2 = OAuth2PasswordBearer(\r\n \r\n \r\n def get_db() -> Generator[Session, None, None]:\r\n+ raise Exception(\"error\")\r\n with Session(engine) as session:\r\n yield session\r\n```\r\n\r\n\r\n...and issue a GET to `http://127.0.0.1:8000/api/v1/users/`, the traceback shown in the console is really unhelpful:\r\n\r\n```\r\n File \"...3.11/lib/python3.11/contextlib.py\", line 650, in enter_async_context\r\n result = await _enter(cm)\r\n ^^^^^^^^^^^^^^^^\r\n File \"...3.11/lib/python3.11/contextlib.py\", line 210, in __aenter__\r\n return await anext(self.gen)\r\n ^^^^^^^^^^^^^^^^^^^^^\r\n File \".../full-stack-fastapi-template/backend/.venv/lib/python3.11/site-packages/fastapi/concurrency.py\", line 35, in contextmanager_in_threadpool\r\n raise e\r\nException: error\r\n\r\n```\r\n\r\nThere are no frames from the actual site of the exception, and, on the face of it, potentially no way to go back from the exception to the source of the error.\r\n\r\nI first noticed this doing test driven development on a new FastAPI project, having not done any FastAPI dev for a couple of years, and was pretty shocked.\r\n\r\nWhat I don't understand is why the exception being re-raised appears to have no traceback of its own?\n---\nComment: Did you try the last FastAPI version?\n---\nComment: Close enough:\r\n\r\n```\r\n$ uv tree | grep -i fast\r\nResolved 81 packages in 0.92ms\r\n├── fastapi[standard] v0.115.0\r\n│ ├── fastapi-cli[standard] v0.0.5 (extra: standard)\r\n├── sentry-sdk[fastapi] v1.45.1\r\n│ └── fastapi v0.115.0 (extra: fastapi) (*)\r\n```\r\n\r\n\r\nDropped a breakpoint, does indeed appear that `__traceback__` is None, but why?\r\n\r\n```\r\n> .../python3.11/site-packages/fastapi/concurrency.py(36)contextmanager_in_threadpool()\r\n-> raise e\r\n(Pdb) !e\r\nException('error')\r\n(Pdb) !e.__traceback__\r\n(Pdb) !e.__traceback__ is None\r\nTrue\r\n```\n---\nComment: Can you try on the really latest?", "source_type": "issue", "path": "issues/13067.json", "symbol": "poor quality traceback / useful stack frames not present when exceptions raised in sync dependencies", "url": "https://github.com/fastapi/fastapi/issues/13067", "start_line": null, "end_line": null} {"id": "issue::13111", "text": "# Issue #13111: Incorrect handling of non utf-8 data in body in case of a validataion error\n### Privileged issue\r\n\r\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\nThere was no way to report actual issue by the rules so I had to lie about being able to do so...\r\nThere has to be a section in discussions or something then.\r\n\r\n```\r\nERROR: Exception in ASGI application\r\nTraceback (most recent call last):\r\n File \"REDACTED\\.venv\\Lib\\site-packages\\starlette\\_exception_handler.py\", line 53, in wrapped_app\r\n await app(scope, receive, sender)\r\n File \"REDACTED\\.venv\\Lib\\site-packages\\starlette\\routing.py\", line 72, in app\r\n response = await func(request)\r\n ^^^^^^^^^^^^^^^^^^^\r\n File \"REDACTED\\.venv\\Lib\\site-packages\\fastapi\\routing.py\", line 315, in app\r\n raise validation_error\r\nfastapi.exceptions.RequestValidationError: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': b'----cpp-httplib-multipart-data-UxL5MB5nIRg5wqYk\\r\\nContent-Disposition: form-data; name=\"metadata\"\\r\\nContent-Type: application/json\\r\\n\\r\\n{\"started\":1735320698,\"length_seconds\":3}\\r\\n----cpp-httplib-multipart-data-UxL5MB5nIRg5wqYk\\r\\nContent-Disposition: form-data; name=\"metadata\"; filename=\"main.ogg\"\\r\\nContent-Type: audio/ogg\\r\\n\\r\\nOggS\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x81Z\\x97E\\x00\\x00\\x00\\x00\\x0b\\xffmn\\x01\\x13OpusHead\\x01\\x028\\x01\\x80>\\x00\\x00\\x00\\x00\\x00OggS\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x81Z\\x97E\\x01\\x00\\x00\\x00\\xf3sR\\x98\\x01\\'OpusTags\\x17\\x00\\x00\\x00recorder ogg-opus 0.0.1\\x00\\x00\\x00\\x00OggS\\x00\\x00\\xc0\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x81Z\\x97E\\x02\\x00\\x00\\x00\\xd2\\xf2\\x8d\r\n\r\nOriginally posted by **bruchar1** March 30, 2022\r\n### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nrouter.add_api_route(\r\n \"/clear\",\r\n clear,\r\n methods=[\"POST\", \"DELETE\"]\r\n)\r\n```\r\n\r\n\r\n### Description\r\n\r\nSeems to be caused by #4650.\r\n\r\nThe new `generate_unique_id()` function uses `list(route.methods)[0].lower()` as suffix for the `operation_id`. Therefore, in my example, both post and delete endpoints get `_post` suffix for operation_id, causing it to no longer be unique.\r\n\r\nIt then issues a \"UserWarning: Duplicate Operation ID\"\r\n\r\n### Operating System\r\n\r\nWindows\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\n0.75.0\r\n\r\n### Python Version\r\n\r\n3.10.2\r\n\r\n### Additional Context\r\n\r\n_No response_
\n---\nComment: There is also PR #4851 that aimed to solve this, but it was closed by Sebastian with the [comment](https://github.com/fastapi/fastapi/pull/4851#issuecomment-2294657832):\n\n> Using multiple methods for the same function is not actually supported. `@router.api_route()` is there as a semi-internal utility, and because Starlette supports multiple methods, the interface is there. But the official way to do it in FastAPI and have all the FastAPI features (including the automatic OpenAPI integration, with operation IDs) is by using the dedicated methods, like `app.post()`, `app.get()`, etc.\n\nIf we agree that `.api_route()` and `.add_api_route()` methods are semi-internal and shouldn't be used by user, we should probably turn them into private methods (add deprecation warning)?\n\n```py\ndef add_route(...):\n warnings.warn(\n \"This method is deprecated and will be removed in a future version. \"\n \"Please use `.get()`, `.post()`, etc.. methods instead.\",\n DeprecationWarning,\n \n---\nComment: There's a PR already for it: https://github.com/fastapi/fastapi/pull/10694/\n---\nComment: I've seen `@api_route` suggested in this repo when you need to work with generic Requests (e.g. you want to create a proxy).", "source_type": "issue", "path": "issues/13175.json", "symbol": "Duplicated OperationID when adding route with multiple methods", "url": "https://github.com/fastapi/fastapi/issues/13175", "start_line": null, "end_line": null} {"id": "issue::13316", "text": "# Issue #13316: Callable object as dependency with body params is not parsing parameters inside `__call__` properly\nWhen callable object is used as dependency, there is problem with parameters inside `__call__` method of object class. With following setup, you end up with query parameters instead of body parameters:\n\n```python\nclass SomeModel(BaseModel):\n arg1: str\n\nclass SomeDependency:\n def __call__(\n self,\n some_model: Annotated[SomeModel, Body(..., description=\"Some model\")],\n ) -> dict:\n print(some_model.arg1)\n\n@app.post(\"/hello\")\nasync def hello(data: Annotated[dict, Depends(SomeDependency())]):\n return data\n```\n\nConsole:\n```\npydantic.errors.PydanticUserError: `TypeAdapter[typing.Annotated[ForwardRef(\"Annotated[SomeModel, Body(..., description='Some model')]\"), Query(PydanticUndefined)]]` is not fully defined; you should define `typing.Annotated[ForwardRef(\"Annotated[SomeModel, Body(..., description='Some model')]\"), Query(PydanticUndefined)]` and all referenced types, then call `.rebuild()` on the instance.\n```\n\n`Query(PydanticUndefined)` makes no sense, there are no query parameters. But when this function (in `fastapi/dependencies/utils.py`) gets updated:\n\n```python\ndef get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:\n signature = inspect.signature(call)\n globalns = getattr(call, \"__globals__\", {})\n ...\n```\n\ninto this:\n\n```python\ndef get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:\n signature = inspect.signature(call)\n if isinstance(call, type) or isinstance(call, types.FunctionType):\n globalns = getattr(call, \"__globals__\", {})\n else:\n globalns = getattr(call.__call__, \"__globals__\", {})\n ...\n```\n\nit works fine. Probably not the best solution. It's just to point out to the problem.\n\n_Originally posted by @SobikXexe in https://github.com/fastapi/fastapi/discussions/13286#discussioncomment-12043516_", "source_type": "issue", "path": "issues/13316.json", "symbol": "Callable object as dependency with body params is not parsing parameters inside `__call__` properly", "url": "https://github.com/fastapi/fastapi/issues/13316", "start_line": null, "end_line": null} {"id": "issue::13399", "text": "# Issue #13399: Dependency Models created from Form input data are loosing metadata(field set) and are enforcing validation on default values.\nLabels: question\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/13380\n\n
\n\nOriginally posted by **sneakers-the-rat** February 16, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n**Short version (UPD by @YuriiMotov):**\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import FastAPI, Form\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\nclass ExampleModel(BaseModel):\n field_1: bool = True\n\napp = FastAPI()\n\n@app.post(\"/body\")\nasync def body_endpoint(model: ExampleModel):\n return {\"fields_set\": list(model.model_fields_set)}\n\n@app.post(\"/form\")\nasync def form_endpoint(model: Annotated[ExampleModel, Form()]):\n return {\"fields_set\": list(model.model_fields_set)}\n\nclient = TestClient(app)\n\ndef test_body():\n resp = client.post(\"/body\", json={})\n assert resp.status_code == 200, resp.text\n fields_set = resp.json()[\"fields_set\"]\n assert fields_set == [] # Ok\n\ndef test_form():\n resp = client.post(\"/form\", data={})\n assert resp.status_code == 200, resp.text\n fields_set = resp.json()[\"fields_set\"]\n assert fields_set == [] # AssertionError: assert ['field_1'] == []\n```\n\n**Original code (in details):**\n\n
\n\nFile: fastapi_defaults_bug.py\n```python\nimport uvicorn\nfrom typing import Annotated\nfrom pydantic import BaseModel, Field\n\nfrom fastapi import FastAPI, Form\n\n\nclass ExampleJsonModel(BaseModel):\n sample_field_1: Annotated[bool, Field(default=True)]\n sample_field_2: Annotated[bool, Field(default=False)]\n sample_field_3: Annotated[bool, Field(default=None)]\n sample_field_4: Annotated[str, Field(default=0)] # This is dangerous but can be used with a validator\n\n\nclass ExampleFormModel(BaseModel):\n sample_field_1: Annotated[bool, Form(default=True)]\n sample_field_2: Annotated[bool, Form(default=False)]\n sample_field_3: Annotated[bool, Form(default=None)]\n sample_field_4: Annotated[str, Form(default=0)] # This is dangerous but can be used with a validator\n\n\nclass ResponseSampleModel(BaseModel):\n fields_set: Annotated[list, Field(default_factory=list)]\n dumped_fields_no_exclude: Annotated[dict, Field(default_factory=dict)]\n dumped_fields_exclude_default: Annot\n---\nComment: @sneakers-the-rat i think you are on the right spot, i do not have any role to expose what is the general preferred solution, this will be evaluated by reviewers and tiangolo. \nWhat can i do, is express my personal opinion and what i think.\nBased on your discussion i wrote a number of test cases to help anyone who want to work on this, to easily reproduce the issue and at the same time see what is the expected behaviour.\n\nAbout Pydantic compatibility:\n v1, v2, v1 submodule of v2 should all be handled and sometimes this could be a bit tricky.\n\nAbout the issue: while preloading the default values could be considered part of the root cause, for me the real problem is that we are loosing the information about if a field has been set or not and other corner cases that have to deal with default and validation ( this will generate other issues including your original one ).\n\n@Warlord-10 if you want to contribute look at: https://fastapi.tiangolo.com/contributing/\n\n@async-shreyas \nYou spotted \n---\nComment: Ok great, I'll write a PR now.\n\n@async-shreyas yes, see the prior discussion at https://github.com/fastapi/fastapi/discussions/13380\n---\nComment: from fastapi import Form\nfrom pydantic import BaseModel\n\nclass User(BaseModel):\n name: str = \"default\"", "source_type": "issue", "path": "issues/13399.json", "symbol": "Dependency Models created from Form input data are loosing metadata(field set) and are enforcing validation on default values.", "url": "https://github.com/fastapi/fastapi/issues/13399", "start_line": null, "end_line": null} {"id": "issue::13400", "text": "# Issue #13400: Header parameter and model handling does not work as expected\nLabels: bug\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/13160\n\n
\n\nOriginally posted by **freud14-tm** January 6, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom typing import Annotated, TypeAlias\n\nfrom fastapi import FastAPI, Header\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass CommonHeaders(BaseModel):\n host: str\n save_data: bool\n if_modified_since: str | None = None\n traceparent: str | None = None\n x_tag: list[str] = []\n\n\nCommonHeadersAnnotated: TypeAlias = Annotated[CommonHeaders, Header()]\n\n\n@app.get(\"/items/\")\nasync def read_items(headers: CommonHeadersAnnotated):\n return headers\n\n\n@app.get(\"/items2/\")\nasync def read_items2(x_prd_code: Annotated[str, Header()], headers: CommonHeadersAnnotated):\n return headers\n```\n\n\n### Description\n\nThere seems to be a few problems when using [Header Parameter Models](https://fastapi.tiangolo.com/tutorial/header-param-models/) as documented. The code above and the screenshots bellow show it. First, it seems that the Swagger UI doesn't convert underscores into dashes when using a Header Parameter Model. It works fine otherwise. Second, when using another header in the function, FastAPI interprets the parameter model as an object to be sent as a single header with the parameters as a comma-separated list instead of expecting the single parameters.\n\n\n![image](https://github.com/user-attachments/assets/7f387f1d-e737-492a-98ae-752dafa7438b)\n\n![image](https://github.com/user-attachments/assets/30e5eaea-2d5f-4595-b989-46fb6bf89e00)\n\n\n### Operating System\n\nLinux\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.115.6\n\n### Pydantic Version\n\n2.10.4\n\n### Python Version\n\n3.11.0\n\n### Additional Context\n\n_No response_
\n---\nComment: Thanks for the discussion, everyone!\n\nLet's split this into two things.\n\nThe first, handling correctly `convert_underscores`, this is a bug, let's keep this issue for that. It should have been handled in https://github.com/fastapi/fastapi/pull/13515 🎉 \n\nThis will be released in the next version, `0.115.12`, in the next hours.\n\nThe new docs: https://fastapi.tiangolo.com/tutorial/header-param-models/#forbid-extra-headers\n\n---\n\nAbout having a model alongside another parameter, this would be a feature request, better in a new discussion.\n\nI'm also not sure about it, because it would behave differently from a body parameter alongside a body model. So I would have to think about that feature some more first. For now, when using a Pydantic model for headers, only one model per path operation is supported.\n\nAnyway, feel free to create a new discussion question with the feature request. 🤓 \n---\nComment: Ah, then it's a bug. Sorry.\n---\nComment: I'll look into cleaning up the code to fit more within the `analyze_param` function and then could look into creating a PR for it", "source_type": "issue", "path": "issues/13400.json", "symbol": "Header parameter and model handling does not work as expected", "url": "https://github.com/fastapi/fastapi/issues/13400", "start_line": null, "end_line": null} {"id": "issue::13440", "text": "# Issue #13440: Validations in `Annotated` like `AfterValidator` do not work in FastAPI 0.115.10\nLabels: bug\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/13431\n\n
\n\nOriginally posted by **amacfie-tc** February 28, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom typing import Annotated\n\nfrom pydantic import AfterValidator\nfrom fastapi import FastAPI\n\n\napp = FastAPI()\n\ndef validator(v):\n raise ValueError()\n\nInts = Annotated[list[int], AfterValidator(validator)]\n\n@app.post(\"/\")\ndef post(ints: Ints) -> None:\n return None\n```\n\n\n### Description\n\nIf we run the code and send a request to the endpoint, e.g.\n```\necho -n '[2,3,4]' | http POST http://localhost:8000\n```\non version 0.115.9, we get a 422 but on 0.115.10 we get 200. Is this a bug?\n\n### Operating System\n\nLinux\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.115.10\n\n### Pydantic Version\n\n2.9.2, 2.10.6\n\n### Python Version\n\n3.12\n\n### Additional Context\n\n_No response_
\n\n---\n\n@tiangolo writes:\n\nThis was introduced here: https://github.com/fastapi/fastapi/pull/13314\n\nI'm currently investigating and a fix will be released shortly.\n\nThe problem is only when using `Annotated` directly in FastAPI parameters, when used inside of Pydantic models the validators work (raise) as expected:\n\n```Python\nfrom typing import Annotated\n\nfrom fastapi import FastAPI\nfrom pydantic import AfterValidator, BaseModel\n\napp = FastAPI()\n\n\ndef validator(v):\n raise ValueError()\n\n\nInts = Annotated[list[int], AfterValidator(validator)]\n\n\nclass Model(BaseModel):\n ints: Ints\n\n\n@app.post(\"/\")\ndef post(ints: Model) -> None:\n return None\n```\n---\nComment: Cool :) \n---\nComment: This was handled in https://github.com/fastapi/fastapi/pull/13442\n\nThat reverted the PR that introduced the problem, and added docs for these specific use cases, including source examples and tests for them to ensure they keep being supported. 🤓 \n\nIt is available in FastAPI 0.115.11, just released. 🚀 ", "source_type": "issue", "path": "issues/13440.json", "symbol": "Validations in `Annotated` like `AfterValidator` do not work in FastAPI 0.115.10", "url": "https://github.com/fastapi/fastapi/issues/13440", "start_line": null, "end_line": null} {"id": "issue::13471", "text": "# Issue #13471: Basic auth `realm` is REQUIRED but handled as optional\nLabels: bug\nAccording to https://datatracker.ietf.org/doc/html/rfc7617#autoid-3 , specification of the `realm` parameter is REQUIRED, so making `realm` optional here\n\nhttps://github.com/fastapi/fastapi/blob/643d2845de09a437b955a163ab25eb0887bfd0e1/fastapi/security/http.py#L195\n\nand at related places, is misleading and makes it easy to create non-conforming APIs. It bit me when a Shelly device refused (rightfully) to authenticate against the API which was using the default (missing) `realm` behavior.\n\n---\nComment: I think we should close this issue.\n\nAs Sebastian mentioned in [this comment](https://github.com/fastapi/fastapi/pull/13786#pullrequestreview-3501695067), `realm` seems to be not required in latest version of RFC.\n\n> I also noted that the spec says that the realm is now optional, but only in a footer note (https://datatracker.ietf.org/doc/html/rfc7235#appendix-A). 😂 Anyway, we are good with that now.\n\n\nI checked this and agree:\n\nThe https://datatracker.ietf.org/doc/html/rfc7617#autoid-3 states:\n\n> The authentication parameter 'realm' is REQUIRED ([RFC7235], Section 2.2).\n\nBut if we go to Section 2.2 of RFC7235, we have:\n\n> [2.2](https://datatracker.ietf.org/doc/html/rfc7235#section-2.2). Protection Space (Realm)\n> \n> The \"realm\" authentication parameter is reserved for use by\n> authentication schemes that wish to indicate a scope of protection.\n> \n> A protection space is defined by the canonical root URI (the scheme\n> and authority components of the effective request URI; \n---\nComment: Yeah this does look like a mistake to have \"realm\" as optional\n---\nComment: looks to be getting fixed here https://github.com/fastapi/fastapi/pull/12507", "source_type": "issue", "path": "issues/13471.json", "symbol": "Basic auth `realm` is REQUIRED but handled as optional", "url": "https://github.com/fastapi/fastapi/issues/13471", "start_line": null, "end_line": null} {"id": "issue::13533", "text": "# Issue #13533: Multiple regressions in the handling of forms & form validation\nLabels: bug\n\n\n### Issue Content\n\nWe have found at least 2 regression in the way forms are handled while trying to migrate to v0.115.11 from version v0.112.4. After investigation we were able to identify 2 commits that introduce 2 separate bugs that break the handling of default values in both `x-form-urlencoded` and `mutlipart` froms. Partial fixes have been proposed that also address a CVE, but the PR has been hanging since october 24.\n\n# Breaking in the handling of default value in `x-url-encoded` forms\n\nThis bug has been introduced in https://github.com/fastapi/fastapi/pull/12134.\n\nMRE:\n```python\napp = FastAPI()\n\n\n@app.post(\"/\")\ndef root(\n name: Annotated[Optional[str], Form(embed=True)] = None,\n):\n print(name)\n return name\n```\n\nwith the following request:\n```\n❯ http post -v --form localhost:8888 name=\"\"\nPOST / HTTP/1.1\nAccept: */*\nAccept-Encoding: gzip, deflate, br, zstd\nConnection: keep-alive\nContent-Length: 5\nContent-Type: application/x-www-form-urlencoded\nHost: localhost:8888\nUser-Agent: xh/0.24.0\n\nname=\n\nHTTP/1.1 200 OK\nContent-Length: 2\nContent-Type: application/json\nDate: Sun, 23 Mar 2025 21:01:49 GMT\nServer: uvicorn\n\n\"\"\n```\nThe expected result is that `None` is printed, but instead `\"\"` is printed.\n\nthis is the offending bit from the linked PR:\n```\ndiff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py\nindex 6083b731..db7eedba 100644\n--- a/fastapi/dependencies/utils.py\n+++ b/fastapi/dependencies/utils.py\n@@ -789,9 +789,9 @@ async def _extract_form_body(\n value = serialize_sequence_value(field=field, value=results)\n if value is not None:\n values[field.name] = value\n- for key, value in received_body.items():\n- if key not in values:\n- values[key] = value\n+ # for key, value in received_body.items():\n+ # if key not in values:\n+ # values[key] = value\n return values\n```\nThis patch solves the x-form-urlencoded case. So we indeed have two different regressions.\nThis _get_multi_dict_value gets called for all fields in the schema: https://github.com/fastapi/fastapi/blob/4633b1bca933e68dac5c3bcce797ff5963debe2a/fastapi/dependencies/utils.py#L765-L765\nwe see here the special case for empty fields: https://github.com/fastapi/fastapi/blob/4633b1bca933e68dac5c3bcce797ff5963debe2a/fastapi/dependencies/utils.py#L695-L700\nThis bit here just blindly re-adds all fields from the body: https://github.com/fastapi/fastapi/blob/4633b1bca933e68dac5c3bcce797ff5963debe2a/fastapi/dependencies/utils.py#L794-L796\n\nThis would be partially fixed by https://github.com/fastapi/fastapi/pull/12502/files, but also requires that ignored fields are not re-added to the form.\n\n\n# Breaking in the handling of default value in `multipart` forms\n\nThe breaking of multipart form originates from https://github.com/fastapi/fastapi/pull/12117 where the check for empty field was dropped https://github.com/fastapi/fastapi/pull/12117/files#diff-aef3dac481b68359f4edd6974fa3a047cfde595254a4567\n---\nComment: @alv2017 take the following example, this is the `x-www-form-urlencoded` case:\n\n```python\nfrom typing import Annotated, Optional\nimport fastapi\n\napp = fastapi.FastAPI()\n\n@app.post(\"/\")\ndef root(\n age: Annotated[Optional[int], fastapi.Form()] = None,\n):\n print(age)\n return age\n\n```\n\nrunning the following command:\n```\ncurl -v -X POST http://localhost:8888/ --data-urlencode 'age='\n```\n\nwith fastapi `0.112.4`\n\n```\nNote: Unnecessary use of -X or --request, POST is already inferred.\n* Host localhost:8888 was resolved.\n* IPv6: ::1\n* IPv4: 127.0.0.1\n* Trying [::1]:8888...\n* connect to ::1 port 8888 from ::1 port 55215 failed: Connection refused\n* Trying 127.0.0.1:8888...\n* Connected to localhost (127.0.0.1) port 8888\n> POST / HTTP/1.1\n> Host: localhost:8888\n> User-Agent: curl/8.7.1\n> Accept: */*\n> Content-Length: 4\n> Content-Type: application/x-www-form-urlencoded\n>\n* upload completely sent off: 4 bytes\n< HTTP/1.1 200 OK\n< date: Mon, 24 Mar 2025 18:57:03 GMT\n< server: uvicorn\n< c\n---\nComment: Also note that it's only for forms, json bodies work as intended\n---\nComment: > Also note that it's only for forms, json bodies work as intended\n\nCorrection added. :smiley:\n\nIt would be good if you could show the code, that you are using with http clients. Maybe the test that was passing before, and that is failing after upgrading to the newer version?\n", "source_type": "issue", "path": "issues/13533.json", "symbol": "Multiple regressions in the handling of forms & form validation", "url": "https://github.com/fastapi/fastapi/issues/13533", "start_line": null, "end_line": null} {"id": "issue::13606", "text": "# Issue #13606: FastAPI Tensor flow and tensor flow lite issue with Pyhon v3.14.x when making a pip installtion bug\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nI'm running a FastAPI backend and a frontend in flutter . After upgrading python version to v3.14.x, i was unable to install tensorflow or tensorflow lite for my project \nplease check out the issue to fix \n\nDowngrading python to v3.14.x fixed it.\n---\nComment: not resolved yet\n---\nComment: Please create a discussion.", "source_type": "issue", "path": "issues/13606.json", "symbol": "FastAPI Tensor flow and tensor flow lite issue with Pyhon v3.14.x when making a pip installtion bug", "url": "https://github.com/fastapi/fastapi/issues/13606", "start_line": null, "end_line": null} {"id": "issue::13715", "text": "# Issue #13715: SUB APPLICATIONS - MOUNTS IS SHOW INCORRECT INFORMATION\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nHi,\n\nI'm checking the docs: https://fastapi.tiangolo.com/advanced/sub-applications/#check-the-automatic-api-docs\n\nI see this example:\n\n![Image](https://github.com/user-attachments/assets/12381416-ea90-46c8-bc0d-bf1f38fbc9ec)\n\nbut when I test in my local machine. I see it:\n\n![Image](https://github.com/user-attachments/assets/347a24d3-edb2-439c-b3cc-afe4875d0783)\n\nAm I doing some bad?\n\nThanks.", "source_type": "issue", "path": "issues/13715.json", "symbol": "SUB APPLICATIONS - MOUNTS IS SHOW INCORRECT INFORMATION", "url": "https://github.com/fastapi/fastapi/issues/13715", "start_line": null, "end_line": null} {"id": "issue::13839", "text": "# Issue #13839: API Big file attacks\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nAny POST interface, submitting a file request (even if the interface does not declare to accept file parameters) causes the service memory to expand until the service crashes\n", "source_type": "issue", "path": "issues/13839.json", "symbol": "API Big file attacks", "url": "https://github.com/fastapi/fastapi/issues/13839", "start_line": null, "end_line": null} {"id": "issue::13880", "text": "# Issue #13880: Support for propertyNames in OpenAPI schema when using dict[Enum, ...] with Pydantic v2\nWhen using dict[StrEnum, ...] or RootModel[dict[StrEnum, ...]] in a FastAPI app with Pydantic v2, the generated OpenAPI schema does not enumerate the enum values used as dictionary keys. Instead, the UI shows [any-key], which does not reflect the actual constraints.\n\nAs of Pydantic v2.11+, support for emitting propertyNames with enum constraints was added via [PR #10478](https://github.com/pydantic/pydantic/pull/10478). This allows OpenAPI/JSON Schema to correctly express restrictions on object keys, such as:\n\n```\n{\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\",\n \"enum\": [\"foo\", \"bar\"]\n },\n \"additionalProperties\": {\n \"type\": \"integer\"\n }\n}\n```\n\nHowever, FastAPI currently does not appear to consume or propagate the propertyNames node from Pydantic’s schema output, so these constraints are missing in the OpenAPI spec and Swagger UI.\n\n### Expected Behavior\n\nFastAPI should correctly include propertyNames in the generated OpenAPI schema when dict[Enum, T] is used as a request/response model with Pydantic v2. This would allow Swagger UI to better reflect the allowed dictionary keys.\n\n### To Reproduce\n```\nfrom enum import StrEnum\nfrom pydantic import RootModel\nfrom fastapi import FastAPI\n\nclass MyEnum(StrEnum):\n foo = \"foo\"\n bar = \"bar\"\n\nclass MyModel(RootModel[dict[MyEnum, int]]):\n pass\n\napp = FastAPI()\n\n@app.post(\"/test\")\ndef test_endpoint(model: MyModel):\n return model\n```\n\n### Resulting OpenAPI Schema:\n```\n{\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"integer\"\n }\n}\n```\n\n### Expected Schema (from Pydantic v2.11+):\n```\n{\n \"type\": \"object\",\n \"propertyNames\": {\n \"type\": \"string\",\n \"enum\": [\"foo\", \"bar\"]\n },\n \"additionalProperties\": {\n \"type\": \"integer\"\n }\n}\n```\n\n### Environment\n- FastAPI version: latest\n- Pydantic version: 2.11.x+\n- Python version: 3.10+\n- Swagger UI version: [auto-generated by FastAPI]\n---\nComment: Hi! I'm trying to reproduce this behavior using:\n\nPydantic version: 2.11.7\n\nPython version: 3.11.13\n\nHere’s the relevant snippet from the generated OpenAPI schema:\n\n```yaml\n\"MyEnum\": {\n \"type\": \"string\",\n \"enum\": [\"foo\", \"bar\"],\n \"title\": \"MyEnum\"\n},\n\"MyModel\": {\n \"additionalProperties\": {\n \"type\": \"integer\"\n },\n \"propertyNames\": {\n \"$ref\": \"#/components/schemas/MyEnum\"\n },\n \"type\": \"object\",\n \"title\": \"MyModel\"\n}\n```\n\nIs this the expected output? Or am I missing something?\n\nApologies if this is a basic question — still getting familiar with how all of this fits together.\n\nThanks!\n---\nComment: I checked it and on current FastAPI (1.116.1) and Pydantic (2.11.7) versions it gives me schema with `propertyNames`.\nIt uses reference to `MyEnum`, but it seems to me that it's Ok (it doesn't change anything if I change it to the schema from the issue text).\n\nSwagger shows schema correctly, but struggles to create correct example and doesn't validate input on UI side:\n\"Image\"\n\n\"Image\"\n\nSo, I think this is not an issue on FastAPI's side and we should close it.\n\n@andrzejdoros, could you please check it?\n---\nComment: pip install --upgrade fastapi pydantic\n", "source_type": "issue", "path": "issues/13880.json", "symbol": "Support for propertyNames in OpenAPI schema when using dict[Enum, ...] with Pydantic v2", "url": "https://github.com/fastapi/fastapi/issues/13880", "start_line": null, "end_line": null} {"id": "issue::14010", "text": "# Issue #14010: validate_core_schema has been removed in the new pydantic-core (>=2.35.0), causing FastAPI to fail to import. Hoping to resolve this.\n### Privileged issue\n\n- [ ] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nvalidate_core_schema has been removed in the new pydantic-core (>=2.35.0), causing FastAPI to fail to import. Hoping to resolve this.\n\nfastapi==0.116.1\npydantic_core==2.39.0", "source_type": "issue", "path": "issues/14010.json", "symbol": "validate_core_schema has been removed in the new pydantic-core (>=2.35.0), causing FastAPI to fail to import. Hoping to resolve this.", "url": "https://github.com/fastapi/fastapi/issues/14010", "start_line": null, "end_line": null} {"id": "issue::14078", "text": "# Issue #14078: AI Bug Analysis: ValidationError: 1 validation error for Request\nbody\n field required (type=value_error.missing)\n### 🤖 AI Bug Report\n\n**Original Error:**\n```\nValidationError: 1 validation error for Request\nbody\n field required (type=value_error.missing)\n```\n\n--- \n\n### 🔬 Root Cause Analysis\nThe error message `ValidationError: 1 validation error for Request body field required (type=value_error.missing)` indicates that the request made to the server is missing a required field in the body of the request. This type of error typically occurs in the context of using Pydantic models with FastAPI, where the models define the expected structure and content of request bodies. Pydantic models enforce type checks and required fields, and if a request does not meet these criteria, a `ValidationError` is raised.\n\nGiven the context provided, it seems that the error is related to handling requests in a FastAPI application. The documents referenced in the code context discuss handling errors in FastAPI, including `RequestValidationError` and `ValidationError`, which are crucial for understanding how FastAPI processes and validates incoming request data against Pydantic models.\n\nThe specific error message points to a missing field in the request body, which is required by the Pydantic model that validates the request. This could be due to several reasons:\n\n1. **Client-Side Issue**: The client making the request may have failed to include a necessary field in the request body. This is common when the client's code does not correctly assemble the request or when the user forgets to provide all the required information.\n\n2. **Server-Side Validation Logic**: On the server side, the Pydantic model expects a field that was not provided in the request. This indicates a mismatch between the client's understanding of the required request format and the server's expectations.\n\n3. **Documentation/Communication Gap**: If the API documentation or the communication between the frontend and backend teams is not clear, it might lead to misunderstandings about what data is required, leading to such validation errors.\n\n4. **Code Changes**: Changes in the backend code, such as updating Pydantic models without corresponding updates in the client code, can also lead to such errors if the new requirements are not communicated or documented.\n\nTo resolve this issue, one should:\n\n- Verify the Pydantic model on the server side to understand exactly which field is missing.\n- Check the client's request to ensure it includes all required fields as per the Pydantic model.\n- Ensure that the API documentation is up to date and accurately reflects the current requirements of the Pydantic model.\n- If the error persists, additional logging on the server side to capture incoming requests might help identify what is missing or misformatted in the request body.\n\n--- \n\n### 🛠️ Suggested Fix\nGiven the root cause analysis, the error stems from a missing required field in the request body when it's being validated against a Pydantic model in a FastAPI application. To address this issue, we need to ensure that the c", "source_type": "issue", "path": "issues/14078.json", "symbol": "AI Bug Analysis: ValidationError: 1 validation error for Request\nbody\n field required (type=value_error.missing)", "url": "https://github.com/fastapi/fastapi/issues/14078", "start_line": null, "end_line": null} {"id": "issue::14114", "text": "# Issue #14114: how is this code is relavent to this ?\n> Here's another repro:\n> \n> ```python\n> from __future__ import annotations\n> \n> from typing import TYPE_CHECKING, Annotated\n> \n> from fastapi import Depends, FastAPI\n> from fastapi.testclient import TestClient\n> \n> if TYPE_CHECKING:\n> from httpx import AsyncClient\n> \n> app = FastAPI()\n> \n> \n> @app.get(\"/test\")\n> async def ping(client: Annotated[AsyncClient, Depends(lambda: AsyncClient())]) -> str:\n> resp = await client.get('http://example.com')\n> resp.raise_for_status()\n> return f\"Got {len(resp.text)} bytes\"\n> \n> \n> \n> async def test() -> None:\n> from httpx import AsyncClient\n> \n> async with AsyncClient() as client:\n> client = TestClient(app)\n> \n> response = client.get(\"/test\")\n> assert response.status_code == 200, f\"{response.status_code=}: {response.text=}\"\n> \n> \n> if __name__ == \"__main__\":\n> import anyio\n> \n> anyio.run(test)\n> ``` \n\n _Originally posted by @adriangb in [#13056](https://github.com/fastapi/fastapi/issues/13056#issuecomment-2616362994)_", "source_type": "issue", "path": "issues/14114.json", "symbol": "how is this code is relavent to this ?", "url": "https://github.com/fastapi/fastapi/issues/14114", "start_line": null, "end_line": null} {"id": "issue::14128", "text": "# Issue #14128: AssertionError: fastapi_inner_astack not found in request scope\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nlatest version of Fastapi is not support with Starlette 0.48.0.\n\nFAFastAPI 0.118.0\nStarlette 0.48.0\n---\nComment: > [@tiangolo](https://github.com/tiangolo) [@Kludex](https://github.com/Kludex) hello, this error ocurrs when paginating resuts:\n> \n> from fastapi_pagination import Page from fastapi_pagination.ext.sqlalchemy import paginate\n> \n> @contents_router.get( \"\", response_model=Page[UploadedContentResponse], status_code=status.HTTP_200_OK, tags=[\"Contents\"], )\n> \n> Is there any solution for this issue?\n\nJust in case someone else stumbles upon this error - it's solved with `fastapi-pagination` v0.14.2 [[link](https://github.com/uriyyo/fastapi-pagination/issues/1599)]\n---\nComment: btw, this is an MRE:\n```py\nfrom fastapi import APIRouter\nfrom starlette.testclient import TestClient\n\n\nrouter = APIRouter()\n\n\n@router.get(\"/items\")\nasync def root():\n return \"hi\"\n\n\nclient = TestClient(router)\nclient.get(\"/items\")\n```\n---\nComment: > this error ocurrs when paginating resuts:\n\nPlease, report this in the repository of `fastapi_pagination` package that you are using", "source_type": "issue", "path": "issues/14128.json", "symbol": "AssertionError: fastapi_inner_astack not found in request scope", "url": "https://github.com/fastapi/fastapi/issues/14128", "start_line": null, "end_line": null} {"id": "issue::14199", "text": "# Issue #14199: Se que ha pasado mucho tiempo, soy ingeniero y Senior en Desarrollo de Software, creo que hay demasiado factores para que un código sea más rápido, o se note lento:\nSe que ha pasado mucho tiempo, soy ingeniero y Senior en Desarrollo de Software, creo que hay demasiado factores para que un código sea más rápido, o se note lento:\r\na) El hadware.\r\nb) La internet.\r\nc) Puede haber un virus.\r\nd) La memoria esta muy ocupada,\r\ne) etc. etc.\r\n\r\nFastApi, es simplemente una arquitectura, y de paso creo desconoce que en Python puede emplearse como una consola de servicio, mediante la libreria de PyCharm, que es algo totalmente distinto API Rest. por que es una arquitectura que debes diseñar con mucho criterio. Esto le permitiría tener administración correcta de los recursos eliminar cualquier tasa latencia, si es lo que están evaluando. \r\nDe todas maneras no existe un mejor lenguaje de programación, para arquitecturas complejas de datos si no el mismo DBC, mediante procedimiento almacenado, y si quieren algo más complejo componente desarrollado en C++.\r\nCon un componente (Librería Dinámica), es que postgres puede generar Vectores Embedding. Imaginase una fuerte lógica de negocios. \r\n\r\nSaludos;\r\n\r\n_Originally posted by @Joseg212 in https://github.com/fastapi/fastapi/discussions/7320#discussioncomment-14469070_", "source_type": "issue", "path": "issues/14199.json", "symbol": "Se que ha pasado mucho tiempo, soy ingeniero y Senior en Desarrollo de Software, creo que hay demasiado factores para que un código sea más rápido, o se note lento:", "url": "https://github.com/fastapi/fastapi/issues/14199", "start_line": null, "end_line": null} {"id": "issue::142", "text": "# Issue #142: ApiKey Header documentation\nLabels: docs, confirmed, reviewed\nHi,\r\n\r\nDo you have some documentation or example regarding configuration for ApiKey (header) and how to verify it on FastAPI ?\r\n\r\nthanks in advance,\r\n\r\nRémy.\n---\nComment: I ended up working it out, here's how i solved the problem\r\n\r\nsecurity.py\r\n```python\r\nfrom fastapi import Depends, HTTPException\r\nfrom fastapi.security import APIKeyHeader\r\nfrom starlette import status\r\n\r\n\r\nX_API_KEY = APIKeyHeader(name='X-API-Key')\r\n\r\n\r\ndef check_authentication_header(x_api_key: str = Depends(X_API_KEY)):\r\n \"\"\" takes the X-API-Key header and converts it into the matching user object from the database \"\"\"\r\n\r\n # this is where the SQL query for converting the API key into a user_id will go\r\n if x_api_key == \"1234567890\":\r\n # if passes validation check, return user data for API Key\r\n # future DB query will go here\r\n return {\r\n \"id\": 1234567890,\r\n \"companies\": [1, ],\r\n \"sites\": [],\r\n }\r\n # else raise 401\r\n raise HTTPException(\r\n status_code=status.HTTP_401_UNAUTHORIZED,\r\n detail=\"Invalid API Key\",\r\n )\r\n```\r\n\r\nmain.py\r\n```python\r\n...\r\nfrom fastapi import APIRouter, Depends\r\nfrom mod\n---\nComment: if api_key is not necessary in the endpoint you can go for \r\n```Python\r\nfrom fastapi import Security\r\nfrom fastapi.security.api_key import APIKeyHeader\r\n\r\nAPI_KEY = \"1234567asdfgh\"\r\nAPI_KEY_NAME = \"X-API-KEY\"\r\n\r\napi_key_header_auth = APIKeyHeader(name=API_KEY_NAME, auto_error=True)\r\n\r\nasync def get_api_key(api_key_header: str = Security(api_key_header_auth)):\r\n if api_key_header != API_KEY:\r\n raise HTTPException(\r\n status_code=status.HTTP_401_UNAUTHORIZED,\r\n detail=\"Invalid API Key\",\r\n )\r\n\r\n@router.get('/health', dependencies=[Security(get_api_key)])\r\nasync def endpoint():\r\n```\n---\nComment: Thanks @wshayes for your help here! Much appreciated as always :tada: \r\n\r\n@meandus if you can use OAuth2, that tutorial and the project generator might help. If somehow you explicitly need something different than OAuth2, with some custom APIKeyHeader (as defined in OpenAPI), yes, it is supported, but it is not properly documented yet.\r\n\r\nI suggest you check the security section in the docs shared by William, and after knowing how it works, if you need to explicitly use `APIKeyHeader` instead of OAuth2, you can `from fastapi.security.api_key import APIKeyHeader`.\r\n\r\nAt least while I update the docs with those specifics... :grin: ", "source_type": "issue", "path": "issues/142.json", "symbol": "ApiKey Header documentation", "url": "https://github.com/fastapi/fastapi/issues/142", "start_line": null, "end_line": null} {"id": "issue::14221", "text": "# Issue #14221: Changes to _remap_definitions_and_field_mappings failing in v0.119\nHello there! I just noticed that recent changes to\n\nhttps://github.com/fastapi/fastapi/blame/cb7018d782c88b189f11d6141c8231ffb9b403b0/fastapi/_compat/v2.py#L273 in v0.119.0\n\nStarted showing up as errors like:\n\n```python\n def _remap_definitions_and_field_mappings(\n *,\n model_name_map: ModelNameMap,\n definitions: Dict[str, Any],\n field_mapping: Dict[\n Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue\n ],\n ) -> Tuple[\n Dict[Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue],\n Dict[str, Any],\n ]:\n old_name_to_new_name_map = {}\n for field_key, schema in field_mapping.items():\n model = field_key[0].type_\n if model not in model_name_map:\n continue\n new_name = model_name_map[model]\n> old_name = schema[\"$ref\"].split(\"/\")[-1]\n ^^^^^^^^^^^^^^\nE KeyError: '$ref'\n\n(...)\n\n field_mapping = {(ModelField(field_info=Body(PydanticUndefined), name='body', mode='validation'), 'validation'): {'$ref': '#/component...validation'), 'validation'): {'$ref': '#/components/schemas/xyz__apps__api__preferences__integrations__Body'}, ...}\n```\n---\nComment: Do you have an MRE?\n---\nComment: In my case the error is similar but with the `.split()` method.\n\n```\n File \".venv/lib/python3.12/site-packages/fastapi/_compat/v2.py\", line 245, in _replace_refs\n ref_name = schema[\"$ref\"].split(\"/\")[-1]\n ^^^^^^^^^^^^^^^^^^^^\nAttributeError: 'dict' object has no attribute 'split'\n```\n---\nComment: Do you have an MRE?", "source_type": "issue", "path": "issues/14221.json", "symbol": "Changes to _remap_definitions_and_field_mappings failing in v0.119", "url": "https://github.com/fastapi/fastapi/issues/14221", "start_line": null, "end_line": null} {"id": "issue::14225", "text": "# Issue #14225: docs: Fix typo in tutorial documentation\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n## Description\nFixed a minor typo in the tutorial documentation to improve clarity and readability.\n\n## Changes\n- Fixed typo: \"recieve\" → \"receive\" in `docs/en/docs/tutorial/body.md`\n- Line 45: Updated documentation for better accuracy\n\n## Checklist\n- [x] Typo verified against proper spelling\n- [x] No code changes, documentation only\n- [x] Follows existing documentation style\n\nThis small fix helps new users better understand the tutorial.", "source_type": "issue", "path": "issues/14225.json", "symbol": "docs: Fix typo in tutorial documentation", "url": "https://github.com/fastapi/fastapi/issues/14225", "start_line": null, "end_line": null} {"id": "issue::14247", "text": "# Issue #14247: Component name regression in OpenAPI spec for v0.119.0\nLabels: bug\nAdding the issue here for completeness, although most of the conversation is in the GitHub Discussion.\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14177\n\n
\n\nOriginally posted by **walsha2** October 12, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom enum import StrEnum\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, Field\n\n\nclass MessageEventType(StrEnum):\n alpha = \"alpha\"\n beta = \"beta\"\n\n\nclass MessageEvent(BaseModel):\n event_type: MessageEventType = Field(default=MessageEventType.alpha)\n output: str\n\n\nclass MessageOutput(BaseModel):\n body: str = \"\"\n events: list[MessageEvent]\n\n\nclass Message(BaseModel):\n id: str\n input: str\n output: MessageOutput\n\n\napp = FastAPI(title=\"Minimal FastAPI App\", version=\"1.0.0\")\n\n\n@app.post(\"/messages\", response_model=Message)\nasync def create_message(input_message: str) -> Message:\n return Message(\n input=input_message,\n output=MessageOutput(body=f\"Processed: {input_message}\"),\n )\n\n\nif __name__ == \"__main__\":\n openapi_spec = app.openapi()\n for c in list(openapi_spec.get(\"components\", {}).get(\"schemas\", {}).keys()):\n print(c)\n```\n\n\n### Description\n\n## Issue Summary\n\nTake the minimal example provided above, run with `fastapi==0.118.3` and it will produce:\n\n```\nHTTPValidationError\nMessage\nMessageEvent\nMessageEventType\nMessageOutput\nValidationError\n```\n\nNow run the same code with `fastapi==0.119.0` and it will produce:\n\n```\nHTTPValidationError\nMessage\nMessageEvent\nMessageEventType\nMessageOutput-Input\nMessageOutput-Output\nValidationError\n```\n\nNote how `MessageOutput` is now suffixed unnecessarily as: `MessageOutput-Input` and `MessageOutput-Output`. This seems unexpected considering the changes made between `v0.118.3` and `v0.119.0`\n\n## Minor Tweak\n\nOne minor tweak to the example and this issue goes away. Remove the enum from `MessageEvent`: \n\n```python\nclass MessageEvent(BaseModel):\n output: str\n```\n\nRun again and the issue is no longer there.\n\n```\nHTTPValidationError\nMessage\nMessageEvent\nMessageOutput\nValidationError\n```\n\n## TLDR\n\nWhy does the presence of an enum value on `MessageEvent` create a bifur\n---\nComment: It should be fixed in https://github.com/fastapi/fastapi/pull/14246, just relased in FastAPI 0.120.2. :tada: ", "source_type": "issue", "path": "issues/14247.json", "symbol": "Component name regression in OpenAPI spec for v0.119.0", "url": "https://github.com/fastapi/fastapi/issues/14247", "start_line": null, "end_line": null} {"id": "issue::14271", "text": "# Issue #14271: 🐛 0.120.3 breaks `SecurityBase` based dependencies in OpenAPI\nLabels: bug\nEdit: Added as an issue for completeness and history.\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14263\n\n
\n\nOriginally posted by **oldfielj-ansto** October 31, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom uvicorn import run\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OpenIdConnect\n\n\n_oidc = OpenIdConnect(\n openIdConnectUrl=\"https://localhost/auth/realms/test/.well-known/openid-configuration\",\n)\n\napp = FastAPI(\n title=\"My Application\",\n docs_url=\"/swagger\",\n redoc_url=\"/docs\",\n openapi_url=\"/openapi.json\",\n dependencies=(Depends(_oidc),),\n)\n\n\n@app.get(\"/\")\nasync def hello_world():\n return {\"Hello\": \"World\"}\n\n\nif __name__ == \"__main__\":\n run(app=app, port=8080)\n```\n\n\n### Description\n\n# Under FastAPI **0.120.2**\n\n* Run the example code and navigate to [http://localhost:8080/swagger](http://localhost:8080/swagger)\n* Notice that the green \"Authorize\" button is present and user can choose to authenticate a session, padlock icon is also present on root endpoint.\n* Calling the endpoint normally without user being authorized, results in expected 403 status.\n\n# Under FastAPI **0.120.3**\n\n* Run the example code and navigate to [http://localhost:8080/swagger](http://localhost:8080/swagger)\n* Notice that the green \"Authorize\" button is missing and user cannot choose to authenticate a session, padlock icon is also missing on root endpoint.\n* Calling the endpoint normally without user being authorized, results in expected 403 status.\n\nAs well as testing `Depends` I have tested with `Security` to declare the dependency, which results in the same behavior.\n\nWhat I'd expect is that FastAPI **0.120.3** displays consistent behavior with FastAPI **0.120.2**, when defining a security dependency, and that the \"Authorize\" button and padlock icon on the root endpoint would be displayed in the auto generated Swagger documentation.\n\nIt would seem that in **0.120.3**, the security section of the generated `openapi.json` file is omitted.\n\n## Under FastAPI **0.120.2**\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"My Application\",\n \"version\": \"0.1.0\"\n },\n \"paths\": {\n \"\n---\nComment: This was solved by @YuriiMotov in https://github.com/fastapi/fastapi/pull/14266. It was just released in FastAPI 0.120.4. :rocket: :tada: ", "source_type": "issue", "path": "issues/14271.json", "symbol": "🐛 0.120.3 breaks `SecurityBase` based dependencies in OpenAPI", "url": "https://github.com/fastapi/fastapi/issues/14271", "start_line": null, "end_line": null} {"id": "issue::14312", "text": "# Issue #14312: CORS Middleware and exception handler\nthe MRE is at [https://github.com/4tst/mre-exception-handler](https://github.com/4tst/mre-exception-handler). \r\n\r\nwithout `@exception_handler(ValueError)`, then will appear CORS error when request sub-route,\r\nfor more detail, please click [here](https://github.com/4tst/mre-exception-handler)", "source_type": "issue", "path": "issues/14312.json", "symbol": "CORS Middleware and exception handler", "url": "https://github.com/fastapi/fastapi/issues/14312", "start_line": null, "end_line": null} {"id": "issue::14316", "text": "# Issue #14316: `Depends(func, scope=\"function\")` with `yield` dependency exits after the request is sent instead of after the function\nLabels: bug\nAdding this issue for completeness.\n\nSolved by: https://github.com/fastapi/fastapi/pull/14301\n\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14296\n\n
\n\nOriginally posted by **guldfisk** November 5, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom types import NoneType\nfrom typing import Iterator, Annotated\n\nfrom fastapi import APIRouter\nfrom fastapi import Depends\nfrom fastapi import FastAPI\n\n\napp = FastAPI()\n\n\nclass ApplicationError(Exception): ...\n\n\ndef dependency_with_cleanup_error() -> Iterator[None]:\n yield\n raise ApplicationError()\n\n\nrouter = APIRouter(\n dependencies=[Depends(dependency_with_cleanup_error, scope=\"function\")]\n)\n\n\n@router.get(\"/broken\")\ndef broken():\n # Will return 200, and then fail in the cleanup.\n return {\"status\": \"ok\"}\n\n\n@router.get(\"/works\")\ndef endpoint(\n v: Annotated[NoneType, Depends(dependency_with_cleanup_error, scope=\"function\")],\n):\n # Will correctly return 500\n return {\"status\": \"ok\"}\n\n\napp.include_router(router)\n```\n\n\n### Description\n\nWhen using the new \"scope\" feature for yield dependencies, function scope is still cleaned up after the response is sent, if the dependency is requested in the api router, instead of on the path function.\n\nMaybe this is a feature, as in \"function\" should be interpreted as the scope of where the dependency is requested, and not always the path function, but I can't find any documentation mentioning this behavior, and in any case I'm not sure what the usecase for that would be.\n\n### Operating System\n\nLinux\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.121.0\n\n### Pydantic Version\n\n2.12.3\n\n### Python Version\n\n3.11.12\n\n### Additional Context\n\n_No response_
\n---\nComment: This was solved by https://github.com/fastapi/fastapi/pull/14301, released in FastAPI 0.121.1. 🐛 ", "source_type": "issue", "path": "issues/14316.json", "symbol": "`Depends(func, scope=\"function\")` with `yield` dependency exits after the request is sent instead of after the function", "url": "https://github.com/fastapi/fastapi/issues/14316", "start_line": null, "end_line": null} {"id": "issue::14344", "text": "# Issue #14344: AttributeError: 'dict' object has no attribute 'split'\nLabels: bug, answered\nMinimum Reproducible Example:\n\n```py\n# /// script\n# dependencies = [\n# \"pydantic\",\n# \"fastapi[standard]\",\n# \"starlette\",\n# ]\n# ///\n\nimport pydantic\nimport starlette\nimport fastapi\nfrom fastapi import FastAPI\nimport sys\nfrom pydantic import BaseModel, Field, ConfigDict\n\n# print the dependencies to stdout, one per line\nprint(f'pydantic version = {pydantic.__version__}')\nprint(f'starlette version = {starlette.__version__}')\nprint(f'fastapi version = {fastapi.__version__}')\n# print python version\nprint(f'Python version = {sys.version}')\n\n\napp = FastAPI(title='Logfire')\n\nclass ModelWithRef(BaseModel):\n ref: str = Field(validation_alias='$ref', serialization_alias='$ref')\n model_config = ConfigDict(validate_by_alias=True, serialize_by_alias=True)\n\n\n\n@app.get('/')\nasync def read_root() -> ModelWithRef:\n return ModelWithRef(ref='some-ref')\n\nprint(app.openapi())\n```\n\nRun with `uv run main.py`.\n\nError:\n\n```bash\n❯ uv run main.py \nInstalled 42 packages in 61ms\npydantic version = 2.12.4\nstarlette version = 0.49.3\nfastapi version = 0.121.1\nPython version = 3.10.15 (main, Oct 16 2024, 08:33:15) [Clang 18.1.8 ]\nTraceback (most recent call last):\n File \"/Users/marcelotryle/dev/main.py\", line 36, in \n print(app.openapi())\n File \"/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/applications.py\", line 1060, in openapi\n self.openapi_schema = get_openapi(\n File \"/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/openapi/utils.py\", line 504, in get_openapi\n field_mapping, definitions = get_definitions(\n File \"/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/main.py\", line 292, in get_definitions\n v2_field_maps, v2_definitions = v2.get_definitions(\n File \"/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py\", line 249, in get_definitions\n new_mapping, new_definitions = _remap_definitions_and_field_mappings(\n File \"/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py\", line 331, in _remap_definitions_and_field_mappings\n new_value = _replace_refs(\n File \"/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py\", line 273, in _replace_refs\n new_schema[key] = _replace_refs(\n File \"/Users/marcelotryle/.cache/uv/environments-v2/main-84bd05b9e640fe68/lib/python3.10/site-packages/fastapi/_compat/v2.py\", line 265, in _replace_refs\n ref_name = schema[\"$ref\"].split(\"/\")[-1]\nAttributeError: 'dict' object has no attribute 'split'\n```\n\n---\nComment: See also: https://github.com/fastapi/fastapi/discussions/14196\n---\nComment: This should be fixed by https://github.com/fastapi/fastapi/pull/14349, released in FastAPI 0.121.2 🎉 ", "source_type": "issue", "path": "issues/14344.json", "symbol": "AttributeError: 'dict' object has no attribute 'split'", "url": "https://github.com/fastapi/fastapi/issues/14344", "start_line": null, "end_line": null} {"id": "issue::14431", "text": "# Issue #14431: FastAPI app with `separate_input_output_schemas` disabled excludes computed fields on Pydantic models from OpenAPI output\nLabels: bug\nAdding the issue for completeness.\n\nSolved in https://github.com/fastapi/fastapi/pull/13207\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/10342\n\n
\n\nOriginally posted by **ldthorne** September 27, 2023\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nimport pytest\nfrom fastapi import FastAPI\nfrom starlette.testclient import TestClient\n\n\n@pytest.fixture(name=\"client\")\ndef get_client():\n app = FastAPI(separate_input_output_schemas=False)\n\n from pydantic import BaseModel, computed_field\n\n class Rectangle(BaseModel):\n width: int\n length: int\n\n @computed_field\n @property\n def area(self) -> int:\n return self.width * self.length\n\n @app.get(\"/\")\n def read_root() -> Rectangle:\n return Rectangle(width=3, length=4)\n\n client = TestClient(app)\n return client\n\n\ndef test_get(client: TestClient):\n response = client.get(\"/openapi.json\")\n data = response.json()\n\n rectangle_model = data[\"components\"][\"schemas\"][\"Rectangle\"][\"properties\"]\n\n assert \"area\" in rectangle_model.keys()\n```\n\n\n### Description\n\nI expect that even with `separate_input_output_schemas` set to `False` the OpenAPI schema includes computed fields declared on a Pydantic model\n\n### Operating System\n\nmacOS\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.103.1\n\n### Pydantic Version\n\n2.4.1\n\n### Python Version\n\n3.8.16\n\n### Additional Context\n\nI think it may come from [here](https://github.com/tiangolo/fastapi/blob/073e7fc950f1af24634b304afbb34bf212756dff/fastapi/_compat.py#L186)
\n---\nComment: Fixed by https://github.com/fastapi/fastapi/pull/13207\n\nAvailable in FastAPI 0.123.4, released in the next few hours.", "source_type": "issue", "path": "issues/14431.json", "symbol": "FastAPI app with `separate_input_output_schemas` disabled excludes computed fields on Pydantic models from OpenAPI output", "url": "https://github.com/fastapi/fastapi/issues/14431", "start_line": null, "end_line": null} {"id": "issue::14444", "text": "# Issue #14444: FastAPI 0.123.5 breaks async wrappers using @wraps\nLabels: bug\n(Already being worked on)\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14442\n\n
\n\nOriginally posted by **falkoschindler** December 3, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom functools import wraps\nimport uvicorn\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\ndef my_decorator(func):\n \"\"\"A decorator that wraps a sync function with an async handler.\"\"\"\n\n @wraps(func)\n async def wrapper():\n func()\n return 'OK'\n\n return wrapper\n\n@app.get('/')\n@my_decorator\ndef index():\n \"\"\"A simple sync page function.\"\"\"\n print('Hello!')\n\nif __name__ == '__main__':\n uvicorn.run(app)\n```\n\n\n### Description\n\n* Visit \"/\".\n* You'll see \"Internal Server Error\".\n* A ValueError appears:\n ```\n ValueError: [TypeError(\"'coroutine' object is not iterable\"), TypeError('vars() argument must have __dict__ attribute')]\n ```\n\nSince FastAPI 0.123.5 (PR #14434), using `functools.wraps` on an async wrapper around a sync function causes FastAPI to incorrectly treat the handler as sync, resulting in: `ValueError: [TypeError(\"'coroutine' object is not iterable\"), ...]`\n\nThe issue is that `Dependant.is_coroutine_callable` now uses `inspect.unwrap()` which follows `__wrapped__` back to the original sync function, instead of checking if the actual registered handler is async.\n\n### Operating System\n\nmacOS\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.123.5\n\n### Pydantic Version\n\n2.12.5\n\n### Python Version\n\n3.11.11\n\n### Additional Context\n\n_No response_
\n---\nComment: This should be fixed by https://github.com/fastapi/fastapi/pull/14448\n\nIt's now released in FastAPI 0.123.6 :tada: ", "source_type": "issue", "path": "issues/14444.json", "symbol": "FastAPI 0.123.5 breaks async wrappers using @wraps", "url": "https://github.com/fastapi/fastapi/issues/14444", "start_line": null, "end_line": null} {"id": "issue::14454", "text": "# Issue #14454: OAuth2 security schemes duplicated in OpenAPI, with and without scopes, when used at the router level\nLabels: bug\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nOAuth2 security schemes duplicated in OpenAPI, with and without scopes, when used at the router level\n\nReported by @Kludex on another channel 🙌 \n\n(I'm working on it)\n\n```Python\n# /// script\n# dependencies = [\n# \"fastapi[standard]==0.121.3\",\n# ]\n# ///\n\nimport json\nimport sys\nfrom typing import Annotated\n\nimport fastapi\nfrom fastapi import APIRouter, Depends, FastAPI, Security\nfrom fastapi.security import OAuth2AuthorizationCodeBearer, SecurityScopes\n\n\n# print the dependencies\nprint(f'fastapi version = {fastapi.__version__}')\nprint(f'Python version = {sys.version}')\n\n\n\napp = FastAPI()\n\noauth2_scheme = OAuth2AuthorizationCodeBearer(\n authorizationUrl='api/oauth/authorize',\n tokenUrl='/api/oauth/token',\n refreshUrl='/api/oauth/token',\n auto_error=False,\n scopes={'read': 'Read access', 'write': 'Write access'},\n)\n\nasync def get_token(\n token: Annotated[str, Depends(oauth2_scheme)],\n) -> str:\n return token\n\nAccessToken = Annotated[str, Depends(get_token, use_cache=True)]\n\n\nasync def require_oauth_scopes(security_scopes: SecurityScopes, token: AccessToken) -> None:\n pass \n\n\nasync def check_limit(token: AccessToken) -> None:\n pass\n\n# The problem is here. If we remove the dependency from the router, the schema is generated correctly in both fastapi versions.\nrouter = APIRouter(prefix='/v1', dependencies=[Depends(check_limit)])\n\nchannels_router = APIRouter(prefix='/channels', tags=['Channels'])\n@channels_router.get(\"/\", dependencies=[Security(require_oauth_scopes, scopes=['read'])])\ndef read_items():\n return {\"msg\": \"You have READ access\"}\n\n\nrouter.include_router(channels_router)\n\napp.include_router(router)\nschema = app.openapi()\npretty_schema = json.dumps(schema, indent=4)\nprint(pretty_schema)\n\n\"\"\"\nwith fastapi 0.123.7, the generated openapi schema icludes security without scopes:\n\n \"security\": [\n {\n \"OAuth2AuthorizationCodeBearer\": []\n }\n ]\n\nbut in fastapi 0.121.3, the generated openapi schema includes two items in security:\n\n \"security\": [\n {\n \"OAuth2AuthorizationCodeBearer\": []\n },\n {\n \"OAuth2AuthorizationCodeBearer\": [\n \"read\"\n ]\n }\n ]\n\"\"\"\n```\n---\nComment: That didn't fix it. 😱 \n\nWorking on it now.\n---\nComment: This was fixed by https://github.com/fastapi/fastapi/pull/14455, released in FastAPI 0.123.8 :tada: \n---\nComment: This should be fixed now in https://github.com/fastapi/fastapi/pull/14459 (strike 2 ⚾). Released in FastAPI 0.123.9 🚀 ", "source_type": "issue", "path": "issues/14454.json", "symbol": "OAuth2 security schemes duplicated in OpenAPI, with and without scopes, when used at the router level", "url": "https://github.com/fastapi/fastapi/issues/14454", "start_line": null, "end_line": null} {"id": "issue::14465", "text": "# Issue #14465: Bug with async callable class dependency in fastapi>=0.123.6\nLabels: bug\nCreating the issue for completeness.\n\nSolved by https://github.com/fastapi/fastapi/pull/14458\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14452\n\n
\n\nOriginally posted by **tanguyMichardiere** December 4, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\nfrom fastapi.dependencies.models import Dependant\nfrom uvicorn import run\n\n\nclass Dependency:\n def __init__(self):\n print(\"init\")\n\n async def __call__(self):\n print(\"call\")\n\n\nprint(Dependant(Dependency).is_coroutine_callable)\n# `True` with fastapi>=0.123.6\n# `False` with fastapi<0.123.6\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def route(*, dependency: Annotated[Dependency, Depends()]):\n await dependency()\n\n\nrun(app)\n\n# then `curl localhost:8000`\n```\n\n\n### Description\n\n```\nFile \".venv/lib/python3.14/site-packages/fastapi/dependencies/utils.py\", line 647, in solve_dependencies\n solved = await call(**solved_result.values)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nTypeError: 'Dependency' object can't be awaited\n```\n\n`fastapi.dependencies.models.Dependant` incorrectly identifies `Dependency` as a \"coroutine callable\", and `solve_dependencies` then tries to `await` an instance of `Dependency`.\n\n### Operating System\n\nmacOS\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.123.7\n\n### Pydantic Version\n\n2.12.5\n\n### Python Version\n\n3.14.1\n\n### Additional Context\n\n_No response_
\n---\nComment: Fixed by https://github.com/fastapi/fastapi/pull/14458", "source_type": "issue", "path": "issues/14465.json", "symbol": "Bug with async callable class dependency in fastapi>=0.123.6", "url": "https://github.com/fastapi/fastapi/issues/14465", "start_line": null, "end_line": null} {"id": "issue::14466", "text": "# Issue #14466: Bug with async callable class dependency in fastapi>=0.123.6\nLabels: bug\nCreating this issue for completeness.\n\nSolved by https://github.com/fastapi/fastapi/pull/14458\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14452\n\n
\n\nOriginally posted by **tanguyMichardiere** December 4, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\nfrom fastapi.dependencies.models import Dependant\nfrom uvicorn import run\n\n\nclass Dependency:\n def __init__(self):\n print(\"init\")\n\n async def __call__(self):\n print(\"call\")\n\n\nprint(Dependant(Dependency).is_coroutine_callable)\n# `True` with fastapi>=0.123.6\n# `False` with fastapi<0.123.6\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def route(*, dependency: Annotated[Dependency, Depends()]):\n await dependency()\n\n\nrun(app)\n\n# then `curl localhost:8000`\n```\n\n\n### Description\n\n```\nFile \".venv/lib/python3.14/site-packages/fastapi/dependencies/utils.py\", line 647, in solve_dependencies\n solved = await call(**solved_result.values)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nTypeError: 'Dependency' object can't be awaited\n```\n\n`fastapi.dependencies.models.Dependant` incorrectly identifies `Dependency` as a \"coroutine callable\", and `solve_dependencies` then tries to `await` an instance of `Dependency`.\n\n### Operating System\n\nmacOS\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.123.7\n\n### Pydantic Version\n\n2.12.5\n\n### Python Version\n\n3.14.1\n\n### Additional Context\n\n_No response_
\n---\nComment: Fixed by https://github.com/fastapi/fastapi/pull/14458", "source_type": "issue", "path": "issues/14466.json", "symbol": "Bug with async callable class dependency in fastapi>=0.123.6", "url": "https://github.com/fastapi/fastapi/issues/14466", "start_line": null, "end_line": null} {"id": "issue::14467", "text": "# Issue #14467: Computed fields support breaks with mixed route types\nLabels: bug\nCreating issue for completeness.\n\nFixed by https://github.com/fastapi/fastapi/pull/14453\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14451\n\n
\n\nOriginally posted by **coltonevansid** December 4, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.openapi.utils import get_openapi\nfrom pydantic import BaseModel, computed_field\n\nclass ModelWithComputedField(BaseModel):\n name: str\n\n @computed_field\n @property\n def computed_name(self) -> str:\n return f\"computed_{self.name}\"\n\nclass SimpleModel(BaseModel):\n value: str\n\napp = FastAPI()\n\n@app.get(\"/with-computed\")\ndef route_with_computed() -> ModelWithComputedField:\n \"\"\"Route returning a model with computed fields.\"\"\"\n return ModelWithComputedField(name=\"test\")\n\n@app.get(\"/without-computed\")\ndef route_without_computed() -> SimpleModel:\n \"\"\"Route returning a simple model (no computed fields).\"\"\"\n return SimpleModel(value=\"test\")\n\n\nif __name__ == \"__main__\":\n # This will raise KeyError when both routes are present\n schema = get_openapi(\n title=\"Test App\",\n version=\"1.0.0\",\n routes=app.routes,\n separate_input_output_schemas=False, # Bug only occurs with False\n )\n```\n\n\n### Description\n\nFastAPI 0.123.4 added support for computed fields in OpenAPI schemas (#13207) when `separate_input_output_schemas=False`, but the implementation has a bug where the schema generation crashes with a `KeyError` if the FastAPI app contains both:\n\n1. Routes with response models that have computed fields\n2. Routes with response models that don't have computed fields (e.g., dict responses or BaseModels without computed fields)\n\n### Expected Behavior\n\n OpenAPI schema should generate successfully with computed fields included in models that have them, regardless of mixing route types.\n\n### Current Behavior\n\n ```python\n File \"../python3.13/site-packages/fastapi/_compat/v2.py\", line 192, in get_schema_from_model_field\n json_schema = field_mapping[(field, override_mode or field.mode)]\n ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nKeyError: (ModelField(field_info=Fi\n---\nComment: Fixed by https://github.com/fastapi/fastapi/pull/14453", "source_type": "issue", "path": "issues/14467.json", "symbol": "Computed fields support breaks with mixed route types", "url": "https://github.com/fastapi/fastapi/issues/14467", "start_line": null, "end_line": null} {"id": "issue::14483", "text": "# Issue #14483: Since FastAPI 0.119.0, using `arbitrary_types_allowed=True` with custom types that define their serialization and JSON Schema breaks when generating OpenAPI\nLabels: bug\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nUsing `arbitrary_types_allowed=True` with custom types that define their serialization and JSON Schema breaks when generating OpenAPI.\n\nOriginally reported in: https://github.com/fastapi/fastapi/discussions/14184\n\nExtracting the minimal reproducible example from the comments:\n\n```Python\nfrom typing import Annotated\n\nimport numpy as np\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel, ConfigDict, WithJsonSchema, TypeAdapter\n\ntype MyNumpyArray = Annotated[\n np.ndarray, WithJsonSchema(TypeAdapter(list[float]).json_schema(), mode=\"serialization\"),\n]\n\n\nclass MyModel(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n custom_field: MyNumpyArray\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef test() -> MyModel:\n raise NotImplementedError()\n\nprint(app.openapi())\n# {'openapi': '3.1.0', 'info': {'title': 'FastAPI', 'version': '0.1.0'}, 'paths': {'/': {'get': {'summary': 'Test', 'operationId': 'test__get', 'responses': {'200': {'description': 'Successful Response', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/MyModel'}}}}}}}}, 'components': {'schemas': {'MyModel': {'properties': {'custom_field': {'$ref': '#/components/schemas/MyNumpyArray'}}, 'type': 'object', 'required': ['custom_field'], 'title': 'MyModel'}, 'MyNumpyArray': {'items': {'type': 'number'}, 'type': 'array'}}}}\n```\n\nShould be solved by: https://github.com/fastapi/fastapi/pull/14482\n---\nComment: It should be fixed in https://github.com/fastapi/fastapi/pull/14482, available in FastAPI 0.124.1, just released. :tada: ", "source_type": "issue", "path": "issues/14483.json", "symbol": "Since FastAPI 0.119.0, using `arbitrary_types_allowed=True` with custom types that define their serialization and JSON Schema breaks when generating OpenAPI", "url": "https://github.com/fastapi/fastapi/issues/14483", "start_line": null, "end_line": null} {"id": "issue::14484", "text": "# Issue #14484: In FastAPI 0.123.7, annotations from code imported in `if TYPE_CHECKING` could break\nLabels: bug\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nIn FastAPI 0.123.7, annotations from code imported in `if TYPE_CHECKING` could break\n\nOriginally discussed in https://github.com/fastapi/fastapi/discussions/14464 and https://github.com/fastapi/fastapi/pull/11355\n\nMinimal example extracted from the discussion:\n\n```Python\n# /// script\n# requires-python = \"==3.14.*\"\n# dependencies = [\n# \"fastapi==0.123.7\",\n# \"uvicorn\",\n# ]\n# ///\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Annotated\n\nfrom fastapi import Depends, FastAPI\n\nif TYPE_CHECKING:\n from collections.abc import AsyncGenerator\n\napp = FastAPI()\n\n\nclass DummyClient:\n async def get_people(self) -> list:\n return [\"John Doe\", \"Jane Doe\"]\n\n async def close(self) -> None: ...\n\n\nasync def get_client() -> AsyncGenerator[DummyClient, None]:\n client = DummyClient()\n yield client\n await client.close()\n\n\nClient = Annotated[DummyClient, Depends(get_client)]\n\n\n@app.get(\"/\")\nasync def get_people(client: Client) -> list:\n return await client.get_people()\n\n\nif __name__ == \"__main__\":\n import uvicorn\n uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n```\n\nHandled in https://github.com/fastapi/fastapi/pull/14485\n---\nComment: This is fixed by https://github.com/fastapi/fastapi/pull/14485, available in FastAPI 0.124.2, just released. 🎉 ", "source_type": "issue", "path": "issues/14484.json", "symbol": "In FastAPI 0.123.7, annotations from code imported in `if TYPE_CHECKING` could break", "url": "https://github.com/fastapi/fastapi/issues/14484", "start_line": null, "end_line": null} {"id": "issue::14493", "text": "# Issue #14493: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14493.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14493", "start_line": null, "end_line": null} {"id": "issue::14494", "text": "# Issue #14494: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14494.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14494", "start_line": null, "end_line": null} {"id": "issue::14496", "text": "# Issue #14496: Performance issue\nSlow response under load\n---\nComment: @LakshmiMandal, please, stop opening issue or you will be banned!", "source_type": "issue", "path": "issues/14496.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14496", "start_line": null, "end_line": null} {"id": "issue::14497", "text": "# Issue #14497: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14497.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14497", "start_line": null, "end_line": null} {"id": "issue::14498", "text": "# Issue #14498: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14498.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14498", "start_line": null, "end_line": null} {"id": "issue::14499", "text": "# Issue #14499: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14499.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14499", "start_line": null, "end_line": null} {"id": "issue::14500", "text": "# Issue #14500: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14500.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14500", "start_line": null, "end_line": null} {"id": "issue::14501", "text": "# Issue #14501: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14501.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14501", "start_line": null, "end_line": null} {"id": "issue::14502", "text": "# Issue #14502: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14502.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14502", "start_line": null, "end_line": null} {"id": "issue::14503", "text": "# Issue #14503: Performance issue\nSlow response under load", "source_type": "issue", "path": "issues/14503.json", "symbol": "Performance issue", "url": "https://github.com/fastapi/fastapi/issues/14503", "start_line": null, "end_line": null} {"id": "issue::14508", "text": "# Issue #14508: Discriminated Unions Break When Wrapped in Annotated[Union, Body(...)] in FastAPI 0.124.1+\nLabels: bug\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/14495\n\n
\n\nOriginally posted by **atlasale** December 11, 2025\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom typing import Annotated, Union\r\nfrom pydantic import BaseModel, Tag, Discriminator\r\nfrom fastapi import FastAPI, Body\r\n\r\nclass Cat(BaseModel):\r\n pet_type: str = \"cat\"\r\n meows: int\r\n\r\nclass Dog(BaseModel):\r\n pet_type: str = \"dog\"\r\n barks: float\r\n\r\ndef get_pet_type(v):\r\n if isinstance(v, dict):\r\n return v.get(\"pet_type\", \"\")\r\n return getattr(v, \"pet_type\", \"\")\r\n\r\n# Define discriminated union\r\nPet = Annotated[\r\n Union[\r\n Annotated[Cat, Tag(\"cat\")],\r\n Annotated[Dog, Tag(\"dog\")]\r\n ],\r\n Discriminator(get_pet_type)\r\n]\r\n\r\napp = FastAPI()\r\n\r\n# ✅ THIS WORKS in 0.124.1+\r\n@app.post(\"/pet/works\")\r\nasync def create_pet_works(pet: Pet = Body(...)):\r\n return pet\r\n\r\n# ❌ THIS BREAKS in 0.124.1+ (worked in 0.124.0)\r\n@app.post(\"/pet/broken\")\r\nasync def create_pet_broken(pet: Annotated[Pet, Body(...)]):\r\n return pet\n```\n\n\n### Description\n\nI'm experiencing a breaking change when upgrading from FastAPI 0.124.0 to\r\n 0.124.1/0.124.2.\r\n\r\n What works:\r\n\r\n - FastAPI 0.124.0 - Both endpoint patterns work correctly\r\n - FastAPI 0.124.1+ - Only pet: Pet = Body(...) works\r\n\r\n What breaks:\r\n\r\n - FastAPI 0.124.1+ - The pattern pet: Annotated[Pet, Body(...)] fails\r\n with:\r\n\r\n pydantic.errors.PydanticUserError: `Tag` not provided for choice {\r\n 'type': 'tagged-union',\r\n 'choices': {\r\n 'cat': {'type': 'definition-ref', 'metadata':\r\n {'pydantic_internal_union_tag_key': 'cat'}},\r\n 'dog': {'type': 'definition-ref', 'metadata':\r\n {'pydantic_internal_union_tag_key': 'dog'}}\r\n },\r\n 'discriminator': \r\n } used with `Discriminator`\r\n\r\n For further information visit\r\n https://errors.pydantic.dev/2.12/u/callable-discriminator-no-tag\r\n\r\n Root Cause: This appears to be caused by commit 42b250d (https://github.com\r\n /fastapi/fastapi/commit/42b250d14dd42d3c0c24dd085fa53878172a985f) which\r\n fixed arbitrary_types_allowed=True but introduced a regr\n---\nComment: This is fixed in https://github.com/fastapi/fastapi/pull/14512, it is now available in FastAPI 0.124.3 :tada: ", "source_type": "issue", "path": "issues/14508.json", "symbol": "Discriminated Unions Break When Wrapped in Annotated[Union, Body(...)] in FastAPI 0.124.1+", "url": "https://github.com/fastapi/fastapi/issues/14508", "start_line": null, "end_line": null} {"id": "issue::14680", "text": "# Issue #14680: StreamingResponse doc example needs correction\n[`StreamingResponse` docs](https://fastapi.tiangolo.com/advanced/custom-response/?h=responses#streamingresponse) state:\n\n> Takes an async generator or a normal generator/iterator\n\nHowever based on https://github.com/Kludex/starlette/discussions/1776#discussioncomment-3207518 `async` generetors need something `await`ed to work:\n\n```py\nimport asyncio\nfrom time import sleep\nfrom fastapi import FastAPI\nfrom fastapi.responses import StreamingResponse\n\napp = FastAPI()\n\nasync def fake_video_streamer():\n for i in range(10):\n sleep(0.1)\n yield b\"some fake video bytes\"\n # await asyncio.sleep(0) # <-- uncomment to fix example\n\n@app.get(\"/\")\nasync def main():\n \"\"\"\n this is as per\n https://fastapi.tiangolo.com/advanced/custom-response/?h=responses#streamingresponse\n but does not to work (blocks for 1 sec, then returns all chunks at once):\n curl -sNo- localhost:8000\n wget -qO- localhost:8000\n \"\"\"\n return StreamingResponse(fake_video_streamer())\n```\n\n- `uvicorn==0.40.0`\n- `fastapi==0.128.0`\n---\nComment: fixed in #14681\n---\nComment: It seems based on https://github.com/Kludex/starlette/discussions/1776#discussioncomment-3207518 that `await asyncio.sleep(0)` needs to be added to the documented example to work.\n---\nComment: Hi @casperdcl, thanks for raising this. I understand the issue and the root cause with async generators blocking without an await. If the fix isn’t already finalized, I’d be happy to work on this or help refine the docs/validate the example. Please let me know if that works for you.", "source_type": "issue", "path": "issues/14680.json", "symbol": "StreamingResponse doc example needs correction", "url": "https://github.com/fastapi/fastapi/issues/14680", "start_line": null, "end_line": null} {"id": "issue::1476", "text": "# Issue #1476: Improve `HTTPDigest` implementation\nLabels: feature, confirmed, reviewed\n### Describe the bug\r\n\r\n`fastapi.security.HTTPDigest` is actually not implementing HTTP Digest Access Authentication as specified by [RFC 7616](https://tools.ietf.org/html/rfc7616) or (the obsoleted) [RFC 2617](https://tools.ietf.org/html/rfc2617).\r\n\r\n### To Reproduce\r\n\r\nRead the relevant RFCs or maybe try it out using `curl --digest`.\r\n\r\n### Expected behavior\r\n\r\nExactly as specified in [RFC 7616](https://tools.ietf.org/html/rfc7616).\n---\nComment: Would love to see this implemented as well, trying to replicate a device for testing that uses digest, and it's been quite the headache.\r\n\r\nThat being said, I tried getting #9825 working, and it appears it doesn't work with `pydantic` when the version is ^2, but I was able to get it working with `1.10.12`, is this worth updating to the latest `pydantic` version?\n---\nComment: @UpstreamData I've fixed the PR to properly support both `pydantic` ^2 and `1.10` -- was an issue with the model config; decided to do away with arbitrary types all together. Tested locally and the quick `curl` test works for both versions.\n---\nComment: I added docs to the digest classes explaining that they are a stub to connect with OpenAPI, and the rest of the implementation would need to be done in user code.\n\nIt is more or less just extending HTTP Basic auth, but using MD5 which is cryptographically weak, and still vulnerable to man-in-the-middle attacks when used without HTTPS, which is what it attempts to overcome avoiding sending a password in plaintext.\n\nBut nowadays using HTTPS is expected almost everywhere, and authentication using tokens or similar methods.\n\nSo, I don't think it makes sense to spend a long time doing a thorough implementation (that then also needs to be maintained) for a semi-deprecated standard.\n\nI'll wait to see if there are new and common use cases that require it to revisit it. But for now, I'll pass on this request. ☕ \n\n---\n\nHaving issues open for specific things is becoming problematic as they attract AI slop PRs, so I'm having to closing some PRs for cleanup. ☕", "source_type": "issue", "path": "issues/1476.json", "symbol": "Improve `HTTPDigest` implementation", "url": "https://github.com/fastapi/fastapi/issues/1476", "start_line": null, "end_line": null} {"id": "issue::14787", "text": "# Issue #14787: Add Arabic (العربية) documentation translation\n### Description\n\nFastAPI currently supports translations in 13 languages (de, en, es, fr, ja, ko, pt, ru, tr, uk, zh, zh-hant), but Arabic (العربية) is not yet available.\n\nArabic is spoken by over 400 million people and is widely used in the growing tech communities across the Middle East and North Africa (MENA region). Many Arabic-speaking developers use FastAPI in production, and having documentation in Arabic would significantly lower the barrier to entry.\n\n### What I'd like to contribute\n\nI'd like to start an Arabic translation following the [Contributing to translations](https://fastapi.tiangolo.com/contributing/#translations) guide. I would begin with:\n\n1. `docs/ar/docs/index.md` (landing page)\n2. `docs/ar/docs/tutorial/first-steps.md` (getting started)\n3. `docs/ar/docs/tutorial/path-params.md` (path parameters)\n\n### Notes\n\n- Arabic is an RTL (right-to-left) language, which may require some CSS/layout considerations in the MkDocs theme\n- I'm a native Arabic speaker and active FastAPI user (using it in a healthcare RAG application)\n- Happy to coordinate with other Arabic-speaking contributors\n\nWould love to get approval before starting work on this. Thanks! 🚀", "source_type": "issue", "path": "issues/14787.json", "symbol": "Add Arabic (العربية) documentation translation", "url": "https://github.com/fastapi/fastapi/issues/14787", "start_line": null, "end_line": null} {"id": "issue::14810", "text": "# Issue #14810: estoque ses\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n_No response_\n---\nComment: wat", "source_type": "issue", "path": "issues/14810.json", "symbol": "estoque ses", "url": "https://github.com/fastapi/fastapi/issues/14810", "start_line": null, "end_line": null} {"id": "issue::14888", "text": "# Issue #14888: Bug with complex fields (`list[str]`) inside `BaseModel`\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n## Summary\nWhen \"complex\" (e.g., `list[str]`) field is definied inside `BaseModel`, it doesn't get parsed.\n\n## MRE1\n### Summary\nExample when \"complex\" field defined in `BaseModel` doesn't get parsed.\n\n#### Code\n```python\nfrom typing import Annotated\nimport uvicorn\nfrom fastapi import Depends, FastAPI, Query\nfrom pydantic import BaseModel\n\nclass MyParams(BaseModel):\n size: Annotated[int | None, Query()] = None\n field: Annotated[list[str] | None, Query()] = None\n\napp = FastAPI()\n\n@app.get(\"/items\")\nasync def get_items(\n params: Annotated[MyParams, Depends()],\n) -> None:\n print(\"params: \", params)\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"127.0.0.1\", port=8000)\n```\n\n#### Request:\n```bash\ncurl --location 'localhost:8000/items?size=100&field=foo&field=bar'\n```\n\n#### Expected:\n```text\nparams: size=100 field=foo,bar\nINFO: 127.0.0.1:54972 - \"GET /items?size=100&field=foo&field=bar HTTP/1.1\" 200 OK\n```\n\n#### Actual:\n```text\nparams: size=100 field=None\nINFO: 127.0.0.1:54972 - \"GET /items?size=100&field=foo&field=bar HTTP/1.1\" 200 OK\n```\n\n## MRE2\n### Summary\nExample when \"complex\" field is moved from `BaseModel` to a separate attribute and gets parsed.\n\n#### Code\n```python\nfrom typing import Annotated\nimport uvicorn\nfrom fastapi import Depends, FastAPI, Query\nfrom pydantic import BaseModel\n\nclass MyParams(BaseModel):\n size: Annotated[int | None, Query()] = None\n\napp = FastAPI()\n\n@app.get(\"/items\")\nasync def get_items(\n params: Annotated[MyParams, Depends()],\n field: Annotated[list[str] | None, Query()] = None,\n) -> None:\n print(\"params: \", params)\n print(\"field: \", field)\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host=\"127.0.0.1\", port=8000)\n```\n\n#### Request:\n```bash\ncurl --location 'localhost:8000/items?size=100&field=foo&field=bar'\n```\n\n#### Expected:\n```text\nparams: size=100\nfield: ['foo', 'bar']\nINFO: 127.0.0.1:55020 - \"GET /items?size=100&field=foo&field=bar HTTP/1.1\" 200 OK\n```\n\n#### Actual:\n```text\nparams: size=100\nfield: ['foo', 'bar']\nINFO: 127.0.0.1:55020 - \"GET /items?size=100&field=foo&field=bar HTTP/1.1\" 200 OK\n```\n\n### Versions\n```text\n├── fastapi v0.128.7\n│ ├── annotated-doc v0.0.4\n│ ├── pydantic v2.12.5\n│ │ ├── annotated-types v0.7.0\n│ │ ├── pydantic-core v2.41.5\n│ │ │ └── typing-extensions v4.15.0\n│ │ ├── typing-extensions v4.15.0\n│ │ ├── typing-inspection v0.4.2\n│ │ │ └── typing-extensions v4.15.0\n│ │ └── email-validator v2.3.0 (extra: email)\n│ │ ├── dnspython v2.8.0\n│ │ └── idna v3.11\n│ ├── starlette v0.52.1\n│ │ ├── anyio v4.12.1 (*)\n│ │ └── typing-extensions v4.15.0\n│ ├── typing-extensions v4.15.0\n│ └── typing-inspection v0.4.2 (*)\n```\n\n---\nComment: @YuriiMotov please review\n---\nComment: @Danipulok, please follow the rules!\nOpen discussion, nut issue", "source_type": "issue", "path": "issues/14888.json", "symbol": "Bug with complex fields (`list[str]`) inside `BaseModel`", "url": "https://github.com/fastapi/fastapi/issues/14888", "start_line": null, "end_line": null} {"id": "issue::14988", "text": "# Issue #14988: Dependency keeps going after response returns when there exists any backgroud tasks.\n### Privileged issue\n\n- [ ] #14989\n\n### Issue Content\n\n```python\nimport asyncio\n\nfrom fastapi import Depends, BackgroundTasks, FastAPI\nfrom fastapi.responses import PlainTextResponse\n\n\napp = FastAPI()\n\nasync def dep():\n yield\n print(\"dep done\")\n\nasync def task():\n await asyncio.sleep(5)\n print(\"task done\")\n\n@app.get(\"/test\", response_class=PlainTextResponse, tags=[\"test\"], dependencies=[Depends(dep)])\nasync def test(bk: BackgroundTasks):\n bk.add_task(task)\n return \"OK\"\n```\n\nWhen access test endpoint, Both fastapi 0.128.0 and 0.133.0 have this behavior:\n\n1. Response returns\n2. print \"dep done\"\n3. print \"task done\".\n\nBut in fastapi 0.115.12:\n\n1. print \"dep done\"\n2. Response returns\n3. print \"task done\".\n\nWhen the dependency is a database transaction, transaction is not committed after response returns, data changes are not accessable before backgroud tasks completion.", "source_type": "issue", "path": "issues/14988.json", "symbol": "Dependency keeps going after response returns when there exists any backgroud tasks.", "url": "https://github.com/fastapi/fastapi/issues/14988", "start_line": null, "end_line": null} {"id": "issue::14989", "text": "# Issue #14989: I'm @tiangolo or he asked me directly to create an issue here.", "source_type": "issue", "path": "issues/14989.json", "symbol": "I'm @tiangolo or he asked me directly to create an issue here.", "url": "https://github.com/fastapi/fastapi/issues/14989", "start_line": null, "end_line": null} {"id": "issue::15000", "text": "# Issue #15000: Consider speciesist language in documentation\n## Summary\r\n\r\nWhile reviewing the FastAPI codebase and documentation for inclusive language, I identified several instances of terminology that could be updated to use more inclusive, non-speciesist alternatives. This aligns with broader industry trends toward inclusive language (similar to efforts around master/main, blacklist/allowlist, etc.).\r\n\r\n## Findings\r\n\r\n### 1. `Blacklist` / `Whitelist` in `fastapi/param_functions.py` (14 instances)\r\n\r\nThe docstrings for `validation_alias` and `serialization_alias` parameters across all parameter functions (`Path`, `Query`, `Header`, `Cookie`, `Body`, `Form`, `File`) use the terms `'Whitelist' validation step` and `'Blacklist' validation step`.\r\n\r\n**Example** (lines 62, 71):\r\n\r\n```python\r\nvalidation_alias: Annotated[\r\n str | AliasPath | AliasChoices | None,\r\n Doc(\r\n \"\"\"\r\n 'Whitelist' validation step. The parameter field will be the single one\r\n allowed by the alias or set of aliases defined.\r\n \"\"\"\r\n ),\r\n] = None,\r\nserialization_alias: Annotated[\r\n str | None,\r\n Doc(\r\n \"\"\"\r\n 'Blacklist' validation step. The vanilla parameter field will be the\r\n single one of the alias' or set of aliases' fields and all the other\r\n fields will be ignored at serialization time.\r\n \"\"\"\r\n ),\r\n] = None,\r\n```\r\n\r\n**Suggested alternatives:** `'Allowlist'` / `'Denylist'` (or `'Inclusion'` / `'Exclusion'`)\r\n\r\n### 2. `monkey patching` in `fastapi/dependencies/utils.py` (line 575)\r\n\r\n```python\r\n# people might be monkey patching this function (although that's not supported)\r\n```\r\n\r\nThis is a widely-used technical term with origins rooted in animal exploitation metaphors. The alternative **\"runtime patching\"** is equally clear and more descriptive of what actually happens.\r\n\r\n**Suggested alternative:** `runtime patching`\r\n\r\n### 3. Default branch name `master`\r\n\r\nThe repository still uses `master` as its default branch. While not speciesist per se, this is related to the broader inclusive language conversation. GitHub's own default changed to `main` in 2020, and many major projects (including Python, Django, Redis, and others) have already made this transition.\r\n\r\n**Suggested alternative:** `main`\r\n\r\nThis would also affect approximately 15+ hardcoded references to `master` in documentation links throughout `docs/en/` and translated docs.\r\n\r\n## Why this matters\r\n\r\nLanguage shapes thought. Terms like \"blacklist/whitelist\" carry racial connotations, while terms rooted in the exploitation of animals (\"monkey patching,\" \"guinea pig,\" \"canary deployment,\" etc.) normalize the idea that animals exist as tools for human use. The tech industry has increasingly recognized the importance of inclusive terminology -- this is a small change with outsized symbolic value.\r\n\r\nFastAPI is used by millions of developers worldwide. Updates to its terminology signal that inclusive language is a community value.\r\n\r\n## Proposed changes\r\n\r\n| Current | Suggested | Location |\r\n|---|---", "source_type": "issue", "path": "issues/15000.json", "symbol": "Consider speciesist language in documentation", "url": "https://github.com/fastapi/fastapi/issues/15000", "start_line": null, "end_line": null} {"id": "issue::15002", "text": "# Issue #15002: Consider speciesist language in documentation\n## Summary\n\nWhile reviewing the FastAPI codebase and documentation for inclusive language, I identified several instances of terminology that could be updated to use more inclusive, non-speciesist alternatives. This aligns with broader industry trends toward inclusive language (similar to efforts around master/main, blacklist/allowlist, etc.).\n\n## Findings\n\n### 1. Blacklist / Whitelist in fastapi/param_functions.py (14 instances)\n\nThe docstrings for validation_alias and serialization_alias parameters across all parameter functions (Path, Query, Header, Cookie, Body, Form, File) use the terms Whitelist validation step and Blacklist validation step.\n\nExample (lines 62, 71):\n\n\\\nSuggested alternatives: Allowlist / Denylist (or Inclusion / Exclusion)\n\n### 2. monkey patching in fastapi/dependencies/utils.py (line 575)\n\n\\\nThis is a widely-used technical term with origins rooted in animal exploitation metaphors. The alternative runtime patching is equally clear and more descriptive of what actually happens.\n\nSuggested alternative: runtime patching\n\n### 3. Default branch name master\n\nThe repository still uses master as its default branch. While not speciesist per se, this is related to the broader inclusive language conversation. GitHub's own default changed to main in 2020, and many major projects (including Python, Django, Redis, and others) have already made this transition.\n\nSuggested alternative: main\n\nThis would also affect approximately 15+ hardcoded references to master in documentation links throughout docs/en/ and translated docs.\n\n## Why this matters\n\nLanguage shapes thought. Terms like blacklist/whitelist carry racial connotations, while terms rooted in the exploitation of animals (monkey patching, guinea pig, canary deployment, etc.) normalize the idea that animals exist as tools for human use. The tech industry has increasingly recognized the importance of inclusive terminology -- this is a small change with outsized symbolic value.\n\nFastAPI is used by millions of developers worldwide. Updates to its terminology signal that inclusive language is a community value.\n\n## Proposed changes\n\n| Current | Suggested | Location |\n|---|---|---|\n| Whitelist | Allowlist | fastapi/param_functions.py (7 instances) |\n| Blacklist | Denylist | fastapi/param_functions.py (7 instances) |\n| monkey patching | runtime patching | fastapi/dependencies/utils.py |\n| master branch | main | Repository default branch + docs links |\n\nI am happy to submit a PR for any or all of these changes if the maintainers are open to it.\n\n## References\n\n- [GitHub renaming default branch to main](https://github.com/github/renaming)\n- [IETF: Terminology, Power and Oppressive Language](https://datatracker.ietf.org/doc/html/draft-knodel-terminology)\n- [Inclusive Naming Initiative](https://inclusivenaming.org/)", "source_type": "issue", "path": "issues/15002.json", "symbol": "Consider speciesist language in documentation", "url": "https://github.com/fastapi/fastapi/issues/15002", "start_line": null, "end_line": null} {"id": "issue::15049", "text": "# Issue #15049: Add .cursorrules file to help Cursor IDE users follow FastAPI conventions\n## Proposal: Add a `.cursorrules` file for Cursor IDE contributors\n\nHi\\! I noticed the FastAPI repo does not have a `.cursorrules` file. FastAPI is hugely popular and many contributors use [Cursor IDE](https://cursor.sh). A `.cursorrules` file tells Cursor's AI assistant about the project's conventions, helping contributors write matching code from the start.\n\n### What `.cursorrules` does\n\nIt instructs Cursor's AI to follow your project's:\n- Coding style and naming conventions\n- Architectural patterns (dependency injection, Pydantic models, etc.)\n- Testing approach\n- Common patterns to follow and pitfalls to avoid\n\nFor FastAPI specifically this is valuable since Pydantic v2 + async patterns have non-obvious conventions new contributors often get wrong.\n\n### What I'd suggest\n\nA `.cursorrules` for this repo could cover:\n- Pydantic v2 model patterns (`model_config = ConfigDict(...)`, validators)\n- `Depends()` injection patterns\n- Async-first with `asyncio.gather()` for concurrent operations\n- `pytest` + `httpx.AsyncClient` testing patterns\n- Strict type annotation conventions (no implicit `Any`)\n\nI maintain an open-source collection at https://github.com/survivorforge/cursor-rules that includes a [python-fastapi rules file](https://github.com/survivorforge/cursor-rules/tree/main/rules/python-fastapi) that could serve as a starting point.\n\n### Options\n\n1. **I can submit a PR** with a `.cursorrules` tailored to FastAPI's codebase conventions\n2. **You can adapt** the [python-fastapi rules](https://github.com/survivorforge/cursor-rules/tree/main/rules/python-fastapi) from our collection\n3. **No action needed** if you prefer to keep the repo lightweight\n\nFree contribution, no strings attached.", "source_type": "issue", "path": "issues/15049.json", "symbol": "Add .cursorrules file to help Cursor IDE users follow FastAPI conventions", "url": "https://github.com/fastapi/fastapi/issues/15049", "start_line": null, "end_line": null} {"id": "issue::15085", "text": "# Issue #15085: Docs: No guidance on Pandas DataFrame serialization — numpy types cause JSON errors\n## Summary\n\nThe `encoder.md` tutorial covers `jsonable_encoder` for Pydantic models and Python `datetime` objects, but does not mention **Pandas DataFrames** — a very common data source in FastAPI apps (ML pipelines, analytics APIs, data science backends).\n\n## The Problem\n\nWhen returning data from a Pandas DataFrame using `.to_dict(orient=\"records\")`, columns retain **NumPy types** (`numpy.int64`, `numpy.float64`, `numpy.nan`, `pandas.NaT`). These are **not natively JSON serializable**, causing runtime errors:\n\n```\nTypeError: Object of type int64 is not JSON serializable\n```\n\nOr silently producing invalid JSON with `NaN` values (not valid JSON spec).\n\n## Minimal Reproduction\n\n```python\nfrom fastapi import FastAPI\nimport pandas as pd\n\napp = FastAPI()\n\n@app.get(\"/data\")\ndef get_data():\n df = pd.DataFrame({\n \"count\": [1, 2, 3], # numpy.int64\n \"score\": [1.5, float(\"nan\"), 3.0], # numpy.float64 + NaN\n })\n return df.to_dict(orient=\"records\") # 💥 NaN breaks JSON, int64 may fail\n```\n\n## Expected\n\nDocs should show the safe pattern for returning Pandas DataFrames:\n\n```python\nfrom fastapi.encoders import jsonable_encoder\n\n@app.get(\"/data\")\ndef get_data():\n df = pd.DataFrame({...})\n # ✅ Converts numpy types + handles NaT/NaN -> null\n return jsonable_encoder(df.to_dict(orient=\"records\"))\n```\n\nOr alternatively using pandas native JSON serialization:\n\n```python\nimport json\n\n@app.get(\"/data\")\ndef get_data():\n df = pd.DataFrame({...})\n # ✅ pandas handles numpy types natively\n return json.loads(df.to_json(orient=\"records\", date_format=\"iso\"))\n```\n\n## Why This Matters\n\nPandas is extremely common in FastAPI backends (ML inference APIs, analytics dashboards, data pipelines). This silent failure is a frequent gotcha for developers and is not covered anywhere in the current docs.\n\nProposing a small addition to `docs/en/docs/tutorial/encoder.md` under a new **\"Working with Pandas DataFrames\"** section.\n\n## Environment\n\n- FastAPI: latest\n- Python: 3.11\n- pandas: 2.x\n- Hit this while building a healthcare analytics REST API backed by a pandas DataFrame\n\n", "source_type": "issue", "path": "issues/15085.json", "symbol": "Docs: No guidance on Pandas DataFrame serialization — numpy types cause JSON errors", "url": "https://github.com/fastapi/fastapi/issues/15085", "start_line": null, "end_line": null} {"id": "issue::15111", "text": "# Issue #15111: Injected BackgroundTasks silently discarded when Response has its own background\n### Description\n\nWhen an endpoint uses both dependency-injected `BackgroundTasks` and returns a `Response` object that already has its own `background` attribute set, the injected background tasks are silently discarded. This causes tasks to disappear without any error, warning, or indication of what went wrong, which can lead to very hard-to-debug issues in production.\n\n### Example\n\n```python\nfrom fastapi import FastAPI, BackgroundTasks\nfrom starlette.responses import Response\nfrom starlette.background import BackgroundTask\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def endpoint(tasks: BackgroundTasks):\n tasks.add_task(lambda: print(\"This will NOT be printed\"))\n return Response(\n content=\"Custom response\",\n background=BackgroundTask(lambda: print(\"Only this will be printed\")),\n )\n```\n\nIn this case, `tasks.add_task(...)` silently does nothing because the returned `Response` already has a `background` and FastAPI does not attach the injected tasks.\n\n### Current behavior\n\nThe dependency-injected `BackgroundTasks` are silently dropped with no warning or error.\n\n### Expected behavior\n\nAt minimum, a `UserWarning` should be emitted so the developer knows their injected background tasks are being discarded. The warning message should explain how to resolve the conflict.\n\n### Root cause\n\nIn `fastapi/routing.py`, the request handler checks `raw_response.background is None` before attaching the injected tasks. If the response already has a background, the injected tasks are simply ignored:\n\n```python\nif isinstance(raw_response, Response):\n if raw_response.background is None:\n raw_response.background = solved_result.background_tasks\n response = raw_response\n```\n\n### Related\n\nThis is related to the discussion in #11215. Maintainer @YuriiMotov [suggested](https://github.com/fastapi/fastapi/issues/11215#issuecomment-3124203048) adding a warning in such cases, which is the approach taken in the accompanying PR.\n\n### Environment\n\n- FastAPI version: 0.135.1 (current master)\n- Python version: 3.11+", "source_type": "issue", "path": "issues/15111.json", "symbol": "Injected BackgroundTasks silently discarded when Response has its own background", "url": "https://github.com/fastapi/fastapi/issues/15111", "start_line": null, "end_line": null} {"id": "issue::15118", "text": "# Issue #15118: 🌐 Urdu (اردو) Documentation Translation — Review Tracker\n## 🌐 Urdu (اردو) Documentation Translation — Review Tracker\n\nThis issue tracks the review progress for the complete Urdu documentation translation added in #15117.\n\n### 📖 Preview the docs\n\n👉 **[Preview Urdu Docs](https://d914cf26.fastapitiangolo.pages.dev/ur/)**\n\n### 🤝 How to help review\n\nThis is a **collaborative review effort** — you don't need to review everything! Pick one or a few pages, review them, and check them off. This way the workload is distributed across multiple reviewers.\n\n**Review guidelines:**\n- Check the translation for accuracy and natural Urdu flow\n- Ensure technical terms are kept in English (as per the [translation prompt](https://github.com/fastapi/fastapi/blob/feat/urdu-docs-translation/docs/ur/llm-prompt.md))\n- Verify code blocks and links are intact\n- Comment on the PR with any corrections needed, referencing the file path\n- Once a page looks good, check it off below\n\n---\n\n### Pages to Review\n\n#### Root Pages\n- [ ] [index.md](https://d914cf26.fastapitiangolo.pages.dev/ur/) — مرکزی صفحہ (Landing Page)\n- [ ] [features.md](https://d914cf26.fastapitiangolo.pages.dev/ur/features/) — خصوصیات\n- [ ] [python-types.md](https://d914cf26.fastapitiangolo.pages.dev/ur/python-types/) — Python Types\n- [ ] [async.md](https://d914cf26.fastapitiangolo.pages.dev/ur/async/) — Async / Concurrency\n- [ ] [benchmarks.md](https://d914cf26.fastapitiangolo.pages.dev/ur/benchmarks/) — بینچ مارکس\n- [ ] [alternatives.md](https://d914cf26.fastapitiangolo.pages.dev/ur/alternatives/) — متبادل، تحریک اور موازنے\n- [ ] [history-design-future.md](https://d914cf26.fastapitiangolo.pages.dev/ur/history-design-future/) — تاریخ، ڈیزائن اور مستقبل\n- [ ] [help-fastapi.md](https://d914cf26.fastapitiangolo.pages.dev/ur/help-fastapi/) — FastAPI کی مدد کریں\n- [ ] [environment-variables.md](https://d914cf26.fastapitiangolo.pages.dev/ur/environment-variables/) — ماحولیاتی متغیرات\n- [ ] [virtual-environments.md](https://d914cf26.fastapitiangolo.pages.dev/ur/virtual-environments/) — ورچوئل ماحول\n- [ ] [editor-support.md](https://d914cf26.fastapitiangolo.pages.dev/ur/editor-support/) — ایڈیٹر سپورٹ\n- [ ] [fastapi-cli.md](https://d914cf26.fastapitiangolo.pages.dev/ur/fastapi-cli/) — FastAPI CLI\n- [ ] [project-generation.md](https://d914cf26.fastapitiangolo.pages.dev/ur/project-generation/) — پروجیکٹ جنریشن\n\n#### About\n- [ ] [about/index.md](https://d914cf26.fastapitiangolo.pages.dev/ur/about/) — FastAPI کے بارے میں\n\n#### Learn\n- [ ] [learn/index.md](https://d914cf26.fastapitiangolo.pages.dev/ur/learn/) — سیکھیں\n\n#### Resources\n- [ ] [resources/index.md](https://d914cf26.fastapitiangolo.pages.dev/ur/resources/) — وسائل\n\n#### Tutorial — User Guide\n- [ ] [tutorial/index.md](https://d914cf26.fastapitiangolo.pages.dev/ur/tutorial/) — ٹیوٹوریل — صارف رہنما\n- [ ] [tutorial/first-steps.md](https://d914cf26.fastapitiangolo.pages.dev/ur/tutorial/first-steps/) — پہلے قدم\n- [ ] [tutorial/path-params.md](https://d914cf26.fastapitiangolo.pages.dev/ur/tutorial/path-params/) — Path Paramet\n---\nComment: Please, follow the template and don't open issues.\n\nAlso, see https://fastapi.tiangolo.com/contributing/#request-a-new-language", "source_type": "issue", "path": "issues/15118.json", "symbol": "🌐 Urdu (اردو) Documentation Translation — Review Tracker", "url": "https://github.com/fastapi/fastapi/issues/15118", "start_line": null, "end_line": null} {"id": "issue::15138", "text": "# Issue #15138: I had similar issue, solved like this:\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nI had similar issue, solved like this:", "source_type": "issue", "path": "issues/15138.json", "symbol": "I had similar issue, solved like this:", "url": "https://github.com/fastapi/fastapi/issues/15138", "start_line": null, "end_line": null} {"id": "issue::15188", "text": "# Issue #15188: Bug: SSE protocol injection via unvalidated event and id fields in format_sse_event()\n**Severity:** Low (framework-level), Medium/High in affected applications\n**CWE:** CWE-116: Improper Encoding for Output in a Different Plaintext Context\n**OWASP:** A03:2021: Injection\n**Affected version:** FastAPI 0.135.1 (master, commit `2742546af`)\n**Affected file:** `fastapi/sse.py` (FastAPI-owned code, not Starlette)\n**Fix PR:** #15187\n**Discovered:** 2026-03-20\n\n---\n\n## What's happening\n\n`format_sse_event()` builds SSE wire-format bytes by directly interpolating the `event` and `id` fields into output lines without stripping or rejecting newline characters. If either field contains a `\\n` or `\\r\\n`, it injects an extra SSE field-line into the stream. The browser's `EventSource` parser has no way to tell injected lines from real ones, so it treats them as valid protocol fields.\n\nThe `data` and `comment` fields in the same function are already handled safely with `splitlines()`. The omission for `event` and `id` looks like an oversight rather than a deliberate choice.\n\n---\n\n## Background: the SSE wire format\n\nSSE is a plain-text streaming protocol from the [HTML Living Standard §9.2](https://html.spec.whatwg.org/multipage/server-sent-events.html). Each event is a sequence of `field: value` lines separated by blank lines:\n\n```\nevent: message\\n\nid: 42\\n\ndata: {\"text\": \"hello\"}\\n\n\\n\n```\n\nThe newline is the entire field separator. There is no quoting, no escaping, no length prefix. The parser reads byte-by-byte and splits on `\\n` and `\\r\\n`. A newline inside a value is structurally identical to a field separator, so it creates a new field-line.\n\nValid field names are `event`, `id`, `data`, and `retry`. Lines starting with `:` are comments. The spec says unknown field names are ignored, but `data:` and `event:` are valid and directly affect browser behavior, so injecting them is meaningful.\n\n---\n\n## Vulnerable code\n\n### `fastapi/sse.py:146-214` — `format_sse_event()`\n\n```python\ndef format_sse_event(\n *,\n data_str: str | None = None,\n event: str | None = None,\n id: str | None = None,\n retry: int | None = None,\n comment: str | None = None,\n) -> bytes:\n lines: list[str] = []\n\n if comment is not None:\n for line in comment.splitlines(): # ✅ SAFE — splits on newlines\n lines.append(f\": {line}\")\n\n if event is not None:\n lines.append(f\"event: {event}\") # ❌ UNSAFE — raw f-string, no check\n\n if data_str is not None:\n for line in data_str.splitlines(): # ✅ SAFE — splits on newlines\n lines.append(f\"data: {line}\")\n\n if id is not None:\n lines.append(f\"id: {id}\") # ❌ UNSAFE — raw f-string, no newline check\n\n if retry is not None:\n lines.append(f\"retry: {retry}\")\n\n lines.append(\"\")\n lines.append(\"\")\n return \"\\n\".join(lines).encode(\"utf-8\")\n```\n\n### `fastapi/sse.py:36-39` — `_check_id_no_null()`\n\nThe only validation on `id` is a null-byte check. It does not reject `\\n` or `\\r`:\n\n```python\ndef _check_id_no_null(v: str | None) -> str | No\n---\nComment: @subhashdasyam, please follow the repository rules and don't open issues! You should've opened discussion instead\n---\nComment: > [@subhashdasyam](https://github.com/subhashdasyam), please follow the repository rules and don't open issues! You should've opened discussion instead\n\nSorry about that. I missed the contribution guidelines and should have opened a Discussion instead. My mistake.\n\nThe fix is tracked in PR #15187 . Closing this now.", "source_type": "issue", "path": "issues/15188.json", "symbol": "Bug: SSE protocol injection via unvalidated event and id fields in format_sse_event()", "url": "https://github.com/fastapi/fastapi/issues/15188", "start_line": null, "end_line": null} {"id": "issue::15197", "text": "# Issue #15197: FastAPI + Starlette 1.0.0: Jinja2 TemplateResponse raises 'unhashable type: dict'\n## Description\n\nAfter upgrading to Starlette 1.0.0, FastAPI applications using Jinja2 templates fail with:\n\n```\nTypeError: cannot use 'tuple' as a dict key (unhashable type: 'dict')\n```\n\nat `jinja2/utils.py`, line 515.\n\n## Environment\n\n- FastAPI 0.135.1\n- Starlette 1.0.0\n- Jinja2 3.1.6\n- Tested on Python 3.12 and 3.14 (issue reproduced on both)\n\n## Steps to reproduce\n\n1. Install `fastapi==0.135.1` with `starlette==1.0.0`\n2. Create a route that returns a `Jinja2Templates.TemplateResponse`\n3. Any template render raises the error above\n\n## Workaround\n\nPin `starlette<1.0.0` in `requirements.txt`.\n\n## Notes\n\nThis appears to be related to breaking changes in Starlette 1.0.0's `TemplateResponse` signature. FastAPI may need to update how it passes context to Jinja2 templates for Starlette 1.0.0 compatibility.\n\nDetected in production during a routine deployment where pip resolved Starlette 1.0.0 instead of 0.52.x.", "source_type": "issue", "path": "issues/15197.json", "symbol": "FastAPI + Starlette 1.0.0: Jinja2 TemplateResponse raises 'unhashable type: dict'", "url": "https://github.com/fastapi/fastapi/issues/15197", "start_line": null, "end_line": null} {"id": "issue::15236", "text": "# Issue #15236: Review: compatibility and contract risks around Pydantic >=2.9.0 floor bump\n## Summary\n\nI reviewed the most recent framework-affecting upstream changes visible around FastAPI 0.135.2. The main substantive change in the inspected window is PR #15139:\n\n- Increase lower bound to `pydantic >= 2.9.0`\n- Adjust tests to accept multiple schema shapes across Pydantic 2.9/2.10/2.11\n\nOverall, the code delta is small, but the compatibility impact is not. The main concern is release-management and contract clarity, not request-path performance.\n\n## Findings\n\n### High — Potential breaking change shipped as a patch release\n\nFastAPI changed its dependency floor from `pydantic>=2.7.0` to `pydantic>=2.9.0` in what appears as a patch release (`0.135.2`).\n\n**Why this matters**\n- Patch upgrades are commonly assumed to be safe.\n- This can break downstream environments pinned to Pydantic 2.7.x or 2.8.x.\n- Lockfile resolution may now force broader upgrades than users expect.\n\n**Recommendation**\n- Treat this as a breaking compatibility note in release notes, or\n- Move dependency floor changes like this to a minor release unless there is a hard runtime correctness reason.\n\n### Medium — Test contract is now more permissive, reducing schema-surface precision\n\nThe updated tests use flexible assertions (`IsOneOf`) to accept multiple OpenAPI/JSON Schema shapes depending on the installed Pydantic version.\n\nExamples include:\n- top-level schema presence/absence differences\n- `additionalProperties` presence differences\n- `const`-only vs `const + enum` output differences\n\n**Why this matters**\nGenerated schema is part of FastAPI's effective public contract. More permissive tests reduce spurious failures, but they also make it easier for accidental schema drift to pass unnoticed.\n\n**Recommendation**\n- Keep compatibility tests flexible where needed.\n- Add invariant tests for FastAPI-owned guarantees, e.g. discriminator behavior, required fields, ref stability, and documented normalization behavior.\n\n### Medium — Version-floor bump appears driven by compatibility/test variance more than visible runtime framework changes\n\nIn the inspected diff, the substantive changes are dependency metadata and tests. I did not find corresponding FastAPI runtime implementation changes in `fastapi/` explaining why `>=2.9.0` is strictly required.\n\n**Why this matters**\nIf older supported Pydantic v2 versions still work at runtime, narrowing the support range increases upgrade friction without clear user benefit.\n\n**Recommendation**\n- Document the exact runtime reason `>=2.9.0` is required.\n- If the issue is mainly schema-output variance in tests, prefer encoding that in tests rather than constraining all downstream users.\n\n### Low — No notable FastAPI-side performance risk in the inspected change\n\nThe recent diff does not introduce meaningful new work in request handling, dependency injection, routing, or serialization.\n\n**Assessment**\n- No obvious FastAPI runtime performance regression.\n- Any performance effect would likely come indirectly from Pydantic version behavior, not new", "source_type": "issue", "path": "issues/15236.json", "symbol": "Review: compatibility and contract risks around Pydantic >=2.9.0 floor bump", "url": "https://github.com/fastapi/fastapi/issues/15236", "start_line": null, "end_line": null} {"id": "issue::15237", "text": "# Issue #15237: scripts/people.py still ignores minimized top-level discussions in People stats\n## Summary\nThe recent change in `scripts/people.py` that excludes minimized comments/replies from the FastAPI People statistics is incomplete for top-level discussions.\n\nThe GraphQL query now fetches `minimizedReason` for each discussion node, but `DiscussionsNode` does not model that field and `get_discussions_experts()` never checks it before processing the discussion's comments/replies.\n\nAs a result, a minimized discussion can still contribute participants to the People stats through its non-minimized replies/comments, even though the thread itself has already been moderation-minimized.\n\n## Relevant recent change\n- Commit: `0227991` (`🔨 Exclude spam comments from statistics in scripts/people.py`)\n\n## What I observed\nIn `scripts/people.py`:\n\n1. The GraphQL query includes `minimizedReason` on the discussion node itself.\n2. `DiscussionsNode` only defines:\n - `number`\n - `author`\n - `title`\n - `createdAt`\n - `comments`\n3. `get_discussions_experts()` filters `comment.minimizedReason` and `reply.minimizedReason`, but never filters the discussion/thread itself.\n\nThat means the top-level moderation state is fetched but ignored.\n\n## Why this matters\nIf a discussion is minimized for spam / abuse / off-topic / duplicate reasons, the script still traverses that discussion and can count participants from replies/comments under that thread.\n\nSo the recent fix is only partial: it excludes minimized comments, but not minimized discussions.\n\n## Expected behavior\nIf a discussion itself is minimized for one of the excluded reasons, the script should skip the entire discussion when computing People statistics.\n\n## Possible fix\n- Add `minimizedReason: LowerStr | None = None` to `DiscussionsNode`\n- In `get_discussions_experts()`, skip processing when:\n\n```py\nif discussion.minimizedReason in MINIMIZED_COMMENTS_REASONS_TO_EXCLUDE:\n continue\n```\n\n## Extra note\nBecause the GraphQL query already requests the field, this looks like an accidental omission rather than a design decision.\n", "source_type": "issue", "path": "issues/15237.json", "symbol": "scripts/people.py still ignores minimized top-level discussions in People stats", "url": "https://github.com/fastapi/fastapi/issues/15237", "start_line": null, "end_line": null} {"id": "issue::15238", "text": "# Issue #15238: Static analysis commands are duplicated across lint.sh and pre-commit, making drift likely\n## Summary\n\nThe recent change in PR #15136 adds `ty check fastapi` to `scripts/lint.sh`, but FastAPI now maintains the static-analysis command set in multiple places with slightly different entrypoints:\n\n- `scripts/lint.sh`\n- `.pre-commit-config.yaml`\n- `.github/workflows/pre-commit.yml` / CI setup\n\nThis creates a drift risk: each time a new checker is added or an existing one changes invocation details, contributors and automation may silently diverge.\n\n## Why this matters\n\nRight now, `ty` is present both in `scripts/lint.sh` and in `.pre-commit-config.yaml`, but they are not driven from a single source of truth:\n\n- `scripts/lint.sh` runs bare executables:\n - `mypy fastapi`\n - `ty check fastapi`\n - `ruff check ...`\n - `ruff format ... --check`\n- `.pre-commit-config.yaml` runs the same tools through `uv run ...`\n\nThis means future updates can easily land in one path but not the others. PR #15136 is a good example of how easy it is for the maintenance burden to increase with every new tool added.\n\n## Concrete risk\n\nA contributor can get different results depending on whether they run:\n\n- `bash scripts/lint.sh`\n- `prek run -a`\n- the GitHub Actions pre-commit workflow\n\nEven if they currently happen to pass, the repo is relying on humans to remember to update several places whenever the lint stack changes.\n\n## Suggested fix\n\nUse one source of truth for the static checks. For example:\n\n1. Make `.pre-commit-config.yaml` call `bash scripts/lint.sh` (or smaller script fragments), **or**\n2. Make `scripts/lint.sh` invoke the exact `uv run ...` commands used by pre-commit, **or**\n3. Generate/centralize the command list so adding a new checker only requires one edit.\n\nA smaller improvement would be to at least align invocation style between the script and pre-commit (`uv run ...` vs bare executables), so local and automated paths behave more consistently.\n\n## Context\n\nThis issue was noticed while reviewing the latest changes on `master`, specifically PR #15136 (`👷 Add ty check to lint.sh`).\n", "source_type": "issue", "path": "issues/15238.json", "symbol": "Static analysis commands are duplicated across lint.sh and pre-commit, making drift likely", "url": "https://github.com/fastapi/fastapi/issues/15238", "start_line": null, "end_line": null} {"id": "issue::15268", "text": "# Issue #15268: Add Clarvia AEO badge — FastAPI agent-readiness score\n## Add Clarvia AEO Badge — FastAPI Agent Readiness Score\n\nHi! I'm building [Clarvia](https://clarvia.art) — an AEO (AI Engine Optimization) platform that rates APIs and frameworks for autonomous agent integration quality.\n\nFastAPI is used by millions of developers to build APIs, and increasingly these APIs are being consumed by AI agents. An AEO badge would help FastAPI developers understand how agent-friendly their APIs are.\n\n**What is AEO?** AEO evaluates APIs for:\n- 📚 OpenAPI/JSON Schema completeness\n- 🔧 Structured error responses\n- 🔍 Agent discoverability (OpenAPI auto-discovery)\n- 🛡️ Security patterns (OAuth2, API keys)\n- 🌐 Ecosystem health\n\nFastAPI actually excels at many of these (automatic OpenAPI generation, typed responses, OAuth2 support) — which is why we think it deserves a high AEO score.\n\n**Badge markdown:**\n```markdown\n[![AEO Score](https://clarvia.art/api/badge/fastapi)](https://clarvia.art/tool/fastapi)\n```\n\nFull FastAPI profile: https://clarvia.art — 27,906+ tools indexed.\n\nThis would be a powerful signal to the AI agent developer community that FastAPI-built APIs are agent-ready by default!\n---\nComment: I'm closing this and blocking this user, please follow the AI guidelines, and please don't spam. https://fastapi.tiangolo.com/contributing/#automated-code-and-ai", "source_type": "issue", "path": "issues/15268.json", "symbol": "Add Clarvia AEO badge — FastAPI agent-readiness score", "url": "https://github.com/fastapi/fastapi/issues/15268", "start_line": null, "end_line": null} {"id": "issue::15322", "text": "# Issue #15322: 🚨 Security Vulnerability Detected: docs/en/docs/js/custom.js\n## Sentinel-Zero Automated Report\n\n**Issue:**\n{\"vulnerable\": true, \"type\": \"DOM-based XSS\", \"description\": \"The code uses `node.textContent = inputCommands;` which can lead to DOM-based XSS if the `inputCommands` variable contains user-controlled data. Additionally, the `showRandomAnnouncement` function uses `children[index].style.display = 'block'` which can also lead to DOM-based XSS if the `children` array contains user-controlled data.\"}\n\n*A patch is being generated and a PR will be linked shortly.*", "source_type": "issue", "path": "issues/15322.json", "symbol": "🚨 Security Vulnerability Detected: docs/en/docs/js/custom.js", "url": "https://github.com/fastapi/fastapi/issues/15322", "start_line": null, "end_line": null} {"id": "issue::15324", "text": "# Issue #15324: 🚨 Security Vulnerability Detected: docs/en/docs/js/custom.js\nI have built a AI Agentic Security Analyst that analyses repos with security vulnerabilities... so this was one of it's remediation. Kindly merge it\r\n\r\nYou can view the repository here👇\r\n\r\nRepository Link: https://github.com/Sumedh-6504/sentinel_zero.git\r\n\r\n_Originally posted by @Sumedh-6504 in https://github.com/fastapi/fastapi/issues/15323#issuecomment-4230983767_\r\n ", "source_type": "issue", "path": "issues/15324.json", "symbol": "🚨 Security Vulnerability Detected: docs/en/docs/js/custom.js", "url": "https://github.com/fastapi/fastapi/issues/15324", "start_line": null, "end_line": null} {"id": "issue::15325", "text": "# Issue #15325: 🚨 Security Vulnerability Detected: tests/test_tutorial/test_security/test_tutorial004.py\n## Sentinel-Zero Automated Report\n\n**Issue:**\nThe code contains hardcoded secrets, such as the password 'secret' in the get_access_token function and the test_login function.\n\n*A patch is being generated and a PR will be linked shortly.*", "source_type": "issue", "path": "issues/15325.json", "symbol": "🚨 Security Vulnerability Detected: tests/test_tutorial/test_security/test_tutorial004.py", "url": "https://github.com/fastapi/fastapi/issues/15325", "start_line": null, "end_line": null} {"id": "issue::15401", "text": "# Issue #15401: SSE `stream_item_type` not propagated through `APIRouter` + `include_router`\n### Summary\n\nWhen an SSE route (`response_class=EventSourceResponse` + `AsyncIterator[Frame]` return annotation) is defined on an `APIRouter` and then merged onto a `FastAPI` app via `include_router`, the resulting merged route loses its `stream_item_type`. As a consequence, the OpenAPI `text/event-stream` response schema omits the `data.contentSchema`, so tooling like `datamodel-codegen` cannot generate frame models.\n\nDefining the same route directly on the `FastAPI` app via `@app.post(...)` works correctly.\n\n### Reproduction\n\n```python\nfrom collections.abc import AsyncIterator\n\nfrom fastapi import APIRouter, FastAPI\nfrom fastapi.sse import EventSourceResponse\nfrom pydantic import BaseModel\n\n\nclass Frame(BaseModel):\n kind: str\n\n\n# Case A — route registered directly on the app: works\napp_a = FastAPI()\n\n@app_a.post(\"/s\", response_class=EventSourceResponse)\nasync def a() -> AsyncIterator[Frame]:\n yield Frame(kind=\"x\")\n\n\n# Case B — route defined on a router, then `include_router`: broken\nrouter = APIRouter()\n\n@router.post(\"/s\", response_class=EventSourceResponse)\nasync def b() -> AsyncIterator[Frame]:\n yield Frame(kind=\"x\")\n\n\napp_b = FastAPI()\napp_b.include_router(router)\n\nprint(\"DIRECT:\", app_a.routes[-1].stream_item_type)\nprint(\"ROUTER (pre-include):\", router.routes[-1].stream_item_type)\nprint(\"APP (post-include):\", app_b.routes[-1].stream_item_type)\n\n\ndef has_content_schema(spec: dict) -> bool:\n sse = spec[\"paths\"][\"/s\"][\"post\"][\"responses\"][\"200\"][\"content\"][\"text/event-stream\"]\n return \"contentSchema\" in sse.get(\"itemSchema\", {}).get(\"properties\", {}).get(\"data\", {})\n\n\nprint(\"DIRECT openapi has contentSchema:\", has_content_schema(app_a.openapi()))\nprint(\"INCLUDE_ROUTER openapi has contentSchema:\", has_content_schema(app_b.openapi()))\n```\n\nOutput:\n\n```\nDIRECT: \nROUTER (pre-include): \nAPP (post-include): None\n\nDIRECT openapi has contentSchema: True\nINCLUDE_ROUTER openapi has contentSchema: False\n```\n\n### Expected\n\nAfter `include_router`, the merged route on `app_b` should carry the same `stream_item_type` as the source route, and the emitted OpenAPI should include the `contentSchema` under `responses.200.content[\"text/event-stream\"].itemSchema.properties.data` referencing `Frame`.\n\n### Actual\n\nThe merged route's `stream_item_type` is `None`; the emitted OpenAPI shows the generic SSE envelope (`data: string, event, id, retry`) with no `contentSchema`.\n\n### Root cause (proposed)\n\nIn `fastapi/routing.py`, `APIRoute.__init__` populates `self.stream_item_type` only inside the branch guarded by `isinstance(response_model, DefaultPlaceholder)`:\n\n```python\nif 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 if (\n is\n---\nComment: We'll continue tracking this internally, I'll close this one to prevent more automated AI generated PRs that only add to our overhead. ☕ \n\nhttps://fastapi.tiangolo.com/contributing/#automated-code-and-ai\n---\nComment: Hi, I’d like to work on this issue if it is still available. \n---\nComment: > Hi, I’d like to work on this issue if it is still available.\n\nAs you can see there is a PR linked to the issue. You can review it", "source_type": "issue", "path": "issues/15401.json", "symbol": "SSE `stream_item_type` not propagated through `APIRouter` + `include_router`", "url": "https://github.com/fastapi/fastapi/issues/15401", "start_line": null, "end_line": null} {"id": "issue::15448", "text": "# Issue #15448: Malformed Links in Documentation Home\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nHi, \n\nI just accessed the documentation home page and saw that the links on the Opinitions sections was malformed: \n\n\"Image\"\n\nI though about correcting it to start contributing, but I don't have the time rn, so I wanted to report. If I have the time I might look into correcting this to start contributing more.\n\nPlease, feel free to connect and hope to have helped. Let me know if this is not the right place and where that would be.\n\nBest,\n---\nComment: Thanks for reporting this!\nI'll take a look at it\n---\nComment: Fixed by https://github.com/fastapi/fastapi/pull/15458", "source_type": "issue", "path": "issues/15448.json", "symbol": "Malformed Links in Documentation Home", "url": "https://github.com/fastapi/fastapi/issues/15448", "start_line": null, "end_line": null} {"id": "issue::15466", "text": "# Issue #15466: [Code Review] Recent dependency updates — pydantic 2.13, pydantic-ai 1.83 (Apr 2026)\n## Code Review: fastapi/fastapi Recent Changes (Last 10 Days)\n\n### Overview\nReviewed recent commits from ~Apr 22 to May 1, 2026.\n\n### Low-Risk Changes\n- UI/Docs updates: interactive tabs, layout styling (#15458, #15462)\n- Release v0.136.1 with Pydantic v2 deprecation fixes\n- No security patches needed (clean — no emergency fixes required)\n- All CI commits properly signed; author contributions verified\n\n### Notable Dependency Bumps\n\n| Dependency | Old Version | New Version | Risk Level | Notes |\n|-----------|-------------|-------------|------------|-------|\n| pydantic | 2.12.5 | 2.13.2 | **HIGH** | 1,765 commits between versions |\n| pydantic-ai | 1.63.0 | 1.83.0 | **MEDIUM** | 20 minor version jumps |\n| fastar | 0.9.0 | 0.11.0 | **MEDIUM** | Major minor bump |\n| sqlmodel | 0.0.32 | 0.0.38 | LOW | Patch bumps |\n\n### Key Observations\n\n1. **Multiple major dependency jumps happened simultaneously on Apr 27** with no explanatory release notes — recommend adding a changelog entry explaining why\n\n2. **pydantic-ai upgrade cadence is very fast** — already at 1.86.0 in pending PR #15459; worth monitoring for regressions\n\n3. **pydantic 2.13.x may introduce breaking changes** — recommend thorough testing of Pydantic v2 compatibility, especially with custom validators\n\n4. **No regression issues found** in the review period\n\n### Recommendation\n- Add explanatory release notes for the Apr 27 dependency batch update\n- Consider pinning critical dependency versions if not already done\n- Monitor pydantic-ai upgrade path closely\n\n---\n*Review generated by AI agent (2026-05-01)*", "source_type": "issue", "path": "issues/15466.json", "symbol": "[Code Review] Recent dependency updates — pydantic 2.13, pydantic-ai 1.83 (Apr 2026)", "url": "https://github.com/fastapi/fastapi/issues/15466", "start_line": null, "end_line": null} {"id": "issue::15503", "text": "# Issue #15503: Custom APIRoute classes with explicit constructors fail after strict_content_type was added\n### Summary\n\nRecent FastAPI versions added `strict_content_type` and now pass it through `APIRouter.add_api_route()` into the configured `route_class`. This breaks custom `APIRoute` subclasses that define an explicit constructor matching the previous public `APIRoute.__init__` signature.\n\nSubclasses that only override `get_route_handler()` still work, and subclasses using `**kwargs` still work. The regression affects subclasses that pinned the previously accepted constructor parameters and delegate them to `super().__init__()`.\n\n### Reproducer\n\n```python\nfrom enum import Enum\nfrom typing import Any, Callable, Sequence\n\nfrom fastapi import APIRouter, FastAPI, params\nfrom fastapi.datastructures import Default, DefaultPlaceholder\nfrom fastapi.responses import JSONResponse, Response\nfrom fastapi.routing import APIRoute\nfrom fastapi.types import IncEx\nfrom fastapi.utils import generate_unique_id\nfrom starlette.routing import BaseRoute\n\n\nclass LegacyRoute(APIRoute):\n def __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 ) -> None:\n super().__init__(\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_mod\n---\nComment: Hey, I can reproduce this issue and would love to work on a fix. Could you please assign it to me?\n---\nComment: @4x4550x have you considered using `**kwargs` in the LegacyRoute constructor instead of defining all parameter ?\nyour code can still work if FastAPI make such changes in future and you don't have to wait for the fixes\n---\nComment: Hey there, these conversations should all start as discussions, let me move it over there and we can continue the conversation there.", "source_type": "issue", "path": "issues/15503.json", "symbol": "Custom APIRoute classes with explicit constructors fail after strict_content_type was added", "url": "https://github.com/fastapi/fastapi/issues/15503", "start_line": null, "end_line": null} {"id": "issue::15535", "text": "# Issue #15535: Broken optional orjson/ujson install can break importing fastapi.responses\n### First Check\n\n- [x] I added a very descriptive title to this issue.\n- [x] I used the GitHub search to find a similar issue and didn't find it.\n- [x] I searched the FastAPI documentation, with the integrated search.\n- [x] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [x] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [x] I already checked if it is not related to FastAPI but to Pydantic.\n- [x] I already checked if it is not related to FastAPI but to Swagger UI.\n- [x] I already checked if it is not related to FastAPI but to ReDoc.\n\n### Commit to Help\n\n- [x] I commit to help with one of those options.\n\n### Example Code\n\n```python\nimport sys, importlib\n\nsys.path.insert(0, \"/path/to/fastapi\")\n\nreal_import_module = importlib.import_module\n\ndef fake_import_module(name, package=None):\n if name == \"ujson\":\n raise ModuleNotFoundError(\"No module named 'ujson'\")\n if name == \"orjson\":\n raise ImportError(\"simulated binary/load failure\")\n return real_import_module(name, package)\n\nimportlib.import_module = fake_import_module\n\nimport fastapi.responses\n```\n\n### Description\n\nRecent `fastapi.responses` code catches `ModuleNotFoundError` when importing optional JSON response encoders:\n\n```python\ntry:\n ujson = cast(_UjsonModule, importlib.import_module(\"ujson\"))\nexcept ModuleNotFoundError:\n ujson = None\n\ntry:\n orjson = cast(_OrjsonModule, importlib.import_module(\"orjson\"))\nexcept ModuleNotFoundError:\n orjson = None\n```\n\nThis handles the package-absent case, but it no longer handles the optional C-extension failure case where the module exists but cannot load its binary extension or a platform dependency. In that case, `importlib.import_module(\"orjson\")` or `importlib.import_module(\"ujson\")` can raise a plain `ImportError`, and importing `fastapi.responses` fails even if the user only needs `JSONResponse`, `HTMLResponse`, etc.\n\nI noticed this while reviewing recent changes around free-threaded Python 3.14t support and the `responses.py` optional import cleanup.\n\nExpected behavior: a broken optional `orjson` or `ujson` install should not break importing the general response module. It should behave like the package is unavailable until the deprecated optional response class is actually used.\n\nSuggested fix: catch `ImportError` for these optional imports, as the previous direct imports did, or catch both `ModuleNotFoundError` and `ImportError`.\n\nSuggested regression test: monkeypatch `importlib.import_module` to raise `ImportError` for `orjson`, then assert `import fastapi.responses` succeeds.\n\n### Operating System\n\nWindows\n\n### Operating System Details\n\nWindows 11, local repo checkout\n\n### FastAPI Version\n\nCurrent `master` at `ecace740`\n\n### Python Version\n\nPython 3.12.7\n\n### Additional Context\n\nRelated recent PR reviewed: `#15149` (`4b264878`), \"Support free-threaded Python 3.14t\".\n", "source_type": "issue", "path": "issues/15535.json", "symbol": "Broken optional orjson/ujson install can break importing fastapi.responses", "url": "https://github.com/fastapi/fastapi/issues/15535", "start_line": null, "end_line": null} {"id": "issue::15538", "text": "# Issue #15538: Ensure pydantic_extra_types Color encoder path is covered in tests\n### Describe the bug\n\nThe new `jsonable_encoder()` coverage for `pydantic_extra_types.color.Color` can be skipped in the default test environment, so the modern color-type branch added in `fastapi/encoders.py` may not be exercised by normal test runs.\n\nOn current `master` (`ecace74`), this command passes one color case and skips the `pydantic_extra_types.color` case because `pydantic_extra_types` is not installed in the default test environment:\n\n```console\n$ uv run pytest tests/test_jsonable_encoder.py::test_encode_color -q -rs\n.s [100%]\n=========================== short test summary info ===========================\nSKIPPED [1] tests\\test_jsonable_encoder.py:328: pydantic_extra_types.color not available\n1 passed, 1 skipped in 0.44s\n```\n\n### To Reproduce\n\n1. Check out current `master`.\n2. Run:\n\n```console\nuv run pytest tests/test_jsonable_encoder.py::test_encode_color -q -rs\n```\n\n### Expected behavior\n\nThe newly added `pydantic_extra_types.color.Color` encoder path should be covered in at least one required CI/test environment, or the optional-extra coverage should live in an explicit extra-specific test job.\n\n### Suggested solution\n\nOne of these would make the coverage explicit:\n\n- Add `pydantic-extra-types >=2.0.0` to the `tests` dependency group, or\n- Add an extra-specific CI/test job that installs `fastapi[standard]` or `fastapi[all]` and requires the `pydantic_extra_types.color` branch to run.\n\n### Environment\n\n- FastAPI commit: `ecace74`\n- Python via `uv run`: CPython 3.11.15 on Windows\n- Test command: `uv run pytest tests/test_jsonable_encoder.py::test_encode_color -q -rs`\n\n### Additional context\n\nThis is a low-severity coverage issue, not a runtime import failure. The runtime code intentionally treats `pydantic_extra_types` as optional.", "source_type": "issue", "path": "issues/15538.json", "symbol": "Ensure pydantic_extra_types Color encoder path is covered in tests", "url": "https://github.com/fastapi/fastapi/issues/15538", "start_line": null, "end_line": null} {"id": "issue::15578", "text": "# Issue #15578: fastapi[standard]>=0.112.0,<0.113.0\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nwas using ai to create page", "source_type": "issue", "path": "issues/15578.json", "symbol": "fastapi[standard]>=0.112.0,<0.113.0", "url": "https://github.com/fastapi/fastapi/issues/15578", "start_line": null, "end_line": null} {"id": "issue::15612", "text": "# Issue #15612: OSV advisory MAL-2026-4750 appears to be a false positive for fastapi/fastapi\n### Privileged issue\n\n- [ ] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\nThere is an OSV advisory MAL-2026-4750 that currently lists the FastAPI GitHub repository as affected:\nhttps://osv.dev/vulnerability/MAL-2026-4750\n\nAfter investigating, we believe this is a false positive and that the FastAPI project itself is not affected by the described issue.\n\nIf you agree that MAL-2026-4750 is not applicable to fastapi/fastapi and if you are in contact with OSV, it would be very helpful if you could request a correction or removal of the false association, since many consumers rely on these feeds.\n\nThanks!\n---\nComment: Note that it's being withdrawn: https://github.com/ossf/malicious-packages/pull/1276\n---\nComment: I see they reported it here: https://github.com/ossf/malicious-packages/issues/1274, I'm continuing the conversation there.\n---\nComment: How does OSV works? If I got this right, Amazon reported this, and someone approved?", "source_type": "issue", "path": "issues/15612.json", "symbol": "OSV advisory MAL-2026-4750 appears to be a false positive for fastapi/fastapi", "url": "https://github.com/fastapi/fastapi/issues/15612", "start_line": null, "end_line": null} {"id": "issue::15680", "text": "# Issue #15680: AI安全审计报告:FastAPI代码质量评估\n## 🕳️ AI 代码审计报告\n\n对 FastAPI (tiangolo/fastapi) 进行了自动安全扫描。\n\n### 扫描概况\n\n- 源文件: 1,120 个 Python 文件 (109,217 行代码)\n- 发现: 2 类安全模式\n\n### 发现详情\n\n**1. 命令执行相关调用(3处)**\n- 存在 subprocess.Popen / os.system 等调用\n- 建议: 审查这些调用是否涉及用户输入,使用 shlex.quote 处理参数\n\n**2. 配置密钥(4处)**\n- 代码中包含 SECRET_KEY 等配置字面量\n- 建议: 生产环境通过环境变量注入\n\n---\n\n📊 FastAPI 整体代码质量较高。\n本次扫描基于静态代码分析,未进行动态验证。\n\n⚡ 扫描工具: ONESEC v4.0(多语言引擎:Go + Python)\n\n> 如需对您的项目做安全审计,可联系: l15250432278@163.com", "source_type": "issue", "path": "issues/15680.json", "symbol": "AI安全审计报告:FastAPI代码质量评估", "url": "https://github.com/fastapi/fastapi/issues/15680", "start_line": null, "end_line": null} {"id": "issue::15712", "text": "# Issue #15712: Implement GraphQL integration with automatic schema generation from Pydantic models\n## Problem Statement\nFastAPI excels at REST but lacks GraphQL support. GraphQL schema must be defined separately from Pydantic models. Code duplication between REST and GraphQL definitions. Teams choose between REST and GraphQL instead of offering both.\n\n**Business Impact:** Enables flexible querying, supports multiple client needs, improves API flexibility, enables modern frontend patterns.\n\n## Root Cause Analysis\nGraphQL is separate from REST. Schema duplication is required. Integration is manual.\n\n## Solution Overview\n- Create FastAPI-GraphQL integration\n- Auto-generate GraphQL schema from Pydantic\n- Support both REST and GraphQL simultaneously\n- Build query validation\n- Add performance monitoring\n\n**Implementation Steps:**\n1. Design GraphQL integration API\n2. Build schema generator from Pydantic\n3. Implement query resolver system\n4. Add authentication/authorization\n5. Create examples and documentation\n\n## Type of Change\nEnhancement, API design, New feature\n\n## Testing Done\n- Test 50+ GraphQL scenarios\n- Verify schema generation accuracy\n- Performance testing (< 100ms queries)\n- Test concurrent requests (1000+)\n- Security testing\n\n## Related Issues & Standards\nGraphQL spec, Pydantic integration\n\n## Suggested Labels\nenhancement, graphql, api-design, pydantic, GSSoC26\n---\nComment: ## GSSoC '26 Contribution Opportunity\n\n@tiangolo Available for **GSSoC 2026** contributions.\n\n**Points:** 500+ | **Difficulty:** Advanced | **Type:** API Design\n\n/assign", "source_type": "issue", "path": "issues/15712.json", "symbol": "Implement GraphQL integration with automatic schema generation from Pydantic models", "url": "https://github.com/fastapi/fastapi/issues/15712", "start_line": null, "end_line": null} {"id": "issue::15713", "text": "# Issue #15713: Add automatic request/response caching with smart cache invalidation strategies\n## Problem Statement\nFastAPI lacks built-in caching. Redis integration requires manual setup. Cache invalidation is complex. No standard way to cache responses based on dependencies. Teams implement custom caching repeatedly.\n\n**Business Impact:** Improves endpoint response times by 70-90%, reduces database load by 50%, enables serving 100x more requests, reduces infrastructure costs.\n\n## Root Cause Analysis\nCaching is external concern. No framework integration. Cache invalidation strategies are undefined.\n\n## Solution Overview\n- Implement caching decorator\n- Add smart cache invalidation\n- Build dependency tracking\n- Support multiple backends (Redis, Memcached, in-memory)\n- Create monitoring\n\n**Implementation Steps:**\n1. Design cache decorator API\n2. Implement cache key generation\n3. Build dependency tracking system\n4. Add backend adapters\n5. Create examples\n\n## Type of Change\nEnhancement, Performance, Scalability\n\n## Testing Done\n- Test 40+ caching scenarios\n- Verify cache accuracy\n- Performance testing (< 1ms cache hits)\n- Test invalidation correctness\n- Benchmark with 10000+ requests\n\n## Related Issues & Standards\nHTTP caching standards, cache patterns\n\n## Suggested Labels\nenhancement, caching, performance, scalability, GSSoC26\n---\nComment: ## GSSoC '26 Contribution Opportunity\n\n@tiangolo Available for **GSSoC 2026** contributions.\n\n**Points:** 500+ | **Difficulty:** Advanced | **Type:** Performance\n\n/assign", "source_type": "issue", "path": "issues/15713.json", "symbol": "Add automatic request/response caching with smart cache invalidation strategies", "url": "https://github.com/fastapi/fastapi/issues/15713", "start_line": null, "end_line": null} {"id": "issue::15714", "text": "# Issue #15714: Implement automatic API documentation generation with interactive examples and SDK generation\n## Problem Statement\nFastAPI auto-docs are basic. Complex APIs need better documentation. No interactive examples by default. SDK generation for clients is manual. API consumers lack context. Documentation maintenance is tedious.\n\n**Business Impact:** Improves developer onboarding by 60%, reduces support overhead, accelerates client integration, improves API adoption.\n\n## Root Cause Analysis\nDocs are auto-generated but basic. Examples are static. SDK generation is external.\n\n## Solution Overview\n- Enhance OpenAPI generation\n- Add interactive examples\n- Build SDK generation system\n- Create test scenario documentation\n- Add authentication flow examples\n\n**Implementation Steps:**\n1. Extend OpenAPI schema\n2. Add example generation\n3. Build SDK generators (TypeScript, Python, Java)\n4. Create interactive docs UI\n5. Add documentation best practices\n\n## Type of Change\nEnhancement, Developer experience, Documentation\n\n## Testing Done\n- Test 50+ API patterns\n- Verify OpenAPI compliance\n- Test SDK generation accuracy\n- Cross-language compatibility\n- Performance testing\n\n## Related Issues & Standards\nOpenAPI 3.0 spec, SDK generation best practices\n\n## Suggested Labels\nenhancement, documentation, developer-experience, openapi, GSSoC26\n---\nComment: ## GSSoC '26 Contribution Opportunity\n\n@tiangolo Available for **GSSoC 2026** contributions.\n\n**Points:** 500+ | **Difficulty:** Advanced | **Type:** Developer Experience\n\n/assign", "source_type": "issue", "path": "issues/15714.json", "symbol": "Implement automatic API documentation generation with interactive examples and SDK generation", "url": "https://github.com/fastapi/fastapi/issues/15714", "start_line": null, "end_line": null} {"id": "issue::15715", "text": "# Issue #15715: Add built-in job queue and background task management with monitoring dashboard\n## Problem Statement\nFastAPI has basic background tasks but lacks production features. No job persistence. Task monitoring is external. Complex workflows require external orchestration. Distributed task execution is not straightforward.\n\n**Business Impact:** Enables reliable background processing, improves application responsiveness, supports scheduled jobs, enables workflow automation.\n\n## Root Cause Analysis\nBackground tasks are simple. Production features are missing. Monitoring is external.\n\n## Solution Overview\n- Enhance background task system\n- Add job persistence\n- Build monitoring dashboard\n- Support distributed execution\n- Create workflow support\n\n**Implementation Steps:**\n1. Design task queue system\n2. Implement job persistence\n3. Build monitoring API\n4. Add distributed execution\n5. Create workflow patterns\n\n## Type of Change\nEnhancement, Scalability, Production-ready features\n\n## Testing Done\n- Test 50+ task scenarios\n- Verify persistence and recovery\n- Performance testing (1000+ tasks/sec)\n- Distributed execution testing\n- Failure recovery testing\n\n## Related Issues & Standards\nJob queue patterns, task orchestration standards\n\n## Suggested Labels\nenhancement, background-tasks, job-queue, scalability, GSSoC26\n---\nComment: ## GSSoC '26 Contribution Opportunity\n\n@tiangolo Available for **GSSoC 2026** contributions.\n\n**Points:** 500+ | **Difficulty:** Advanced | **Type:** Scalability\n\n/assign", "source_type": "issue", "path": "issues/15715.json", "symbol": "Add built-in job queue and background task management with monitoring dashboard", "url": "https://github.com/fastapi/fastapi/issues/15715", "start_line": null, "end_line": null} {"id": "issue::15716", "text": "# Issue #15716: Implement advanced input validation with custom rule engine and cross-field validation support\n## Problem Statement\nPydantic validation is powerful but lacks advanced cross-field validation. Complex business rules require custom code. Validation error messages are technical. No way to compose validation rules. Conditional validation is difficult.\n\n**Business Impact:** Improves data quality by 50%, reduces business logic bugs, improves API robustness, enables better error feedback.\n\n## Root Cause Analysis\nField-level validation only. Cross-field validation requires custom code. Error messages are not user-friendly.\n\n## Solution Overview\n- Build custom validation rule engine\n- Support cross-field validation\n- Create user-friendly error messages\n- Build rule composition system\n- Add conditional validation\n\n**Implementation Steps:**\n1. Design validation API\n2. Implement rule engine\n3. Build composition system\n4. Add custom error messages\n5. Create examples\n\n## Type of Change\nEnhancement, Data validation, Developer experience\n\n## Testing Done\n- Test 100+ validation scenarios\n- Verify accuracy of complex rules\n- Performance testing (< 10ms)\n- Cross-field validation accuracy\n- Error message quality testing\n\n## Related Issues & Standards\nPydantic validation, form validation best practices\n\n## Suggested Labels\nenhancement, validation, pydantic, data-quality, GSSoC26\n---\nComment: ## GSSoC '26 Contribution Opportunity\n\n@tiangolo Available for **GSSoC 2026** contributions.\n\n**Points:** 500+ | **Difficulty:** Advanced | **Type:** Validation\n\n/assign", "source_type": "issue", "path": "issues/15716.json", "symbol": "Implement advanced input validation with custom rule engine and cross-field validation support", "url": "https://github.com/fastapi/fastapi/issues/15716", "start_line": null, "end_line": null} {"id": "issue::15738", "text": "# Issue #15738: Aether Bridge API - Autonomous Agent Team Management for FastAPI Apps\n## 🚀 Aether Bridge API - /month\n\nI've built an autonomous agent team management API that can manage FastAPI applications automatically.\n\n**Payment Link**: https://aether-pay.pages.dev\n\n### What It Offers\n- API key with priority rate limits\n- Council session logs & replay\n- Email support\n- Multi-chain crypto payments (Base USDC, Ethereum ETH, Polygon USDC)\n\n### Bridge API Features\n- Agent orchestration for FastAPI workflows\n- Job queue management for async FastAPI tasks\n- Browser automation for FastAPI testing\n- State management for FastAPI state\n- Monitoring and logging for FastAPI tracking\n- Webhook integrations for FastAPI events\n\n### Technical Details\n- **Fee**: 0.5% (XPTP)\n- **Settlement**: Instant\n- **No KYC required**\n- **No account signup**\n\n### Why This Matters for FastAPI\nFastAPI developers need:\n- Agent orchestration for complex FastAPI workflows\n- Job queue management for async FastAPI tasks\n- Browser automation for FastAPI testing\n- State management for FastAPI state\n\nAether Bridge API provides all of this with zero-config crypto payments.\n\n### Integration\nThe API is fully autonomous:\n- REST endpoints for all operations\n- Webhook support for async events\n- API key authentication\n- Rate limiting and monitoring\n\n**Aether Wallet**: 0xDe497AF77d0edf1c8B902Ae854987F67c375Fa0\n\n### Questions?\nFor API access support: bridge@a-to-mind.com\n\nWould this be useful as a FastAPI integration for autonomous agent management?", "source_type": "issue", "path": "issues/15738.json", "symbol": "Aether Bridge API - Autonomous Agent Team Management for FastAPI Apps", "url": "https://github.com/fastapi/fastapi/issues/15738", "start_line": null, "end_line": null} {"id": "issue::15762", "text": "# Issue #15762: 0.137.0: empty-path route nested under prefix-less outer include raises 'Prefix and path cannot be both empty'\nLabels: bug, question\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/15750\n\n
\n\nOriginally posted by **yeonghun-toggle** June 15, 2026\n### First Check\n\n- [X] I added a very descriptive title here.\n- [X] I used the GitHub search to find a similar question and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/pydantic/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom fastapi import FastAPI, APIRouter\r\n\r\nleaf = APIRouter()\r\n\r\n@leaf.get(\"\") # empty path\r\ndef list_items():\r\n return []\r\n\r\ninner = APIRouter()\r\ninner.include_router(leaf, prefix=\"/items\") # inner include HAS a prefix\r\n\r\napp = FastAPI()\r\napp.include_router(inner) # outer include has NO prefix\n```\n\n\n### Description\n\nOn **0.137.0**, the last line raises at app-construction time:\r\n`fastapi.exceptions.FastAPIError: Prefix and path cannot be both empty (path operation: list_items)`\r\n\r\nOn **0.136.3** and earlier the same code works and registers the route at `/items`.\r\n\r\nThis is a regression introduced by the route-tree refactor in #15745 (preserving `APIRouter`/`APIRoute` instances instead of flattening on include).\r\n\r\nIt only happens when an empty-path route (`path=\"\"`) is nested **and** at least one include hop in its ancestry has no prefix. If every hop carries a prefix it still works on 0.137.0. Verified on both versions:\r\n\r\n| setup | 0.136.3 | 0.137.0 |\r\n|---|---|---|\r\n| `app.include_router(leaf, prefix=\"/items\")` (single include) | `/items` | works |\r\n| `inner` and `app` both include with a prefix | `/v1/items` | works |\r\n| `inner` has prefix, `app.include_router(inner)` has no prefix | `/items` | **raises** |\n\n### Operating System\n\nmacOS\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.137.0\n\n### Pydantic Version\n\n2.13.4\n\n### Python Version\n\n3.12.13\n\n### Additional Context\n\nRoot-cause pointer (from a quick read of 0.137.0 `fastapi/routing.py`): in `include_router`, when `prefix` is empty, it recursively iterates the included route candidates and raises if any route's **raw** `path` is empty — without composing the prefixes contributed by the intermediate included routers.\r\nSo a leaf that was included with a prefix at an inner hop still trips the check at a prefix-less outer include.\r\nWhether the right fix is to validate the **effective** (prefix-composed) path, or to defer this validat\n---\nComment: This should be fixed in https://github.com/fastapi/fastapi/pull/15763 , available in FastAPI 0.137.1, just released. 🚀 ", "source_type": "issue", "path": "issues/15762.json", "symbol": "0.137.0: empty-path route nested under prefix-less outer include raises 'Prefix and path cannot be both empty'", "url": "https://github.com/fastapi/fastapi/issues/15762", "start_line": null, "end_line": null} {"id": "issue::15764", "text": "# Issue #15764: 0.137.0: `APIRoute.tags` invisible to type checkers in generate_unique_id_function (regression from #15745)\nLabels: bug\n\n### Discussed in https://github.com/fastapi/fastapi/discussions/15749\n\n
\n\nOriginally posted by **tedserbinski** June 15, 2026\n### First check\n\n- I searched existing discussions and issues — no existing report for this.\n- This is about a **type-checker regression in 0.137.0**, not a runtime bug (runtime is unaffected).\n\n### Summary\n\nIn **0.137.0**, the documented `generate_unique_id_function` pattern from [Advanced → Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/) — which reads `route.tags` — now fails static type checking. Type checkers report that `APIRoute` has no attribute `tags`, even though the docs still show exactly this code and it works fine at runtime.\n\nThis appears to be an unintended side-effect of #15745 (\"Refactor internals to preserve APIRouter and APIRoute instances\"): `APIRoute.__init__` was changed to delegate state-setting to a helper that receives `self` cast to the `_APIRouteLike` Protocol, and `APIRoute` itself no longer carries a class-level `tags` annotation. So the attribute is still assigned at runtime, but it's invisible to type checkers looking at the `APIRoute` type.\n\n### Reproducible example\n\nThis is the docs' own example (`docs_src/generate_clients/tutorial003_py310.py`):\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi.routing import APIRoute\n\n\ndef custom_generate_unique_id(route: APIRoute) -> str:\n return f\"{route.tags[0]}-{route.name}\"\n\n\napp = FastAPI(generate_unique_id_function=custom_generate_unique_id)\n```\n\nRunning a type checker (`ty`) over it on 0.137.0:\n\n```\nerror[unresolved-attribute]: Object of type `APIRoute` has no attribute `tags`\n --> repro.py:6:15\n |\n6 | return f\"{route.tags[0]}-{route.name}\"\n | ^^^^^^^^^^\n```\n\nAt runtime the same code builds the app and generates operation IDs correctly — only the static type surface is affected. `route.name` resolves fine; only `route.tags` is missing.\n\n### Expected behavior\n\n`route.tags` should remain visible to type checkers as a public attribute of `APIRoute` (it's part of the documented public callback contract), as it was in 0.136.x where `APIRoute.__init__` assigned `self.tags = tags or []` directly.\n\n### Environment\n\n- FastAPI: **0.137.0**\n- Python: 3.14\n- Type checker: `ty` 0.0.49 (also reproduces with strict Pyright per the same root cause); mypy may differ\n- OS: macOS\n\n### Possible fix\n\nAdd the lost class-level annotation back to `APIRoute` (e.g. `tags: list[str | Enum]`) so it matches what the `_APIRouteLike` Protocol already declares. Happy to open a PR if that direction is welcome.\n\nThanks for FastAPI! 🙏\n
\n---\nComment: This should be fixed in https://github.com/fastapi/fastapi/pull/15765 , available in FastAPI 0.137.1, just released. 🚀 ", "source_type": "issue", "path": "issues/15764.json", "symbol": "0.137.0: `APIRoute.tags` invisible to type checkers in generate_unique_id_function (regression from #15745)", "url": "https://github.com/fastapi/fastapi/issues/15764", "start_line": null, "end_line": null} {"id": "issue::15844", "text": "# Issue #15844: Barbora Maťaková\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n_No response_", "source_type": "issue", "path": "issues/15844.json", "symbol": "Barbora Maťaková", "url": "https://github.com/fastapi/fastapi/issues/15844", "start_line": null, "end_line": null} {"id": "issue::15845", "text": "# Issue #15845: Hyhdbdhuxjd s\n### Privileged issue\n\n- [x] I'm @tiangolo or he asked me directly to create an issue here.\n\n### Issue Content\n\n_No response_\n---\nComment: > ### Privileged issue\n> \n> * [x] I'm [@tiangolo](https://github.com/tiangolo) or he asked me directly to create an issue here.\n> \n> ### Issue Content\n> \n> _No response_\n\n\n---\nComment: [f.txt.json](https://github.com/user-attachments/files/29367351/f.txt.json)\n---\nComment: @chmelikadam20-gif please stop using this repo as a sandbox!", "source_type": "issue", "path": "issues/15845.json", "symbol": "Hyhdbdhuxjd s", "url": "https://github.com/fastapi/fastapi/issues/15845", "start_line": null, "end_line": null} {"id": "issue::15855", "text": "# Issue #15855: Named type alias body loses OpenAPI ref\n### Description\n\nFastAPI generates different OpenAPI schemas for a bare named Pydantic type alias and the same alias wrapped in `Annotated[..., Body()]`.\n\nThis came up while discussing the Pydantic side in https://github.com/pydantic/pydantic/issues/13236.\n\nExample:\n\n```py\nfrom typing import Annotated, Literal\n\nfrom fastapi import Body, FastAPI\nfrom pydantic import BaseModel, Field\n\napp = FastAPI()\n\n\nclass Cat(BaseModel):\n pet_type: Literal[\"cat\"]\n meows: int\n\n\nclass Dog(BaseModel):\n pet_type: Literal[\"dog\"]\n barks: float\n\n\nclass Lizard(BaseModel):\n pet_type: Literal[\"reptile\", \"lizard\"]\n scales: bool\n\n\ntype Pet = Annotated[\n Cat | Dog | Lizard,\n Field(discriminator=\"pet_type\"),\n]\n\n\n@app.post(\"/bare\")\ndef bare(pet: Pet):\n return pet\n\n\n@app.post(\"/body\")\ndef body(pet: Annotated[Pet, Body()]):\n return pet\n```\n\nExpected: both routes should generate the same request-body schema shape, with a named `Pet` component:\n\n```json\n{\n \"$ref\": \"#/components/schemas/Pet\"\n}\n```\n\nActual: `/body` references `#/components/schemas/Pet`, but `/bare` emits the discriminated union schema inline in the request body.\n\n### Why this matters\n\nFor normal `BaseModel` request bodies, FastAPI supports the ergonomic form:\n\n```py\ndef create_item(item: Item):\n ...\n```\n\nA named discriminated union is also a valid Pydantic body type, but today it needs the more verbose form to get the same named OpenAPI component behavior:\n\n```py\ndef create_pet(pet: Annotated[Pet, Body()]):\n ...\n```\n\n`RootModel` is not a good workaround because it adds a `.root` wrapper, while the desired request body is the flat union object itself.\n\n### Suggested fix\n\nFastAPI should preserve the named alias when it auto-infers a body parameter.\n\nIt looks like FastAPI currently unwraps `TypeAliasType` / PEP 695 aliases during parameter analysis. That may be useful for deciding whether the parameter is a body/query parameter, but the original alias should still be used when creating the inferred body field.\n\nSo this:\n\n```py\ndef create_pet(pet: Pet):\n ...\n```\n\nshould produce the same OpenAPI request-body schema as:\n\n```py\ndef create_pet(pet: Annotated[Pet, Body()]):\n ...\n```\n", "source_type": "issue", "path": "issues/15855.json", "symbol": "Named type alias body loses OpenAPI ref", "url": "https://github.com/fastapi/fastapi/issues/15855", "start_line": null, "end_line": null} {"id": "issue::1773", "text": "# Issue #1773: Automatically support HEAD method for all GET routes, as Starlette does\nLabels: feature, confirmed, reviewed\n### First check\r\n\r\n* [x] I added a very descriptive title to this issue.\r\n* [x] I used the GitHub search to find a similar issue and didn't find it.\r\n* [x] I searched the FastAPI documentation, with the integrated search.\r\n* [x] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n* [x] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n* [x] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n* [x] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n* [x] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n* [x] After submitting this, I commit to:\r\n * Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.\r\n * Or, I already hit the \"watch\" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.\r\n * Implement a Pull Request for a confirmed bug.\r\n\r\n### Example\r\n\r\nHere's a self-contained [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with my use case:\r\n\r\n```Python\r\nfrom fastapi import FastAPI\r\nimport pytest\r\nfrom fastapi.testclient import TestClient\r\n\r\napp = FastAPI()\r\n\r\n@app.get(\"/\")\r\ndef read_root():\r\n return {\"Hello\": \"World\"}\r\n\r\nclient = TestClient(app)\r\n\r\ndef test_index_head():\r\n response = client.head(\"/\")\r\n assert response.status_code == 200\r\n```\r\n\r\n### Description\r\n\r\n* The above test fails because the HEAD request returns a 405.\r\n* This is counterintuitive.\r\n\r\n### The solution you would like\r\n\r\n* To better support the HTTP standard, all routes that handle GET methods should automatically handle HEAD methods, too.\r\n* This is similar to what Starlette's router already does: https://github.com/encode/starlette/issues/45\r\n* This should happen without requiring the developer to do any additional work.\r\n\r\n### Describe alternatives you've considered\r\n\r\n* It's currently possible to do this manually by adding `@app.head` and a helper method for each route, but it's cumbersome:\r\n\r\n```\r\n@app.head(\"/\")\r\ndef read_root_head():\r\n return Response()\r\n```\r\n\r\n* It could also be done using middleware, but that would incur a performance overhead.\r\n\r\n### Environment\r\n\r\n* OS: [e.g. Linux / Windows / macOS]: Linux\r\n* FastAPI Version [e.g. 0.3.0]: 0.60.1\r\n* Python version: 3.8.5\r\n\n---\nComment: Not so, if you look at the related commit at https://github.com/encode/starlette/pull/132/files in `starlette/routing.py`, you can see Starlette adds `HEAD` methods automatically for every `Route` that supports `GET`, regardless of whether they are `FileResponse` or not.\r\n\r\nMany web frameworks do this by default too, e.g. Flask (https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods) and Django. It makes sense to do that because a server should respond to an `HTTP HEAD` request as defined in the spec, see e.g.:\r\n\r\nhttps://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD\r\n\r\n\"The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method. Such a request can be done before deciding to download a large resource to save bandwidth, for example.\"\r\n\r\nClients use this for cache invalidation. The server just needs to run the route method, respond with the headers but discard the response body. Ideally, FastAPI w\n---\nComment: 2024 is going to end, and it's not looking good.\r\nI came across this while setting up uptime monitoring.\n---\nComment: i found this issue today, and i play a bit, and this is what works for me (FastAPI 0.70.0):\r\n\r\n```python\r\n@router.head(\"/hello\")\r\n@router.get(\"/hello\")\r\ndef read_root():\r\n return {\"Hello\": \"World\"}\r\n```\r\n\r\nso with `httpie` this are the results. for GET method\r\n\r\n```bash\r\n$ http http://localhost:8080/hello\r\n```\r\n\r\n```http\r\nHTTP/1.1 200 OK\r\ncontent-length: 17\r\ncontent-type: application/json\r\ndate: Mon, 06 Dec 2021 15:14:18 GMT\r\nserver: uvicorn\r\n\r\n{\r\n \"Hello\": \"World\"\r\n}\r\n```\r\n\r\nand then for HEAD method:\r\n\r\n```bash\r\n$ http head http://localhost:8080/hello\r\n```\r\n\r\n```http\r\nHTTP/1.1 200 OK\r\ncontent-length: 17\r\ncontent-type: application/json\r\ndate: Mon, 06 Dec 2021 15:14:15 GMT\r\nserver: uvicorn\r\n```", "source_type": "issue", "path": "issues/1773.json", "symbol": "Automatically support HEAD method for all GET routes, as Starlette does", "url": "https://github.com/fastapi/fastapi/issues/1773", "start_line": null, "end_line": null} {"id": "issue::190", "text": "# Issue #190: Add section to docs about configuration\nLabels: feature, good first issue, docs, confirmed, reviewed\nIt would be useful if you could add a section to the (already excellent) docs on the recommended way to add app configuration. Would you recommend something based on Pydantic's BaseSettings, or on Starlette's Config?\r\nBoth would work I think, but your opinion on the optimal integration in FastAPI would be useful.\r\nTIA\n---\nComment: I think this issue can be closed. It would be helpful for newbies to see more info on config strategies with regard to testing vs production. But that might be asked too much for the FastAPI docs. \n---\nComment: It's far easier to override the settings when they are a dependency - is there a reason you're choosing not to do it that way?\n---\nComment: > The thing I haven't been able to figure out is how to override non dependency settings in testing\r\n\r\nOne of the things I am doing is relying on the behavior of `@lru_cache()` that it always gives me the same physical object. It feels a little hacky but this works pretty well for say, overriding database settings with a test database:\r\n\r\n```python\r\nclass DatabaseSettings(BaseSettings):\r\n name: str = \"postgres\"\r\n user: str = \"postgres\"\r\n password: str = \"postgres\"\r\n host: str = \"localhost\"\r\n port: int = 5432\r\n\r\n class Config:\r\n env_prefix = \"DB_\"\r\n\r\n @property\r\n def url(self) -> str:\r\n return f\"postgresql://{self.user}:{self.password}@{self.host}:{self.port}/{self.name}\"\r\n...\r\n...\r\n\r\n@lru_cache()\r\ndef get_database_settings() -> DatabaseSettings:\r\n return DatabaseSettings()\r\n```\r\n\r\nAnd then in my `conftest.py`:\r\n\r\n```python\r\n@pytest.fixture(scope=\"session\")\r\ndef postgres_server() -> Postgresql:\r\n postgres = testing.postgresql.Postgresql() # u", "source_type": "issue", "path": "issues/190.json", "symbol": "Add section to docs about configuration", "url": "https://github.com/fastapi/fastapi/issues/190", "start_line": null, "end_line": null} {"id": "issue::2008", "text": "# Issue #2008: Automatic OPTIONS request with route schema\nLabels: feature, investigate, reviewed\n### First check\r\n\r\nYes to all (great list of checks btw, I might copy them to pydantic 👍 )\r\n\r\n### Thank you\r\n\r\n@tiangolo FastAPI is great. This is the first time I've used it in production and I'm really impressed by both the range of features and particularly the documentation. I've written and deployed web apps using django, flask, aiohttp, starlette and now fastapi. FastAPI is the only python web framework I've seen to come close to django in terms of quality of documentation, it's definitely now my go-to web framework.\r\n\r\n**Thank you for the amazing project**, I feel really proud to have contributed to it indirectly.\r\n\r\n### Feature Request\r\n\r\nThe only thing I've seen missing from fastpi is support for informative OPTIONS requests for all/most/some endpoints, automatically included based in the route's definition.\r\n\r\nI effectively want the following:\r\n\r\n```py\r\nclass LoginForm(BaseModel):\r\n email: EmailStr\r\n password: SecretStr\r\n\r\n@app.post('/login/')\r\nasync def login(login_form: LoginForm):\r\n ...\r\n\r\n@app.options('/login/', include_in_schema=False)\r\nasync def login_options():\r\n return LoginForm.schema(by_alias=True)\r\n```\r\n\r\nWithout having to define the second endpoint. This is so my react frontend can build forms without having to duplicate the field definitions.\r\n\r\nI guess it might have to be slightly more complex to include parameters, query args and body model(s).\r\n\r\nI know I can get the information I need from `/openapi.json`, but that involves more processing in js and more data downloaded.\r\n\r\nIn the past when I've implemented a feature like this myself, I had to deal with `OPTIONS` requests associated with preflight checks separately, but that's relatively easy by looking for the `Access-Control-Request-Method` header.\r\n\r\nI guess if this feature was to be approved it would have to be optional, default off. I guess through a keyword arg on `FastAPI`, `include_router` and each route.\r\n\n---\nComment: No, I want the scheme for that URL, which is exactly what OPTIONS requests are for.\n---\nComment: I just ran into this unexpectedly when I saw a bunch of HTTP 405 responses using Swagger UI. It looks like Swagger UI assumes that every endpoint supports `OPTIONS`. It doesn't seem to impede the ability to send requests in the UI, but I assume it's used for _something_, otherwise it wouldn't be there. I was surprised that HTTP OPTIONS wasn't supported by default for FastAPI routes, at minimum returning an empty response with the standard `ALLOW` header.\r\n\r\nI also noticed that `HEAD` similarly was not supported by default, which can be useful for debugging and scripting. This again was surprising to me.\r\n\r\nSo here's my +1 for enabling both `OPTIONS` and `HEAD` by default in FastAPI routes.\n---\nComment: Sorry @whysage, I haven't had much free time. I will try to block out some time for it on Sunday night. Note that I'm not a repo maintainer so you will still need approval from someone else.", "source_type": "issue", "path": "issues/2008.json", "symbol": "Automatic OPTIONS request with route schema", "url": "https://github.com/fastapi/fastapi/issues/2008", "start_line": null, "end_line": null} {"id": "issue::3163", "text": "# Issue #3163: OpenAPI deepObject serialization for query parameters\nLabels: feature, reviewed\n### First check\r\n\r\n* [x] I added a very descriptive title to this issue.\r\n* [x] I used the GitHub search to find a similar issue and didn't find it.\r\n* [x] I searched the FastAPI documentation, with the integrated search.\r\n* [x] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n* [x] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n* [x] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n* [x] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n* [x] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n* [x] After submitting this, I commit to:\r\n * Implement a Pull Request for a confirmed bug - or implement the feature described in this issue :)\r\n\r\n### Description\r\n\r\nAllow usage of `deepObject` [serialization from OpenAPI 3](https://swagger.io/docs/specification/serialization/).\r\n\r\n### What it could look like\r\n\r\n\r\n```Python\r\nfrom fastapi import FastAPI\r\n\r\napp = FastAPI()\r\n\r\nclass UserQuery(BaseModel):\r\n role: str\r\n firstName: str\r\n\r\n@app.get(\"/\")\r\ndef read_root(id: Optional[UserQuery]):\r\n return {\"Hello\": \"World\"}\r\n```\r\n\r\nQuery:\r\n```\r\n/users?id[role]=admin&id[firstName]=Alex\r\n```\r\n\r\n### Related\r\n\r\n * https://github.com/tiangolo/fastapi/issues/245#issuecomment-762729917\r\n * Links to a good example: https://stackoverflow.com/questions/48491688/how-to-define-parameters-with-square-brackets-in-openapi-swagger\r\n * https://github.com/tiangolo/fastapi/issues/203\n---\nComment: How about just `Query(style=\"deepObject\")`?\n---\nComment: See also #283 for broader support of encoding styles.\r\n\r\nThis is the sort of issue where it's not entirely clear if the responsibility of supporting this should be on FastAPI or Pydantic. On one hand, it has to do with value parsing and encoding, which is something FastAPI tends to fully delegate to Pydantic, but on the other hand it's not part of JSON Schema, it's [an OpenAPI extension](https://oai.github.io/Documentation/specification-parameters.html#parameter-serialization-control) that [only applies to route parameter objects](https://github.com/OAI/OpenAPI-Specification/blob/main/schemas/v3.1/schema.yaml#L312-L413), and most of these encoding styles don't make sense in a JSON context (which is what pydantic is generally meant for).\r\n\r\nI would like to see these supported as well.\n---\nComment: For what it's worth I was able to support the full range of options in Xpresso, maybe that can serve as inspiration for FastAPI: https://xpresso-api.dev/0.42.3/tutorial/query_params/#customizing-deserialization", "source_type": "issue", "path": "issues/3163.json", "symbol": "OpenAPI deepObject serialization for query parameters", "url": "https://github.com/fastapi/fastapi/issues/3163", "start_line": null, "end_line": null} {"id": "issue::3317", "text": "# Issue #3317: Add support to lazy initialize `OAuth2` classes\nLabels: feature, reviewed\n### First check\r\n\r\n* [x] I added a very descriptive title to this issue.\r\n* [x] I used the GitHub search to find a similar issue and didn't find it.\r\n* [x] I searched the FastAPI documentation, with the integrated search.\r\n* [x] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n* [x] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n* [x] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n* [x] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n* [x] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n* [x] After submitting this, I commit to:\r\n * Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.\r\n * Or, I already hit the \"watch\" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.\r\n * Implement a Pull Request for a confirmed bug.\r\n\r\n\r\n\r\n### Example\r\n\r\nHere's a self-contained [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with my use case:\r\n\r\n\r\n\r\n```Python\r\nfrom fastapi import FastAPI, Security\r\nfrom fastapi.security import OAuth2AuthorizationCodeBearer\r\nfrom pydantic import BaseSettings\r\n\r\n\r\nclass Config(BaseSettings):\r\n OAUTH2_AUTHORIZATION_URL: str = \"https://example.com/authorize\"\r\n OAUTH2_TOKEN_URL: str = \"https://example.com/oauth/token\"\r\n\r\n\r\nconfig = Config()\r\napp = FastAPI()\r\n\r\n\r\noauth2_scheme = OAuth2AuthorizationCodeBearer(\r\n authorizationUrl=config.OAUTH2_AUTHORIZATION_URL,\r\n tokenUrl=config.OAUTH2_TOKEN_URL,\r\n)\r\n\r\n\r\n@app.get(\"/private-route\", dependencies=[Security(oauth2_scheme, scopes=[\"admin\"])])\r\nasync def private_route():\r\n pass\r\n```\r\n\r\n### Description\r\n\r\n\r\n\r\n* `Config` is instantiated at import time because `OAuth2AuthorizationCodeBearer` class needs values from it\r\n* I would like a way to lazy initialize `OAuth2AuthorizationCodeBearer` and other security classes\r\n\r\n### The solution you would like\r\n\r\n\n---\nComment: This is an interesting problem that I've encountered as well.\r\n\r\nI think that lazy-initializing things like this would be an ideal use case for the dependency injection system (i.e. load `Config`, then build `OAuth2AuthorizationCodeBearer` based on values from `Config`). Unfortunately, `Security` evaluates if it's dependency is a security model _at import/compile time_:\r\n\r\nhttps://github.com/tiangolo/fastapi/blob/996dfd05bde74d8778cf7ad7b5e0dd3588eef9db/fastapi/dependencies/utils.py#L144-L153\r\n\r\nI played around with modifying the DI system for this to work and made some progress. Here's a [sample implementation](https://github.com/adriangb/anydep/blob/30b503cbeb37c5bbf72b3467e07a2cb577bb9001/tests/test_callable_class.py#L47-L66).\n---\nComment: +1 for this. Related to my problem: https://github.com/tiangolo/fastapi/discussions/3958\r\n\r\nMy solution so far has also been wrapping the `OAuth2AuthorizationCodeBearer` for lazy initialization, I would however prefer to avoid the global variable all together and letting the \"auth service\" live within app context.\n---\nComment: I'm not certain if it's related or not, but I noticed that the request body isn't populated in http://127.0.0.1/docs when using `Annotated` and `Security` as the docs describe. For example:\r\n\r\n```python\r\nrouter = APIRouter()\r\n\r\n\r\n@router.post(\"/search\")\r\ndef search_handler(\r\n search: Annotated[\r\n SearchSchema,\r\n Security(oauth2_flow.get_authorization_validator(SearchSchema), scopes=[\"read\"]),\r\n ]\r\n) -> SearchSchema:\r\n return search\r\n```\r\n\r\nLeads docs like the screen shot attached. This is using FastAPI 0.103.2.\r\n\r\n\"image\"\r\n\r\nIf it's useful, the `get_authorization_validator` method returns a callable with a `Security` dependency on calling an `OAuth2AuthorizationCodeBearer` instance.\r\n\r\n```\r\nasync def oauth2_flow_authorization_validator(\r\n required_scopes: SecurityScopes, token: Annotated[str, Security(self._scheme)], request: Request\r\n)\r\n```\r\n", "source_type": "issue", "path": "issues/3317.json", "symbol": "Add support to lazy initialize `OAuth2` classes", "url": "https://github.com/fastapi/fastapi/issues/3317", "start_line": null, "end_line": null} {"id": "issue::3500", "text": "# Issue #3500: Allow access to the path operation's Response from within Dependencies using yield\nLabels: feature, confirmed, reviewed\n## Checks\r\n* [x] I added a very descriptive title to this issue.\r\n* [x] I used the GitHub search to find a similar issue and didn't find it.\r\n* [x] I searched the FastAPI documentation, with the integrated search.\r\n* [x] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n* [x] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n* [x] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n* [x] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n* [x] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n* [x] After submitting this, I commit to:\r\n * Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.\r\n * Or, I already hit the \"watch\" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.\r\n * Implement a Pull Request for a confirmed bug.\r\n\r\n## Problem\r\n\r\nFastAPI's dependency injection system supports generators as dependencies ([docs](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/)).\r\n\r\nBut there is currently no way to access a response generated by the path function in dependencies.\r\nWell, you _can_ access _a_ response object, but it doesn't get merged with the response from the path operation.\r\nHere's a minimal example:\r\n\r\n```python\r\nfrom fastapi import Depends, FastAPI, Response\r\nfrom fastapi.testclient import TestClient\r\n\r\n\r\ndef dependency(response: Response):\r\n yield\r\n assert response.status_code is None # so not the same response object!\r\n\r\n\r\napp = FastAPI(dependencies=[Depends(dependency)])\r\n\r\n@app.get(\"/\")\r\ndef root():\r\n return Response(status_code=400)\r\n\r\n\r\nclient = TestClient(app)\r\nres = client.get(\"/\")\r\n```\r\n\r\nIf your path operation accepts a Response object and modifies and returns the same object,\r\nthen you can access data from the path operation (like status code) in the dependency.\r\nOtherwise, you cannot.\r\n\r\n## Use case\r\n\r\nThe main use case I have for accessing this data is logging, but I imagine there may be others.\r\n\r\n## Proposed solution\r\n\r\nI _think_ that access to the final Response object could be enable via the generator's `send` functionality:\r\n\r\n```python\r\ndef dependency():\r\n response = yield\r\n assert response.status_code == 400\r\n```\r\n\r\nI think the main complication with this will be how FastAPI is using these generators internally.\r\nI believe they are being wrapped in context managers, which means the ability to use `.send()` is lost.\r\n\r\n## Alternatives\r\n\r\n### Changing how responses are merged\r\nI know somewhere within FastAPI Response objects get merged together.\r\nI'm not sure if it's possible, but an alternative might be to merge into the dependency's response object instead of creating a new object or merging into\n---\nComment: I have been thinking about this recently, and I think it makes sense.\r\n\r\nThe main problem is that the current implementation runs the exit code of the dependencies after the background tasks, which means it's all done after the response is sent.\r\n\r\nThe main idea was to allow using the same DB session in background tasks. But now I think that might not be as common, and might actually be even problematic, as the session would be held even while waiting for the network to return the response. For the specific use case of background tasks, it would probably make more sense to create a new DB session.\r\n\r\nAnd then dependencies could do a lot more things, modifying the response, logging, catching exceptions, setting headers and cookies, etc.\r\n\r\nThis would be a somewhat strong change, but I currently think it makes sense (even though before I thought the contrary).\r\n\r\nGiven that, I'm gonna open this again. Because unless I see something that would obviously break and be problematic for a lot \n---\nComment: +1 , would be nice to have it. Use case here is to generate a transaction id, log the incoming request+transaction id, use the transaction_id in the path code, then log response+transaction_id\n---\nComment: It could be really useful for cache implementation.", "source_type": "issue", "path": "issues/3500.json", "symbol": "Allow access to the path operation's Response from within Dependencies using yield", "url": "https://github.com/fastapi/fastapi/issues/3500", "start_line": null, "end_line": null} {"id": "issue::3920", "text": "# Issue #3920: I hope fastapi can support TypeVar\nLabels: feature, reviewed\n### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [x] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [x] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [x] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom typing import TypeVar, Generic\r\n\r\nfrom fastapi import Depends\r\nfrom sqlalchemy.orm import Session\r\n\r\nfrom app.core.database_engine.db_core import get_db\r\nfrom app.core.table_class import HasIdTable, DateCreateTable, DateCreateUpdateTable\r\n\r\nT = TypeVar('T', bound=HasIdTable)\r\n\r\n\r\nclass DbAdaptor(Generic[T]):\r\n def __init__(self, db: Session = Depends(get_db)):\r\n self.db = db\r\n\r\n def add(self, data_element: T, is_commit: bool = True) -> dict:\r\n if isinstance(data_element, DateCreateTable):\r\n data_element.create_stamp()\r\n self.db.add(data_element)\r\n if is_commit:\r\n self.db.commit()\r\n return data_element.get_dict()\r\n\r\n def read_by_id(self, id: int) -> T:\r\n rt: T = self.db.query(T).filter_by(id=id).first()\r\n return rt\r\n\r\n@bp.post('/create', description='create data to table')\r\ndef create(dba: DbAdaptor[SampleTable] = Depends(), data: str = Body(..., embed=True)):\r\n \"\"\"create data into the table\"\"\"\r\n data = SampleTable(data=data,\r\n link=str(random.randint(0, 99999)),\r\n title=data,\r\n content=data)\r\n return dba.add(data)\r\n```\r\n\r\n\r\n### Description\r\n\r\nI'm sorry, I'm no English user but I want to achieve this function.\r\n\r\nThis is the code in my project, but guess what happened when I opened swagger.\r\n\r\n![スクリーンショット 2021-09-18 22 48 27](https://user-images.githubusercontent.com/36730656/133891074-8ef8e5c2-0a41-4f58-bdbb-4c29c138127f.jpg)\r\n\r\nThis shouldn't happen.\r\n\r\nI just want to simplify the operation of the database.\r\n\r\nI just want to make operating the database easier through my code.\r\n\r\nUnder normal circumstances, I can do this without thinking about more specific details.\r\n\r\n\r\n\r\n### Wanted Solution\r\n\r\nI hope it can show a normal swagger.\r\n\r\n### Wanted Code\r\n\r\n```python\r\nnull\r\n```\r\n\r\n\r\n### Alternatives\r\n\r\ndo not use the typevar, But it's not fun.\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### FastAPI Version\r\n\r\nfastapi~=0.68.1\r\n\r\n### Python Version\r\n\r\npython3.8\r\n\r\n\n---\nComment: I faced the same problem.\r\n\r\nI want to dynamically create an API with a type set via `TypeVar`. But FastAPI puts the parameter in the query, not in the body\r\n\r\nHas someone found a solution to how this can be implemented?\r\n\r\n```python\r\nfrom typing import Generic, TypeVar\r\nfrom fastapi import APIRouter, FastAPI\r\nimport uvicorn\r\nfrom sqlmodel import SQLModel\r\n\r\nT_ = TypeVar('T_', bound=SQLModel)\r\n\r\n\r\nclass CreateAPI(Generic[T_]):\r\n def __init__(self, model: type[T_]):\r\n self.model = model\r\n\r\n def create_api(self, router: APIRouter) -> None:\r\n def foo(obj: T_) -> None:\r\n print(obj)\r\n\r\n router.add_api_route(\r\n '/foo',\r\n foo,\r\n description='create',\r\n name='create',\r\n methods=['POST'],\r\n )\r\n\r\n\r\nclass Foo(SQLModel):\r\n a: int = 1\r\n b: str = 'qwe'\r\n\r\napp = FastAPI()\r\nrouter = APIRouter(prefix='/api')\r\nCreateAPI(Foo).create_api(router)\r\napp.include_router(router)\r\n\r\nuvicorn.run(app)\r\n```\n---\nComment: So... if I'm not mistaken the issue is related to https://bugs.python.org/issue40897. Under the hood, FastAPI tries to get the signature using `inspect.signature` in `dependencies/utils.py:get_typed_signature`. It does not work as expected in case of generic classes, see:\r\n```python\r\nimport inspect\r\nfrom typing import TypeVar, Generic\r\n\r\nT = TypeVar(\"T\")\r\n\r\n\r\nclass GenericItem(Generic[T]):\r\n def __init__(self, value: T):\r\n self.value = value\r\n\r\n\r\nclass StringItem:\r\n def __init__(self, value: str):\r\n self.value = value\r\n\r\n\r\nprint(\"GenericItem[str]:\", inspect.signature(GenericItem[str]))\r\nprint(\"StringItem:\", inspect.signature(StringItem))\r\n```\r\n\r\ngives the following results:\r\n```\r\nStringItem: (value: str)\r\nGenericItem[str]: (*args, **kwargs)\r\n```\n---\nComment: I haven't checked your code but we just had a similar issue in our project and... it seems that the issue is fixed with python 3.9. Try to check that first and see if that helps.", "source_type": "issue", "path": "issues/3920.json", "symbol": "I hope fastapi can support TypeVar", "url": "https://github.com/fastapi/fastapi/issues/3920", "start_line": null, "end_line": null} {"id": "issue::4939", "text": "# Issue #4939: Response content longer than Content-Length error for DELETE and NoContent\nLabels: bug, answered, reviewed\n### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom fastapi import FastAPI, status\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.delete(\"/\", status_code=status.HTTP_204_NO_CONTENT)\r\ndef read_root():\r\n return None\r\n```\r\n\r\n\r\n### Description\r\n\r\nUpon requesting above code I got expected response but my logs shows that there is an error in uvicorn. The problem exists for DELETE method and NoContent response status code (for HEAD there is no such problem)\r\n\r\n```INFO: 127.0.0.1:46932 - \"DELETE / HTTP/1.1\" 204 No Content\r\nERROR: Exception in ASGI application\r\nTraceback (most recent call last):\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py\", line 372, in run_asgi\r\n result = await app(self.scope, self.receive, self.send)\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py\", line 75, in __call__\r\n return await self.app(scope, receive, send)\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/fastapi/applications.py\", line 269, in __call__\r\n await super().__call__(scope, receive, send)\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/starlette/applications.py\", line 124, in __call__\r\n await self.middleware_stack(scope, receive, send)\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 184, in __call__\r\n raise exc\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/starlette/middleware/errors.py\", line 162, in __call__\r\n await self.app(scope, receive, _send)\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/starlette/exceptions.py\", line 93, in __call__\r\n raise exc\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/starlette/exceptions.py\", line 82, in __call__\r\n await self.app(scope, receive, sender)\r\n File \"/home/user/PycharmProjects/sample_app/venv/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py\", line 21, in __call__\r\n raise e\r\n File \"/home/user/PycharmProjects/sample_app/ven\n---\nComment: This works as well:\r\n\r\n```python\r\nfrom fastapi import FastAPI, status, Response\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.delete(\"/\", status_code=status.HTTP_204_NO_CONTENT, response_class=Response)\r\ndef read_root():\r\n return None\r\n```\r\n\n---\nComment: Does FastAPI not have any regression tests? How is it that this wasn’t picked up when the starlette version was bumped?\n---\nComment: OK, so I looked into this a bit and the issue looks to be related to a recent change in Starlette (see [this discussion](https://github.com/encode/starlette/discussions/1635) for a repro without FastAPI in the mix). It may be that Starlette used to suppress the content return on a JSONResponse if the response code was 204, but it no longer does.\r\n\r\nI notice that, historically, there are a number of times when people have proposed adding code to FastAPI's router to set the response class explicitly (to `Response` rather than `JSONResponse`) in case the response code is one of the `STATUS_CODES_WITH_NO_BODY`. Given the amount of back-and-forth in the Starlette code around this, perhaps @tiangolo it's worth FastAPI making this change? If you agree I'm happy to take a shot at it. If not, how about explicit documentation in FastAPI that if you plan to return no content you need to specify the response class.", "source_type": "issue", "path": "issues/4939.json", "symbol": "Response content longer than Content-Length error for DELETE and NoContent", "url": "https://github.com/fastapi/fastapi/issues/4939", "start_line": null, "end_line": null} {"id": "issue::501", "text": "# Issue #501: document response in depends\nLabels: feature, confirmed, reviewed\n**Is your feature request related to a problem? Please describe.**\r\nNo not related to a problem.\r\n\r\nI'm using ` fastapi.security.api_key.APIKeyCookie` as a depends and it may raise `HTTPException(403, detail=\"Not authenticated\")` for any router it is used. So i have to document a 403 responses in all related router.\r\n\r\n\r\n**Describe the solution you'd like**\r\n\r\nCould there by a way when I'm using a class as Depends, document responses once as a class member or some thing else instead of document it many times in routers as fastAPI could find all depends of a router. \r\n\n---\nComment: But... why don't you just add this response in router registration?\r\n\r\nIt should look like that:\r\n```py\r\n# ...\r\napp.include_router(my_router, responses={403: ...})\r\n```\n---\nComment: @tiangolo , if you or anyone hasn't got a chance to look into this, shall I take a stab at this?\n---\nComment: @prostomarkeloff Like why using depends instead of calling it in handlers...", "source_type": "issue", "path": "issues/501.json", "symbol": "document response in depends", "url": "https://github.com/fastapi/fastapi/issues/501", "start_line": null, "end_line": null} {"id": "issue::5060", "text": "# Issue #5060: Normalize names of translations in the docs\nLabels: feature, reviewed\n### First Check\n\n- [X] I added a very descriptive title to this issue.\n- [X] I used the GitHub search to find a similar issue and didn't find it.\n- [X] I searched the FastAPI documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\n`mkdocs.yml`:\r\n\r\n\r\n alternate:\r\n - link: /\r\n name: en - English\r\n - link: /az/\r\n name: az\r\n - link: /de/\r\n name: de\r\n - link: /es/\r\n name: es - español\r\n - link: /fa/\r\n name: fa\r\n - link: /fr/\r\n name: fr - français\r\n - link: /id/\r\n name: id\r\n - link: /it/\r\n name: it - italiano\r\n - link: /ja/\r\n name: ja - 日本語\r\n - link: /ko/\r\n name: ko - 한국어\r\n - link: /nl/\r\n name: nl\r\n - link: /pl/\r\n name: pl\r\n - link: /pt/\r\n name: pt - português\r\n - link: /ru/\r\n name: ru - русский язык\r\n - link: /sq/\r\n name: sq - shqip\r\n - link: /tr/\r\n name: tr - Türkçe\r\n - link: /uk/\r\n name: uk - українська мова\r\n - link: /zh/\r\n name: zh - 汉语\n```\n\n\n### Description\n\nThe language menu in the docs contains the names of the language only for some of the available languages, while the rest only have the language code. This looks a little weird, and some developers might not even know what language code their language of choice has. Having the name specified for all languages would be much clearer.\r\n\r\n![names](https://user-images.githubusercontent.com/51365552/174988793-ec0f5dec-6f3d-4a81-8fb7-4f63654b18c8.png)\r\n\n\n### Wanted Solution\n\n1. The `mkdocs.yml` files should be updated to include the name of every available language.\r\n2. The command that generates a new language (e.g. `python ./scripts/docs.py new-lang sv`) should include a second parameter where a name can be specified (`python ./scripts/docs.py new-lang sv svenska`), **or** the instructions for adding a new translation (https://fastapi.tiangolo.com/contributing/#new-language) should at least describe how to add a name manually.\n\n### Wanted Code\n\n```python\n- link: /\r\n name: en - English\r\n - link: /az/\r\n name: az - Azərbaycanca\r\n - link: /de/\r\n name: de - Deutsch\r\n\r\n\r\netc.\n```\n\n\n### Alternatives\n\n_No response_\n\n### Operating System\n\nLinux\n\n### Operating System Details\n\n_No response_\n\n### FastAPI Version\n\n0.78.0\n\n### Python Version\n\n3.10.4\n\n### Additional Context\n\n_No response_\n---\nComment: > It would look a lot cleaner with standard naming.\r\n> \r\n> Instead of changing how users add the language what if we add a lookup function that uses data from [Lang codes](https://en.m.wikipedia.org/wiki/List_of_ISO_639-1_codes) to append the language to the name?\r\n\r\nWhile I like the idea, the language names in that article are in English but I believe they should be in the language itself (i.e. \"svenska\" instead of \"Swedish\")\n---\nComment: It would look a lot cleaner with standard naming. \r\n\r\nInstead of changing how users add the language what if we add a lookup function that uses data from [Lang codes](https://en.m.wikipedia.org/wiki/List_of_ISO_639-1_codes) to append the language to the name?\r\n\n---\nComment: I've pushed a code change that fixes this and would appreciate some 👀 and a 👍🏼 or comments", "source_type": "issue", "path": "issues/5060.json", "symbol": "Normalize names of translations in the docs", "url": "https://github.com/fastapi/fastapi/issues/5060", "start_line": null, "end_line": null} {"id": "issue::54", "text": "# Issue #54: tags at APIRouter level\nLabels: feature, answered, reviewed\n**Is your feature request related to a problem? Please describe.**\r\nI have a certain number of APIRouter, with for each of those a certain number of routes.\r\nI want all routes that belong to a given APIRouter to have the same tag, and currently I'm achieving this by adding `tags=['Tag1']` to each and every route.\r\n\r\n**Describe the solution you'd like**\r\nI got the feeling that I should be able to add the tags keyword directly to APIRouter and that all routes belonging to it inherit the tag.\r\n\r\nNot sure it makes sense though but I feel it would avoid some useless repetition\n---\nComment: Totally agree, good idea.\n---\nComment: @tiangolo Just tested it, works like a charm!\n---\nComment: Thanks for the report @nilsdebruin !\r\n\r\nThanks for the idea and PR @euri10 !\r\n\r\nI'll close this issue now as your PR is already merged and tested :grinning:\r\n\r\nBut feel free to add new comments or issues.", "source_type": "issue", "path": "issues/54.json", "symbol": "tags at APIRouter level", "url": "https://github.com/fastapi/fastapi/issues/54", "start_line": null, "end_line": null} {"id": "issue::5642", "text": "# Issue #5642: Managing out-of-date official doc translations \nLabels: feature, investigate, reviewed\n### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the FastAPI documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in FastAPI\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to FastAPI but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [X] I already checked if it is not related to FastAPI but to [Swagger UI](https://github.com/swagger-api/swagger-ui).\r\n- [X] I already checked if it is not related to FastAPI but to [ReDoc](https://github.com/Redocly/redoc).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Description\r\n\r\n* For contributing translations, it helps that tools or notification to Inform us out of dates translations.\r\n* (I believe) translated documents should shows if up-to-date or out-of-dates to original document. it help users.\r\n\r\n### Wanted Solution\r\n\r\nFirst of all, to solve how to search out-of-date translations, I created simple tools ([PR](#5641)) to compare committed date between original and translated docs. It works (but not correct).\r\n\r\nHow about merging the tools and collaborate them to notify it for developer and user with something like GitHub Actions?\r\n\r\n### Alternatives\r\n\r\n* adding revision number in each documents and parse it for developer. this way has advantages as for user to check if up-to-date or not when reading.\r\n\r\n### Additional Context\r\n\r\n_No response_\n---\nComment: > (I believe) translated documents should shows if up-to-date or out-of-dates to original document. it help users.\r\n\r\nAgree! Also, it could be misleading, if there's no such an information.\r\nI'm not sure if in the form you suggested, but It would be great to have such a functionality.\n---\nComment: > I created simple tools ([PR](https://github.com/tiangolo/fastapi/issues/5642#5641)) to compare committed date between original and translated docs\r\n\r\nCan you share the link to those tools with us? It seems that the link in the \"PR\" is wrong.\r\n\r\nAlso, it seems to me that it's more of a MkDocs localization problem than a FastAPI's.\r\n\r\nFrom what I could gather, there's no official way to handle outdated translations in MkDocs or ReadTheDocs 😬. \n---\nComment: I think this was solved (in a bit different way) by: https://github.com/fastapi/fastapi/pull/13933", "source_type": "issue", "path": "issues/5642.json", "symbol": "Managing out-of-date official doc translations ", "url": "https://github.com/fastapi/fastapi/issues/5642", "start_line": null, "end_line": null} {"id": "issue::608", "text": "# Issue #608: Swagger Offline Support\nLabels: feature, answered, reviewed\nHi everyone! When running the docs (Swagger) of FastAPI the UI is not rendered while offline. \r\n\r\nWould it be possible to include the swagger-ui-bundle.js and swagger-ui.css files (which are currently loaded via a CDN in https://github.com/tiangolo/fastapi/blob/4cea311e6ef112edfa1e42fde2f63b6ab2d7e413/fastapi/openapi/docs.py) in the project so those resources are available offline as well?\r\n\r\nBest regards\r\n\r\n\n---\nComment: Posting here in case anyone else finds this useful...\r\n\r\nI have the cut-and-paste from the instructions @tiangolo posted above way too many times in the past month, and finally just made a package that includes everything: https://pypi.org/project/fastapi-offline/\n---\nComment: Thanks for the help here everyone! :clap: :bow: \r\n\r\nThanks for reporting back and closing the issue :+1: \r\n\r\nThe new docs are here: https://fastapi.tiangolo.com/advanced/extending-openapi/#self-hosting-javascript-and-css-for-docs\n---\nComment: I created a repository which is called 'Fastapi Offline Swagger UI' to which is only download js and css files for offline usage. You can find here [ahmetoner/fastapi-offline-swagger-ui](https://github.com/ahmetoner/fastapi-offline-swagger-ui) \r\n\r\n\r\n### Install\r\nYou can install this software via pip or poetry.\r\n\r\n```sh\r\npip3 install git+https://github.com/ahmetoner/fastapi-offline-swagger-ui\r\n```\r\n\r\nor pyproject.toml\r\n\r\n```sh\r\n\r\n[tool.poetry.dependencies]\r\n...\r\nfastapi-offline-swagger-ui = {git = \"https://github.com/ahmetoner/fastapi-offline-swagger-ui\"}\r\n\r\n```\r\n\r\n\r\n### Usage Examples\r\nAfter installing the module, create a python file. Copy and run following.\r\n```py\r\nfrom fastapi import FastAPI, File, UploadFile, Query, applications\r\nfrom fastapi.responses import StreamingResponse, RedirectResponse\r\nfrom fastapi.staticfiles import StaticFiles\r\nfrom fastapi.openapi.docs import get_swagger_ui_html\r\nimport fastapi_offline_swagger_ui\r\n\r\napp = FastAPI()\r\n\r\n''' This following code block nece", "source_type": "issue", "path": "issues/608.json", "symbol": "Swagger Offline Support", "url": "https://github.com/fastapi/fastapi/issues/608", "start_line": null, "end_line": null} {"id": "issue::617", "text": "# Issue #617: Further develop startup and shutdown events\nLabels: feature, reviewed\nWhile the documentationn for FastAPI is in general extremely solid, there's a weakpoint that I feel hints at some underdevelopped feature within the framework, and that's [startup and shutdown events][1]. They are briefly mentionned (separately) with the startup event in particular being demonstrated like this :\r\n\r\n```py\r\nitems = {}\r\n\r\n\r\n@app.on_event(\"startup\")\r\nasync def startup_event():\r\n items[\"foo\"] = {\"name\": \"Fighters\"}\r\n items[\"bar\"] = {\"name\": \"Tenders\"}\r\n\r\n\r\n@app.get(\"/items/{item_id}\")\r\nasync def read_items(item_id: str):\r\n return items[item_id]\r\n```\r\n\r\n...which could very well be written like this:\r\n\r\n```py\r\nitems = {\r\n \"foo\": {\"name\": \"Fighters\"},\r\n \"bar\": {\"name\": \"Tenders\"}\r\n}\r\n\r\n@app.get(\"/items/{item_id}\")\r\nasync def read_items(item_id: str):\r\n return items[item_id]\r\n```\r\n\r\n...and therefore makes the feature look useless. The example for `shutdown` instead uses logging as an example, which makes it look like this would be the primary purposes for those events, while in reality, it's not.\r\n\r\n**Is your feature request related to a problem? Please describe.**\r\nThe problem is that, throughout the entire documentation, things like database connections are created in the global scope, at module import. While this would be fine in a regular Python application, this has a number of problems, especially with objects that have a side-effect outside the code itself, like database connections. To demonstrate this, I've made [a test structure that creates a lock file when initialized and deletes it when garbage collected][2].\r\n\r\nUsing it like this:\r\n```py\r\nfrom fastapi import FastAPI\r\nfrom lock import FileLock\r\n\r\napp = FastAPI()\r\nlock = FileLock(\"fastapi\")\r\n\r\n@app.get(\"/\")\r\nasync def root():\r\n return {\"message\": \"Hello World\"}\r\n```\r\n\r\n...does not work and the lock is not deleted before shutdown (I was actually expecting it to be closed properly, like SQLAlchemy does with its connections, but clearly there's a lot of extra magic going on with SQLAlchemy that I don't even come close to understanding). This is also extremely apparent when using the `--reload` option on Uvicorn, bcause the lock is *also* not released when the modules are reloaded, causing the import to fail and the server to crash. This would be one thing, but I've had a similar incident occur some time ago when, while developping in reload mode, I've actually managed to take up every connection on my PostgreSQL server because of that problem, since while SQLAlchemy is smart enough to cleanup on exit where my `FileLock` cannot, the same does not happen when hot-reloading code.\r\n\r\nSo that would be one thing; the documentation should probably go into more details about what those startup and shutdown events are for ([the Starlette documentation is a little more concrete about this][3], but no working code is given to illustrate this) and that should also be woven with the chapters about databases and such to make sure people don't miss it.\r\n\r\nExcept... That's n\n---\nComment: @tiangolo: Having the CM be accessible from user code is certainly going to be a huge improvement, but are there any plans of integrating it more seamlessly into the dependency injection framework like my original post suggested? To me, integrading dependency injection with lifetimes was always the point, and makes it so users don't need to store their initialized ressources anywhere or think about where they are being stored.\r\n\r\n```py\r\n@app.lifetime_dependency\r\ndef get_db_conn():\r\n\tconn_pool = create_engine(\"mydb:///\")\r\n\tyield conn_pool\r\n\tconn_pool.close()\r\n\t\r\n@app.get(\"/\")\r\nasync def root(conn: SQLAEngine = Depends(get_db_conn)):\r\n\tpass\r\n```\r\n\r\nThe new doc may also have to be adjusted soon, in light of the [ASGI lifespan state changes in Starlette](https://github.com/encode/starlette/pull/2060) that would now recommend storing state in the ASGI scope. Abstracting the lifetime CM behind special lifetime-scoped dependencies, like with my initial suggestion, would make it so that user c\n---\nComment: > Since you can store the database on the `app` instance (connected or not), I think it actually doesn't have to be that much uglier in practice; from my code:\r\n\r\nI personally like the idea of having databases be passed as dependencies instead of living in some kind of arbitrary app state pseudo-dict (fits more easily with strict typing, allows for mocking during tests, error can be thrown from the dependency if the DB isn't configured, etc.), but it's still a worthy alternative.\r\n\r\n> In general, I think there's an important tradeoff to be made between having an easy-to-follow tutorial, and only showing examples with \"production-worthy code organization\".\r\n\r\nThe tutorial highlights penty of more advanced functions, and I'm personally glad it does, even the ones I personally don't use. I would say that a section on how to properly setup ressources that are expected to live for the lifetime of the application so that they're cleaned up on shutdown and on reload is a good practice anyway \n---\nComment: The implementation from encode/starlette#799 just landed in the upstream master. No release as of the time I'm writing this, but enough to start designing around it.\r\n\r\nLike I've said before, I still believe we should deprecate raw startup and shutdown handlers in favor of wrapping the new generator method in our dependency system. Due to how Starlette is implementing it, some care might need to be taken to avoid breaking existing code using events (the `on_startup` and `on_shutdown` parameters to `Starlette()` cannot be used at the same time as the new `lifespan` parameter, and event handlers declared via the deprecated annotations will simply not fire).", "source_type": "issue", "path": "issues/617.json", "symbol": "Further develop startup and shutdown events", "url": "https://github.com/fastapi/fastapi/issues/617", "start_line": null, "end_line": null} {"id": "issue::639", "text": "# Issue #639: Execute dependencies in parallel instead of sequentially awaiting them\nLabels: feature, reviewed\n**Is your feature request related to a problem? Please describe.**\r\nFastAPI's Dependency injection system, while extremely useful, tends to run into a problem when several long-running dependencies are needed for a single route, such as with the example below.\r\n\r\n```py\r\nfrom fastapi import Depends, FastAPI\r\nfrom asyncio import sleep as async_sleep\r\n\r\napp = FastAPI()\r\n\r\nasync def get_big_data():\r\n await async_sleep(5)\r\n return \"𝐃𝐀𝐓𝐀\"\r\n\r\nasync def compute_pi():\r\n await async_sleep(5)\r\n return \"About 3, I think?\"\r\n\r\nasync def do_nothing_for_a_bit():\r\n await async_sleep(5)\r\n return \"Gotta let the CPU spin down for a bit, otherwise it could explode.\"\r\n\r\n@app.get(\"/do_long_thing\")\r\nasync def do_long_thing(\r\n big_dep1: str = Depends(get_big_data),\r\n big_dep2: str = Depends(compute_pi),\r\n big_dep3: str = Depends(do_nothing_for_a_bit)\r\n):\r\n return {\r\n 'big': big_dep1,\r\n 'pi': big_dep2,\r\n 'sleep': big_dep3,\r\n }\r\n```\r\n\r\nRunning that application and thentrying to access `/do_long_thing` takes 15 seconds to load, even though none of those dependencies are reliant on each other and could very well be ran in parallel.\r\n\r\n**Describe the solution you'd like**\r\nDon't await coroutines and threadpools here. Collect them into a list instead and gather them.\r\n\r\nhttps://github.com/tiangolo/fastapi/blob/3f9f4a0f8f7f5db50fbdc3157fe692cf4e68e13f/fastapi/dependencies/utils.py#L442-L456\r\n\r\n**Describe alternatives you've considered**\r\nAsking that the user take care of running and gathering those dependencies themselves is pretty much the only solution to this problem available right now (that I can see, anyway, there might be another one), which undermines the usefulness of the dependency injection system.\r\n\r\n\n---\nComment: Is this issue not resolved yet? It would be very useful if improved.\n---\nComment: that's indeed a good idea\n---\nComment: This seems like a good idea. But I think it would be quite non-trivial to implement. It would require sorting and finding the dependencies _before_ running them, to be able to know what can be parallelizable that doesn't require something else first.\r\n\r\nBut if you feel like trying to take a stab at it, a PR would be more than welcome. :muscle: ", "source_type": "issue", "path": "issues/639.json", "symbol": "Execute dependencies in parallel instead of sequentially awaiting them", "url": "https://github.com/fastapi/fastapi/issues/639", "start_line": null, "end_line": null} {"id": "issue::754", "text": "# Issue #754: First-class session support in FastAPI\nLabels: feature, reviewed\n### Is your feature request related to a problem\r\n\r\nAll of the security schemas currently supported by FastAPI rely on some sort of \"client-server synergy\" , where, for instance, the client is expected to know and remember an OAuth token or the user credentials to be sent via headers. This works fairly well for single-page applications, but if you need to integrate authentication to an app that uses templates, keeping track of that authentication data becomes a challenge. Most applications would use server-side sessions to deal with this, but FastAPI doesn't really have a system to deal with sessions right now.\r\n\r\n### Describe alternatives you've considered\r\n\r\n#### Using Starlette's SessionMiddleware\r\n\r\nWhile Starlette's `SessionMiddleware` is mentionned a number of times in the FastAPI documentation, it does not integrate very well with the framework itself . What it does is that it adds a `request.session` dict on the `Request` object that lets the backend store and retreive information from it, and just before the response get sent, [that dict is serialized, combined to a timestamp, signed, converted into base 64 and appended as a cookie](https://github.com/encode/starlette/blob/b8bd1696492e501bd617bd151278999c68b30e2b/starlette/middleware/sessions.py#L52-L63). The client is then expected to send theat cookie back so that the server so that information can be decoded and used. This is what the Django doc describes as [the cookie-based approach](https://docs.djangoproject.com/en/2.2/topics/http/sessions/).\r\n\r\nThe problem with all this is that the entire process happens outside of what FastAPI can handle, and therefore does not appear in the generated OpenAPI documentation as an authentication schema.\r\n\r\nHaving read the source for that middleware and the documentation for itsdangerous, I also understand that this kind of \"session blob\" authentication method isn't really supported by OpenAPI, since all supported auth methods are expected to use constants to handle authentication.\r\n\r\n### The solution you would like\r\n\r\nIdeally, I would like to see FastAPI adding some kind of `SessionCookie[T]` class to `fastapi.security`, that would register a cookie-based API key authentication method (which is [what Swagger reccomands](https://swagger.io/docs/specification/authentication/cookie-authentication/), since sessions are out of scope for the OpenAPI spec). Those \"API keys\" would be session tokens, much like the It should also register that routes that depend on that security schema may reply with a `Set-Cookie` header.\r\n\r\nThe question of how that data would be persisted afterwards is an open one. Having a one-size-fits-all implementation as the only one available could be constraining, so there's always the option of a `fastapi.security.sessions` namespace containing things like `MemorySessionStorage`, `DatabaseSessionStorage`, `FileSessionStorage` and so on.\r\n\r\n### Additional context\r\n\r\nMaybe something like this?\r\n\r\n```py\r\nfrom fastapi import Depends, \n---\nComment: It's already in place. More or less like the rest of the security tools. And it's compatible with the rest of the parts, integrated with OpenAPI (as possible), but probably most importantly, with dependencies.\r\n\r\nIt's just not properly documented yet. :disappointed: \r\n\r\nBut still, it works :rocket: e.g.\r\n\r\n```Python\r\nfrom fastapi import FastAPI, Form, HTTPException, Depends\r\nfrom fastapi.security import APIKeyCookie\r\nfrom starlette.responses import Response, HTMLResponse\r\nfrom starlette import status\r\nfrom jose import jwt\r\n\r\n\r\napp = FastAPI()\r\n\r\ncookie_sec = APIKeyCookie(name=\"session\")\r\n\r\nsecret_key = \"someactualsecret\"\r\n\r\nusers = {\"dmontagu\": {\"password\": \"secret1\"}, \"tiangolo\": {\"password\": \"secret2\"}}\r\n\r\n\r\ndef get_current_user(session: str = Depends(cookie_sec)):\r\n try:\r\n payload = jwt.decode(session, secret_key)\r\n user = users[payload[\"sub\"]]\r\n return user\r\n except Exception:\r\n raise HTTPException(\r\n status_code=status.HTTP_403_FORBIDDE\n---\nComment: @tiangolo: Using API key cookies to manage session data would be a bit of a hack at best. The JWT only works so long as it can fit all your session data in there (remember that [RFC 6265 does not require user agents to support individual cookies larger than 4096 bytes](https://tools.ietf.org/html/rfc6265#section-6.1), and [browsers don't usually go over that limit](http://browsercookielimits.squawky.net/)) or if you have a separate session storage backend, and it's then up to the user to implement said storage backend. Compare with my original post and with what encode/starlette#499 is trying to implement. Compare also to how [PHP handles sessions](https://www.php.net/manual/en/class.sessionhandler.php) by generating session keys and creating temporary `sess_{$sess_key}` files (that contain a serialized copy of the `$_SESSION` superglobal) while sending you the session key to use as your session cookie or to [Django's swappable session storage backends](https://docs.djangoproject.com/e\n---\nComment: Stuffing session data in an unencrypted JWT inside a cookie is not a good idea. It potentially leads to information disclosure and should be avoided as a practice. I think FastAPI could really benefit from solid session management - but this could of course easily be an external package. FastAPI contains all the ingredient to build it.", "source_type": "issue", "path": "issues/754.json", "symbol": "First-class session support in FastAPI", "url": "https://github.com/fastapi/fastapi/issues/754", "start_line": null, "end_line": null} {"id": "issue::9424", "text": "# Issue #9424: Using PEP 649 annotations with status code `204 No Content` and return type `None` raises `AssertionError`\n### Privileged issue\r\n\r\n- [X] I'm @tiangolo or he asked me directly to create an issue here.\r\n\r\n### Issue Content\r\n\r\n# Reproduce\r\n\r\n1. create FastAPI app\r\n2. create route with status code `204 No Content`\r\n3. add return type `None` to said route\r\n4. add future annotations ([PEP 649](https://peps.python.org/pep-0649/))\r\n\r\n```py\r\nfrom __future__ import annotations\r\n\r\nimport http\r\nimport logging\r\n\r\nfrom fastapi import FastAPI\r\n\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.post(\"/\", status_code=http.HTTPStatus.NO_CONTENT)\r\nasync def root() -> None:\r\n logging.info(\"endpoint called.\")\r\n```\r\n\r\n## Expected\r\n\r\nThe file above should boot up fine when running `uvicorn filename:app --reload`\r\n\r\n## Actual\r\n\r\nThis raises an error: `AssertionError: Status code 204 must not have a response body`\r\n\r\n### full traceback\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"//lib/python3.11/multiprocessing/process.py\", line 314, in _bootstrap\r\n self.run()\r\n File \"//lib/python3.11/multiprocessing/process.py\", line 108, in run\r\n self._target(*self._args, **self._kwargs)\r\n File \"//venv/lib/python3.11/site-packages/uvicorn/_subprocess.py\", line 76, in subprocess_started\r\n target(sockets=sockets)\r\n File \"//venv/lib/python3.11/site-packages/uvicorn/server.py\", line 59, in run\r\n return asyncio.run(self.serve(sockets=sockets))\r\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n File \"//lib/python3.11/asyncio/runners.py\", line 190, in run\r\n return runner.run(main)\r\n ^^^^^^^^^^^^^^^^\r\n File \"//lib/python3.11/asyncio/runners.py\", line 118, in run\r\n return self._loop.run_until_complete(task)\r\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n File \"uvloop/loop.pyx\", line 1517, in uvloop.loop.Loop.run_until_complete\r\n File \"//venv/lib/python3.11/site-packages/uvicorn/server.py\", line 66, in serve\r\n config.load()\r\n File \"//venv/lib/python3.11/site-packages/uvicorn/config.py\", line 471, in load\r\n self.loaded_app = import_from_string(self.app)\r\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n File \"//venv/lib/python3.11/site-packages/uvicorn/importer.py\", line 21, in import_from_string\r\n module = importlib.import_module(module_str)\r\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n File \"//lib/python3.11/importlib/__init__.py\", line 126, in import_module\r\n return _bootstrap._gcd_import(name[level:], package, level)\r\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n File \"\", line 1206, in _gcd_import\r\n File \"\", line 1178, in _find_and_load\r\n File \"\", line 1149, in _find_and_load_unlocked\r\n File \"\", line 690, in _load_unlocked\r\n File \"\", line 940, in exec_module\r\n File \"\", line 241, in _call_wit\n---\nComment: I think None should be a valid return type hint for 204 endpoints.\n\nI also think that anything different than None (or lack of return statement, which conceptually is the same, but since we retrieve the type hints at runtime, is a bit different, and that's why not using a type hint works as expected here) should raise an error.\n\nEDIT: Also, this is in the \"Issues\" tab. 😁👍\n---\nComment: An explicit `return NONE`, a bare `return`, or \"falling off the end of the function\" all return `None`, and since the return type hint is really about what the function returns (and not, strictly speaking) about the function's role as a 204 endpoint, `-> None` should be the required return type hint on such a function. See [this discussion](https://github.com/python/typing/issues/695#issuecomment-566742632).\n---\nComment: According to the provided [link](https://github.com/hofrob/fastapi-future-annotations) in the issue #9424, you're returning a string in the body \" \"\r\n\r\n``` python \r\n@app.post(\"/\", status_code=http.HTTPStatus.NO_CONTENT)\r\nasync def root() -> str:\r\n logging.info(\"endpoint called.\")\r\n return \"\"\r\n```\r\nEven if this was edit the code to \r\n``` python \r\n@app.post(\"/\", status_code=http.HTTPStatus.NO_CONTENT)\r\nasync def root() -> None:\r\n logging.info(\"endpoint called.\")\r\n return None\r\n```\r\nThe error is thrown because you are still returning something in body as json though it may not be valid \r\ne.g null\r\nWith the third approach of not returning anything like \r\n``` python \r\n@app.post(\"/\", status_code=http.HTTPStatus.NO_CONTENT)\r\nasync def root() -> None:\r\n logging.info(\"endpoint called.\")\r\n```\r\nThe server does not seem to complain one bit , maybe there's a special case or more information should be provided to resolve this issue . ", "source_type": "issue", "path": "issues/9424.json", "symbol": "Using PEP 649 annotations with status code `204 No Content` and return type `None` raises `AssertionError`", "url": "https://github.com/fastapi/fastapi/issues/9424", "start_line": null, "end_line": null}