docs/en/docs/how-to/separate-openapi-schemas.md::Do not Separate Schemas { #do-not-separate-schemas }::L80

# 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 }
## Do not Separate Schemas { #do-not-separate-schemas }

Now, there are some cases where you might want to have the **same schema for input and output**.

Probably 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.

In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`.

/// note

Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓

///

{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *}

### Same Schema for Input and Output Models in Docs { #same-schema-for-input-and-output-models-in-docs }

And now there will be one single schema for input and output for the model, only `Item`, and it will have `description` as **not required**:


docs/en/docs/how-to/testing-database.md::Testing a Database { #testing-a-database }::L1

# Doc: docs/en/docs/how-to/testing-database.md | Page: Testing a Database { #testing-a-database } | Section: Testing a Database { #testing-a-database }
# Testing a Database { #testing-a-database }

You can study about databases, SQL, and SQLModel in the [SQLModel docs](https://sqlmodel.tiangolo.com/). 🤓

There's a mini [tutorial on using SQLModel with FastAPI](https://sqlmodel.tiangolo.com/tutorial/fastapi/). ✨

That tutorial includes a section about [testing SQL databases](https://sqlmodel.tiangolo.com/tutorial/fastapi/tests/). 😎


docs/en/docs/index.md::FastAPI { #fastapi }::L1

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: FastAPI { #fastapi }
---
include_yaml:
  sponsors: data/sponsors.yml
---

# FastAPI { #fastapi }

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

---

**Documentation**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com)

**Source Code**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi)

---

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.

The key features are:

* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <dfn title="also known as auto-complete, autocompletion, IntelliSense">Completion</dfn> everywhere. Less time debugging.
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
* **Robust**: Get production-ready code. With automatic interactive documentation.
* **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/).

* estimation based on tests conducted by an internal development team, building production applications.


docs/en/docs/index.md::Sponsors { #sponsors }::L56

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Sponsors { #sponsors }
## Sponsors { #sponsors }

### Keystone Sponsor { #keystone-sponsor }

{% for sponsor in sponsors.keystone -%}

{% endfor -%}

### Gold Sponsors { #gold-sponsors }

{% for sponsor in sponsors.gold -%}

{% endfor -%}

### Silver Sponsors { #silver-sponsors }

{% for sponsor in sponsors.silver -%}

{% endfor %}

[Other sponsors](https://fastapi.tiangolo.com/fastapi-people/#sponsors)


docs/en/docs/index.md::Opinions { #opinions }::L88

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Opinions { #opinions }
## Opinions { #opinions }

    <button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-microsoft" aria-controls="fo-panel-microsoft" aria-selected="true" tabindex="0">

    </button>
    <button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-uber" aria-controls="fo-panel-uber" aria-selected="false" tabindex="-1">

    </button>
    <button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-netflix" aria-controls="fo-panel-netflix" aria-selected="false" tabindex="-1">

    </button>
    <button class="fastapi-opinions__tab" role="tab" type="button" id="fo-tab-cisco" aria-controls="fo-panel-cisco" aria-selected="false" tabindex="-1">

    </button>

"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."

— Kabir Khan, Microsoft (ref)

"We adopted the FastAPI library to spawn a REST server that can be queried to obtain predictions." [for Ludwig]

— Piero Molino, Yaroslav Dudin, Sai Sumanth Miryala, Uber (ref)

"Netflix is pleased to announce the open-source release of our crisis management orchestration framework: Dispatch!" [built with FastAPI]

— Kevin Glisson, Marc Vilanova, Forest Monsen, Netflix (ref)

"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."

— Deon Pillsbury, Cisco (ref)

"_[...] 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._"

Kabir Khan - Microsoft (ref)

---

"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"

Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)

---

"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"

Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)

---

"_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._"

Deon Pillsbury - Cisco (ref)

---


docs/en/docs/index.md::FastAPI Conf { #fastapi-conf }::L154

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: FastAPI Conf { #fastapi-conf }
## FastAPI Conf { #fastapi-conf }

[**FastAPI Conf '26**](https://fastapiconf.com) is happening on **October 28, 2026** in **Amsterdam, NL**. All about FastAPI, right from the source. 🎤


docs/en/docs/index.md::FastAPI mini documentary { #fastapi-mini-documentary }::L160

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: FastAPI mini documentary { #fastapi-mini-documentary }
## FastAPI mini documentary { #fastapi-mini-documentary }

There's a [FastAPI mini documentary](https://www.youtube.com/watch?v=mpR8ngthqiE) released at the end of 2025, you can watch it online:


docs/en/docs/index.md::**Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }::L166

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: **Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }
## **Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }

If you are building a CLI app to be used in the terminal instead of a web API, check out [**Typer**](https://typer.tiangolo.com/).

**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨ 🚀


docs/en/docs/index.md::Requirements { #requirements }::L174

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Requirements { #requirements }
## Requirements { #requirements }

FastAPI stands on the shoulders of giants:

* [Starlette](https://www.starlette.dev/) for the web parts.
* [Pydantic](https://docs.pydantic.dev/) for the data parts.


docs/en/docs/index.md::Installation { #installation }::L181

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Installation { #installation }
## Installation { #installation }

Create and activate a [virtual environment](https://fastapi.tiangolo.com/virtual-environments/) and then install FastAPI:

<div class="termy">

```console
$ pip install "fastapi[standard]"

---> 100%
```

</div>

**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals.


docs/en/docs/index.md::Example { #example }::L197

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Example { #example }
## Example { #example }

### Create it { #create-it }

Create a file `main.py` with:

```Python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}
```

Or use async def...

If your code uses `async` / `await`, use `async def`:

```Python hl_lines="7  12"
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}
```

**Note**:

If 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).

### Run it { #run-it }

Run the server with:

```console
$ fastapi dev

 ╭────────── FastAPI CLI - Development mode ───────────╮
 │                                                     │
 │  Serving at: http://127.0.0.1:8000                  │
 │                                                     │
 │  API docs: http://127.0.0.1:8000/docs               │
 │                                                     │
 │  Running in development mode, for production use:   │
 │                                                     │
 │  fastapi run                                        │
 │                                                     │
 ╰─────────────────────────────────────────────────────╯

INFO:     Will watch for changes in these directories: ['/home/user/code/awesomeapp']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [2248755] using WatchFiles
INFO:     Started server process [2248757]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
```

About the command fastapi dev...

The 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).

By default, `fastapi dev` will start with auto-reload enabled for local development.

You can read more about it in the [FastAPI CLI docs](https://fastapi.tiangolo.com/fastapi-cli/).

### Check it { #check-it }

Open your browser at [http://127.0.0.1:8000/items/5?q=somequery](http://127.0.0.1:8000/items/5?q=somequery).

You will see the JSON response as:

```JSON
{"item_id": 5, "q": "somequery"}
```

You already created an API that:

* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
* Both _paths_ take `GET` operations (also known as HTTP _methods_).
* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.

### Interactive API docs { #interactive-api-docs }

Now go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).

You will see the automatic interactive API documentation (provided by [Swagger UI](https://github.com/swagger-api/swagger-ui)):

![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)

### Alternative API docs { #alternative-api-docs }

And now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).

You will see the alternative automatic documentation (provided by [ReDoc](https://github.com/Rebilly/ReDoc)):

![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)


docs/en/docs/index.md::Example upgrade { #example-upgrade }::L321

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Example upgrade { #example-upgrade }
## Example upgrade { #example-upgrade }

Now modify the file `main.py` to receive a body from a `PUT` request.

Declare the body using standard Python types, thanks to Pydantic.

```Python hl_lines="2  7-10 23-25"
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool | None = None

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}
```

The `fastapi dev` server should reload automatically.

### Interactive API docs upgrade { #interactive-api-docs-upgrade }

Now go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).

* The interactive API documentation will be automatically updated, including the new body:

![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)

* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:

![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)

* 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:

![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)

### Alternative API docs upgrade { #alternative-api-docs-upgrade }

And now, go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).

* The alternative documentation will also reflect the new query parameter and body:

![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)

### Recap { #recap }

In summary, you declare **once** the types of parameters, body, etc. as function parameters.

You do that with standard modern Python types.

You don't have to learn a new syntax, the methods or classes of a specific library, etc.

Just standard **Python**.

For example, for an `int`:

```Python
item_id: int
```

or for a more complex `Item` model:

```Python
item: Item
```

...and with that single declaration you get:

* Editor support, including:
    * Completion.
    * Type checks.
* Validation of data:
    * Automatic and clear errors when the data is invalid.
    * Validation even for deeply nested JSON objects.
* <dfn title="also known as: serialization, parsing, marshalling">Conversion</dfn> of input data: coming from the network to Python data and types. Reading from:
    * JSON.
    * Path parameters.
    * Query parameters.
    * Cookies.
    * Headers.
    * Forms.
    * Files.
* <dfn title="also known as: serialization, parsing, marshalling">Conversion</dfn> of output data: converting from Python data and types to network data (as JSON):
    * Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
    * `datetime` objects.
    * `UUID` objects.
    * Database models.
    * ...and many more.
* Automatic interactive API documentation, including 2 alternative user interfaces:
    * Swagger UI.
    * ReDoc.

---

Coming back to the previous code example, **FastAPI** will:

* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
    * If it is not, the client will see a useful, clear error.
* 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.
    * As the `q` parameter is declared with `= None`, it is optional.
    * Without the `None` it would be required (as is the body in the case with `PUT`).
* For `PUT` requests to `/items/{item_id}`, read the body as JSON:
    * Check that it has a required attribute `name` that should be a `str`.
    * Check that it has a required attribute `price` that has to be a `float`.
    * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
    * All this would also work for deeply nested JSON objects.
* Convert from and to JSON automatically.
* Document everything with OpenAPI, that can be used by:
    * Interactive documentation systems.
    * Automatic client code generation systems, for many languages.
* Provide 2 interactive documentation web interfaces directly.

---

We just scratched the surface, but you already get the idea of how it all works.

Try changing the line with:

```Python
    return {"item_name": item.name, "item_id": item_id}
```

...from:

```Python
        ... "item_name": item.name ...
```

...to:

```Python
        ... "item_price": item.price ...
```

...and see how your editor will auto-complete the attributes and know their types:

![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)

For a more complete example including more features, see the Tutorial - User Guide.

**Spoiler alert**: the tutorial - user guide includes:

* Declaration of **parameters** from other different places such as: **headers**, **cookies**, **form fields** and **files**.
* How to set **validation constraints** such as `maximum_length` or `regex`.
* A very powerful and easy to use **<dfn title="also known as components, resources, providers, services, injectables">Dependency Injection</dfn>** system.
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
* **GraphQL** integration with [Strawberry](https://strawberry.rocks) and other libraries.
* Many extra features (thanks to Starlette) such as:
    * **WebSockets**
    * extremely easy tests based on HTTPX and `pytest`
    * **CORS**
    * **Cookie Sessions**
    * ...and more.

### Deploy your app (optional) { #deploy-your-app-optional }

You can optionally deploy your FastAPI app to [FastAPI Cloud](https://fastapicloud.com) with a single command. 🚀

```console
$ fastapi deploy

Deploying to FastAPI Cloud...

✅ Deployment successful!

🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev
```

The 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.

That's it! Now you can access your app at that URL. ✨

#### About FastAPI Cloud { #about-fastapi-cloud }

**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**.

It streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort.

It brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉

FastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨

#### Deploy to other cloud providers { #deploy-to-other-cloud-providers }

FastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.

Follow your cloud provider's guides to deploy FastAPI apps with them. 🤓


docs/en/docs/index.md::Performance { #performance }::L531

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Performance { #performance }
## Performance { #performance }

Independent 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). (*)

To understand more about it, see the section [Benchmarks](https://fastapi.tiangolo.com/benchmarks/).


docs/en/docs/index.md::Dependencies { #dependencies }::L537

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: Dependencies { #dependencies }
## Dependencies { #dependencies }

FastAPI depends on Pydantic and Starlette.

### `standard` Dependencies { #standard-dependencies }

When you install FastAPI with `pip install "fastapi[standard]"` it comes with the `standard` group of optional dependencies:

Used by Pydantic:

* [`email-validator`](https://github.com/JoshData/python-email-validator) - for email validation.

Used by Starlette:

* [`httpx`](https://www.python-httpx.org) - Required if you want to use the `TestClient`.
* [`jinja2`](https://jinja.palletsprojects.com) - Required if you want to use the default template configuration.
* [`python-multipart`](https://github.com/Kludex/python-multipart) - Required if you want to support form <dfn title="converting the string that comes from an HTTP request into Python data">"parsing"</dfn>, with `request.form()`.

Used by FastAPI:

* [`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.
* `fastapi-cli[standard]` - to provide the `fastapi` command.
    * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [FastAPI Cloud](https://fastapicloud.com).

### Without `standard` Dependencies { #without-standard-dependencies }

If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.

### Without `fastapi-cloud-cli` { #without-fastapi-cloud-cli }

If 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]"`.

### Additional Optional Dependencies { #additional-optional-dependencies }

There are some additional dependencies you might want to install.

Additional optional Pydantic dependencies:

* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.
* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.

Additional optional FastAPI dependencies:

* [`orjson`](https://github.com/ijl/orjson) - Required if you want to use `ORJSONResponse`.
* [`ujson`](https://github.com/esnme/ultrajson) - Required if you want to use `UJSONResponse`.


docs/en/docs/index.md::License { #license }::L583

# Doc: docs/en/docs/index.md | Page: FastAPI { #fastapi } | Section: License { #license }
## License { #license }

This project is licensed under the terms of the MIT license.


docs/en/docs/learn/index.md::Learn { #learn }::L1

# Doc: docs/en/docs/learn/index.md | Page: Learn { #learn } | Section: Learn { #learn }
# Learn { #learn }

Here are the introductory sections and the tutorials to learn **FastAPI**.

You could consider this a **book**, a **course**, the **official** and recommended way to learn FastAPI. 😎


# Doc: docs/en/docs/management.md | Page: Repository Management | Section: Repository Management
# Repository Management

Here's a short description of how the FastAPI repository is managed and maintained.


# Doc: docs/en/docs/management.md | Page: Repository Management | Section: Owner
## Owner

I, [@tiangolo](https://github.com/tiangolo), am the creator and owner of the FastAPI repository. 🤓

I normally give the final review to each PR before merging them. I make the final decisions on the project, I'm the [<abbr title="Benevolent Dictator For Life">BDFL</abbr>](https://en.wikipedia.org/wiki/Benevolent_dictator_for_life). 😅


# Doc: docs/en/docs/management.md | Page: Repository Management | Section: Team
## Team

There's a team of people that help manage and maintain the project. 😎

Learn more about it in [tiangolo.com - GitHub FastAPI](https://tiangolo.com/github-fastapi/).


# Doc: docs/en/docs/management.md | Page: Repository Management | Section: FastAPI Experts
## FastAPI Experts

The people that help others the most in GitHub Discussions can become [**FastAPI Experts**](./fastapi-people.md#fastapi-experts).

This is normally the best way to contribute to the project.


# Doc: docs/en/docs/management.md | Page: Repository Management | Section: External Help
## External Help

External help is very much appreciated. There are many ways to [help](./help-fastapi.md). ☕


docs/en/docs/newsletter.md::FastAPI and friends newsletter::L1

# Doc: docs/en/docs/newsletter.md | Page: FastAPI and friends newsletter | Section: FastAPI and friends newsletter
# FastAPI and friends newsletter

<iframe data-w-type="embedded" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://xr4n4.mjt.lu/wgt/xr4n4/hj5/form?c=40a44fa4" width="100%" style="height: 800px;"></iframe>

<script type="text/javascript" src="https://app.mailjet.com/pas-nc-embedded-v1.js"></script>


docs/en/docs/project-generation.md::Full Stack FastAPI Template { #full-stack-fastapi-template }::L1

# 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 }
# Full Stack FastAPI Template { #full-stack-fastapi-template }

Templates, 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. 🏁

You 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.

GitHub Repository: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)


docs/en/docs/project-generation.md::Full Stack FastAPI Template - Technology Stack and Features { #full-stack-fastapi-template-technology-stack-and-features }::L9

# 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 }
## Full Stack FastAPI Template - Technology Stack and Features { #full-stack-fastapi-template-technology-stack-and-features }

- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API.
  - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM).
  - 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management.
  - 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database.
- 🚀 [React](https://react.dev) for the frontend.
  - 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
  - 🎨 [Tailwind CSS](https://tailwindcss.com) and [shadcn/ui](https://ui.shadcn.com) for the frontend components.
  - 🤖 An automatically generated frontend client.
  - 🧪 [Playwright](https://playwright.dev) for End-to-End testing.
  - 🦇 Dark mode support.
- 🐋 [Docker Compose](https://www.docker.com) for development and production.
- 🔒 Secure password hashing by default.
- 🔑 JWT (JSON Web Token) authentication.
- 📫 Email based password recovery.
- ✅ Tests with [Pytest](https://pytest.org).
- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.
- 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates.
- 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions.


docs/en/docs/python-types.md::Python Types Intro { #python-types-intro }::L1

# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Python Types Intro { #python-types-intro }
# Python Types Intro { #python-types-intro }

Python has support for optional "type hints" (also called "type annotations").

These **"type hints"** or annotations are a special syntax that allows declaring the <dfn title="for example: str, int, float, bool">type</dfn> of a variable.

By declaring types for your variables, editors and tools can give you better support.

This 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.

**FastAPI** is all based on these type hints, they give it many advantages and benefits.

But even if you never use **FastAPI**, you would benefit from learning a bit about them.

/// note

If you are a Python expert, and you already know everything about type hints, skip to the next chapter.

///


docs/en/docs/python-types.md::Motivation { #motivation }::L21

# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Motivation { #motivation }
## Motivation { #motivation }

Let's start with a simple example:

{* ../../docs_src/python_types/tutorial001_py310.py *}

Calling this program outputs:

```
John Doe
```

The function does the following:

* Takes a `first_name` and `last_name`.
* Converts the first letter of each one to upper case with `title()`.
* <dfn title="Puts them together, as one. With the contents of one after the other.">Concatenates</dfn> them with a space in the middle.

{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}

### Edit it { #edit-it }

It's a very simple program.

But now imagine that you were writing it from scratch.

At some point you start defining the function, and you have the parameters ready...

But then you have to call "that method that converts the first letter to upper case".

Was it `upper`? Was it `uppercase`? `first_uppercase`? `capitalize`?

Then, you try with the old programmer's friend, editor autocompletion.

You type the first parameter of the function, `first_name`, then a dot (`.`) and then hit `Ctrl+Space` to trigger the completion.

But, sadly, you get nothing useful:

### Add types { #add-types }

Let's modify a single line from the previous version.

We will change exactly this fragment, the parameters of the function, from:

```Python
    first_name, last_name
```

to:

```Python
    first_name: str, last_name: str
```

That's it.

Those are the "type hints":

{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}

That is not the same as declaring default values like it would be with:

```Python
    first_name="john", last_name="doe"
```

It's a different thing.

We are using colons (`:`), not equals (`=`).

And adding type hints normally doesn't change what happens from what would happen without them.

But now, imagine you are again in the middle of creating that function, but with type hints.

At the same point, you try to trigger the autocomplete with `Ctrl+Space` and you see:

With that, you can scroll, seeing the options, until you find the one that "rings a bell":


docs/en/docs/python-types.md::More motivation { #more-motivation }::L105

# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: More motivation { #more-motivation }
## More motivation { #more-motivation }

Check this function, it already has type hints:

{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}

Because the editor knows the types of the variables, you don't only get completion, you also get error checks:

<img src="/img/python-types/image04.png">

Now you know that you have to fix it, convert `age` to a string with `str(age)`:

{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}


docs/en/docs/python-types.md::Declaring types { #declaring-types }::L119

# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Declaring types { #declaring-types }
## Declaring types { #declaring-types }

You just saw the main place to declare type hints. As function parameters.

This is also the main place you would use them with **FastAPI**.

### Simple types { #simple-types }

You can declare all the standard Python types, not only `str`.

You can use, for example:

* `int`
* `float`
* `bool`
* `bytes`

{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}

### `typing` module { #typing-module }

For 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`:

```python
from typing import Any

def some_function(data: Any):
    print(data)
```

### Generic types { #generic-types }

Some types can take "type parameters" in square brackets, to define their internal types, for example a "list of strings" would be declared `list[str]`.

These types that can take type parameters are called **Generic types** or **Generics**.

You can use the same builtin types as generics (with square brackets and types inside):

* `list`
* `tuple`
* `set`
* `dict`

#### List { #list }

For example, let's define a variable to be a `list` of `str`.

Declare the variable, with the same colon (`:`) syntax.

As the type, put `list`.

As the list is a type that contains some internal types, you put them in square brackets:

{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}

/// note

Those internal types in the square brackets are called "type parameters".

In this case, `str` is the type parameter passed to `list`.

///

That means: "the variable `items` is a `list`, and each of the items in this list is a `str`".

By doing that, your editor can provide support even while processing items from the list:

Without types, that's almost impossible to achieve.

Notice that the variable `item` is one of the elements in the list `items`.

And still, the editor knows it is a `str`, and provides support for that.

#### Tuple and Set { #tuple-and-set }

You would do the same to declare `tuple`s and `set`s:

{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}

This means:

* The variable `items_t` is a `tuple` with 3 items, an `int`, another `int`, and a `str`.
* The variable `items_s` is a `set`, and each of its items is of type `bytes`.

#### Dict { #dict }

To define a `dict`, you pass 2 type parameters, separated by commas.

The first type parameter is for the keys of the `dict`.

The second type parameter is for the values of the `dict`:

{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}

This means:

* The variable `prices` is a `dict`:
    * The keys of this `dict` are of type `str` (let's say, the name of each item).
    * The values of this `dict` are of type `float` (let's say, the price of each item).

#### Union { #union }

You can declare that a variable can be any of **several types**, for example, an `int` or a `str`.

To define it you use the <dfn title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</dfn> to separate both types.

This is called a "union", because the variable can be anything in the union of those two sets of types.

```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```

This means that `item` could be an `int` or a `str`.

#### Possibly `None` { #possibly-none }

You can declare that a value could have a type, like `str`, but that it could also be `None`.

//// tab | Python 3.10+

```Python hl_lines="1"
{!> ../../docs_src/python_types/tutorial009_py310.py!}
```

////

Using `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.

### Classes as types { #classes-as-types }

You can also declare a class as the type of a variable.

Let's say you have a class `Person`, with a name:

{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}

Then you can declare a variable to be of type `Person`:

{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}

And then, again, you get all the editor support:

Notice that this means "`one_person` is an **instance** of the class `Person`".

It doesn't mean "`one_person` is the **class** called `Person`".


docs/en/docs/python-types.md::Pydantic models { #pydantic-models }::L270

# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Pydantic models { #pydantic-models }
## Pydantic models { #pydantic-models }

[Pydantic](https://docs.pydantic.dev/) is a Python library to perform data validation.

You declare the "shape" of the data as classes with attributes.

And each attribute has a type.

Then 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.

And you get all the editor support with that resulting object.

An example from the official Pydantic docs:

{* ../../docs_src/python_types/tutorial011_py310.py *}

/// note

To learn more about [Pydantic, check its docs](https://docs.pydantic.dev/).

///

**FastAPI** is all based on Pydantic.

You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md).


docs/en/docs/python-types.md::Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }::L296

# 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 }
## Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }

Python also has a feature that allows putting **additional <dfn title="Data about the data, in this case, information about the type, e.g. a description.">metadata</dfn>** in these type hints using `Annotated`.

You can import `Annotated` from `typing`.

{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}

Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.

But you can use this space in `Annotated` to provide **FastAPI** with additional metadata about how you want your application to behave.

The 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.

For now, you just need to know that `Annotated` exists, and that it's standard Python. 😎

Later you will see how **powerful** it can be.

/// tip

The 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. ✨

And also that your code will be very compatible with many other Python tools and libraries. 🚀

///


docs/en/docs/python-types.md::Type hints in **FastAPI** { #type-hints-in-fastapi }::L322

# Doc: docs/en/docs/python-types.md | Page: Python Types Intro { #python-types-intro } | Section: Type hints in **FastAPI** { #type-hints-in-fastapi }
## Type hints in **FastAPI** { #type-hints-in-fastapi }

**FastAPI** takes advantage of these type hints to do several things.

With **FastAPI** you declare parameters with type hints and you get:

* **Editor support**.
* **Type checks**.

...and **FastAPI** uses the same declarations to:

* **Define requirements**: from request path parameters, query parameters, headers, bodies, dependencies, etc.
* **Convert data**: from the request to the required type.
* **Validate data**: coming from each request:
    * Generating **automatic errors** returned to the client when the data is invalid.
* **Document** the API using OpenAPI:
    * which is then used by the automatic interactive documentation user interfaces.

This might all sound abstract. Don't worry. You'll see all this in action in the [Tutorial - User Guide](tutorial/index.md).

The 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.

/// note

If 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).

///


# Doc: docs/en/docs/reference/apirouter.md | Page: `APIRouter` class | Section: `APIRouter` class
# `APIRouter` class

Here's the reference information for the `APIRouter` class, with all its parameters, attributes and methods.

You can import the `APIRouter` class directly from `fastapi`:

```python
from fastapi import APIRouter
```

::: fastapi.APIRouter
    options:
        members:
            - websocket
            - include_router
            - frontend
            - get
            - put
            - post
            - delete
            - options
            - head
            - patch
            - trace
            - on_event


docs/en/docs/reference/background.md::Background Tasks - `BackgroundTasks`::L1

# Doc: docs/en/docs/reference/background.md | Page: Background Tasks - `BackgroundTasks` | Section: Background Tasks - `BackgroundTasks`
# Background Tasks - `BackgroundTasks`

You 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.

You can import it directly from `fastapi`:

```python
from fastapi import BackgroundTasks
```

::: fastapi.BackgroundTasks


# Doc: docs/en/docs/reference/dependencies.md | Page: Dependencies - `Depends()` and `Security()` | Section: `Depends()`
## `Depends()`

Dependencies are handled mainly with the special function `Depends()` that takes a callable.

Here is the reference for it and its parameters.

You can import it directly from `fastapi`:

```python
from fastapi import Depends
```

::: fastapi.Depends


# Doc: docs/en/docs/reference/dependencies.md | Page: Dependencies - `Depends()` and `Security()` | Section: `Security()`
## `Security()`

For many scenarios, you can handle security (authorization, authentication, etc.) with dependencies, using `Depends()`.

But when you want to also declare OAuth2 scopes, you can use `Security()` instead of `Depends()`.

You can import `Security()` directly from `fastapi`:

```python
from fastapi import Security
```

::: fastapi.Security


# Doc: docs/en/docs/reference/encoders.md | Page: Encoders - `jsonable_encoder` | Section: Encoders - `jsonable_encoder`
# Encoders - `jsonable_encoder`

::: fastapi.encoders.jsonable_encoder


docs/en/docs/reference/exceptions.md::Exceptions - `HTTPException` and `WebSocketException`::L1

# Doc: docs/en/docs/reference/exceptions.md | Page: Exceptions - `HTTPException` and `WebSocketException` | Section: Exceptions - `HTTPException` and `WebSocketException`
# Exceptions - `HTTPException` and `WebSocketException`

These are the exceptions that you can raise to show errors to the client.

When 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.

You can use:

* `HTTPException`
* `WebSocketException`

These exceptions can be imported directly from `fastapi`:

```python
from fastapi import HTTPException, WebSocketException
```

::: fastapi.HTTPException

::: fastapi.WebSocketException


# Doc: docs/en/docs/reference/fastapi.md | Page: `FastAPI` class | Section: `FastAPI` class
# `FastAPI` class

Here's the reference information for the `FastAPI` class, with all its parameters, attributes and methods.

You can import the `FastAPI` class directly from `fastapi`:

```python
from fastapi import FastAPI
```

::: fastapi.FastAPI
    options:
        members:
            - openapi_version
            - webhooks
            - state
            - dependency_overrides
            - openapi
            - websocket
            - include_router
            - frontend
            - get
            - put
            - post
            - delete
            - options
            - head
            - patch
            - trace
            - on_event
            - middleware
            - exception_handler


# Doc: docs/en/docs/reference/httpconnection.md | Page: `HTTPConnection` class | Section: `HTTPConnection` class
# `HTTPConnection` class

When 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`.

You can import it from `fastapi.requests`:

```python
from fastapi.requests import HTTPConnection
```

::: fastapi.requests.HTTPConnection


# Doc: docs/en/docs/reference/index.md | Page: Reference | Section: Reference
# Reference

Here's the reference or code API, the classes, functions, parameters, attributes, and
all the FastAPI parts you can use in your applications.

If you want to **learn FastAPI** you are much better off reading the
[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/).


# Doc: docs/en/docs/reference/middleware.md | Page: Middleware | Section: Middleware
# Middleware

There are several middlewares available provided by Starlette directly.

Read more about them in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/).

::: fastapi.middleware.cors.CORSMiddleware

It can be imported from `fastapi`:

```python
from fastapi.middleware.cors import CORSMiddleware
```

::: fastapi.middleware.gzip.GZipMiddleware

It can be imported from `fastapi`:

```python
from fastapi.middleware.gzip import GZipMiddleware
```

::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware

It can be imported from `fastapi`:

```python
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
```

::: fastapi.middleware.trustedhost.TrustedHostMiddleware

It can be imported from `fastapi`:

```python
from fastapi.middleware.trustedhost import TrustedHostMiddleware
```


# Doc: docs/en/docs/reference/openapi/docs.md | Page: OpenAPI `docs` | Section: OpenAPI `docs`
# OpenAPI `docs`

Utilities to handle OpenAPI automatic UI documentation, including Swagger UI (by default at `/docs`) and ReDoc (by default at `/redoc`).

::: fastapi.openapi.docs.get_swagger_ui_html

::: fastapi.openapi.docs.get_redoc_html

::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html

::: fastapi.openapi.docs.swagger_ui_default_parameters


# Doc: docs/en/docs/reference/openapi/index.md | Page: OpenAPI | Section: OpenAPI
# OpenAPI

There are several utilities to handle OpenAPI.

You normally don't need to use them unless you have a specific advanced use case that requires it.


# Doc: docs/en/docs/reference/openapi/models.md | Page: OpenAPI `models` | Section: OpenAPI `models`
# OpenAPI `models`

OpenAPI Pydantic models used to generate and validate the generated OpenAPI.

::: fastapi.openapi.models


# Doc: docs/en/docs/reference/parameters.md | Page: Request Parameters | Section: Request Parameters
# Request Parameters

Here's the reference information for the request parameters.

These are the special functions that you can put in *path operation function* parameters or dependency functions with `Annotated` to get data from the request.

It includes:

* `Query()`
* `Path()`
* `Body()`
* `Cookie()`
* `Header()`
* `Form()`
* `File()`

You can import them all directly from `fastapi`:

```python
from fastapi import Body, Cookie, File, Form, Header, Path, Query
```

::: fastapi.Query

::: fastapi.Path

::: fastapi.Body

::: fastapi.Cookie

::: fastapi.Header

::: fastapi.Form

::: fastapi.File


# Doc: docs/en/docs/reference/request.md | Page: `Request` class | Section: `Request` class
# `Request` class

You 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.

Read more about it in the [FastAPI docs about using Request directly](https://fastapi.tiangolo.com/advanced/using-request-directly/)

You can import it directly from `fastapi`:

```python
from fastapi import Request
```

/// tip

When 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`.

///

::: fastapi.Request


# Doc: docs/en/docs/reference/response.md | Page: `Response` class | Section: `Response` class
# `Response` class

You 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.

You can also use it directly to create an instance of it and return it from your *path operations*.

Read more about it in the [FastAPI docs about returning a custom Response](https://fastapi.tiangolo.com/advanced/response-directly/#returning-a-custom-response)

You can import it directly from `fastapi`:

```python
from fastapi import Response
```

::: fastapi.Response


docs/en/docs/reference/responses.md::Custom Response Classes - File, HTML, Redirect, Streaming, etc.::L1

# 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.
# Custom Response Classes - File, HTML, Redirect, Streaming, etc.

There are several custom response classes you can use to create an instance and return them directly from your *path operations*.

Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/).

You can import them directly from `fastapi.responses`:

```python
from fastapi.responses import (
    FileResponse,
    HTMLResponse,
    JSONResponse,
    ORJSONResponse,
    PlainTextResponse,
    RedirectResponse,
    Response,
    StreamingResponse,
    UJSONResponse,
)
```


# Doc: docs/en/docs/reference/responses.md | Page: Custom Response Classes - File, HTML, Redirect, Streaming, etc. | Section: FastAPI Responses
## FastAPI Responses

There were a couple of custom FastAPI response classes that were intended to optimize JSON performance.

However, 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/).

That way, Pydantic will serialize the data into JSON bytes on the Rust side, which will achieve better performance than these custom JSON responses.

Read 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).

::: fastapi.responses.UJSONResponse
    options:
        members:
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie

::: fastapi.responses.ORJSONResponse
    options:
        members:
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie


# Doc: docs/en/docs/reference/responses.md | Page: Custom Response Classes - File, HTML, Redirect, Streaming, etc. | Section: Starlette Responses
## Starlette Responses

You 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/).

::: fastapi.responses.FileResponse
    options:
        members:
            - chunk_size
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie

::: fastapi.responses.HTMLResponse
    options:
        members:
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie

::: fastapi.responses.JSONResponse
    options:
        members:
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie

::: fastapi.responses.PlainTextResponse
    options:
        members:
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie

::: fastapi.responses.RedirectResponse
    options:
        members:
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie

::: fastapi.responses.Response
    options:
        members:
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie

::: fastapi.responses.StreamingResponse
    options:
        members:
            - body_iterator
            - charset
            - status_code
            - media_type
            - body
            - background
            - raw_headers
            - render
            - init_headers
            - headers
            - set_cookie
            - delete_cookie


# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: Security Tools
# Security Tools

When you need to declare dependencies with OAuth2 scopes you use `Security()`.

But you still need to define what is the dependable, the callable that you pass as a parameter to `Depends()` or `Security()`.

There 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.

You can import them from `fastapi.security`:

```python
from fastapi.security import (
    APIKeyCookie,
    APIKeyHeader,
    APIKeyQuery,
    HTTPAuthorizationCredentials,
    HTTPBasic,
    HTTPBasicCredentials,
    HTTPBearer,
    HTTPDigest,
    OAuth2,
    OAuth2AuthorizationCodeBearer,
    OAuth2PasswordBearer,
    OAuth2PasswordRequestForm,
    OAuth2PasswordRequestFormStrict,
    OpenIdConnect,
    SecurityScopes,
)
```

Read more about them in the [FastAPI docs about Security](https://fastapi.tiangolo.com/tutorial/security/).


docs/en/docs/reference/security/index.md::API Key Security Schemes::L33

# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: API Key Security Schemes
## API Key Security Schemes

::: fastapi.security.APIKeyCookie

::: fastapi.security.APIKeyHeader

::: fastapi.security.APIKeyQuery


# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: HTTP Authentication Schemes
## HTTP Authentication Schemes

::: fastapi.security.HTTPBasic

::: fastapi.security.HTTPBearer

::: fastapi.security.HTTPDigest


# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: HTTP Credentials
## HTTP Credentials

::: fastapi.security.HTTPAuthorizationCredentials

::: fastapi.security.HTTPBasicCredentials


# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OAuth2 Authentication
## OAuth2 Authentication

::: fastapi.security.OAuth2

::: fastapi.security.OAuth2AuthorizationCodeBearer

::: fastapi.security.OAuth2PasswordBearer


# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OAuth2 Password Form
## OAuth2 Password Form

::: fastapi.security.OAuth2PasswordRequestForm

::: fastapi.security.OAuth2PasswordRequestFormStrict


docs/en/docs/reference/security/index.md::OAuth2 Security Scopes in Dependencies::L69

# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OAuth2 Security Scopes in Dependencies
## OAuth2 Security Scopes in Dependencies

::: fastapi.security.SecurityScopes


# Doc: docs/en/docs/reference/security/index.md | Page: Security Tools | Section: OpenID Connect
## OpenID Connect

::: fastapi.security.OpenIdConnect


docs/en/docs/reference/staticfiles.md::Static Files - `StaticFiles`::L1

# Doc: docs/en/docs/reference/staticfiles.md | Page: Static Files - `StaticFiles` | Section: Static Files - `StaticFiles`
# Static Files - `StaticFiles`

You can use the `StaticFiles` class to serve static files, like JavaScript, CSS, images, etc.

Read more about it in the [FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/).

You can import it directly from `fastapi.staticfiles`:

```python
from fastapi.staticfiles import StaticFiles
```

::: fastapi.staticfiles.StaticFiles


# Doc: docs/en/docs/reference/status.md | Page: Status Codes | Section: Status Codes
# Status Codes

You can import the `status` module from `fastapi`:

```python
from fastapi import status
```

`status` is provided directly by Starlette.

It contains a group of named constants (variables) with integer status codes.

For example:

* 200: `status.HTTP_200_OK`
* 403: `status.HTTP_403_FORBIDDEN`
* etc.

It 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.

Read more about it in the [FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).


# Doc: docs/en/docs/reference/status.md | Page: Status Codes | Section: Example
## Example

```python
from fastapi import FastAPI, status

app = FastAPI()

@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT)
def read_items():
    return [{"name": "Plumbus"}, {"name": "Portal Gun"}]
```

::: fastapi.status


# Doc: docs/en/docs/reference/templating.md | Page: Templating - `Jinja2Templates` | Section: Templating - `Jinja2Templates`
# Templating - `Jinja2Templates`

You can use the `Jinja2Templates` class to render Jinja templates.

Read more about it in the [FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/).

You can import it directly from `fastapi.templating`:

```python
from fastapi.templating import Jinja2Templates
```

::: fastapi.templating.Jinja2Templates


docs/en/docs/reference/testclient.md::Test Client - `TestClient`::L1

# Doc: docs/en/docs/reference/testclient.md | Page: Test Client - `TestClient` | Section: Test Client - `TestClient`
# Test Client - `TestClient`

You can use the `TestClient` class to test FastAPI applications without creating an actual HTTP and socket connection, just communicating directly with the FastAPI code.

Read more about it in the [FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/).

You can import it directly from `fastapi.testclient`:

```python
from fastapi.testclient import TestClient
```

::: fastapi.testclient.TestClient


# Doc: docs/en/docs/reference/uploadfile.md | Page: `UploadFile` class | Section: `UploadFile` class
# `UploadFile` class

You can define *path operation function* parameters to be of the type `UploadFile` to receive files from the request.

You can import it directly from `fastapi`:

```python
from fastapi import UploadFile
```

::: fastapi.UploadFile
    options:
        members:
            - file
            - filename
            - size
            - headers
            - content_type
            - read
            - write
            - seek
            - close


# Doc: docs/en/docs/reference/websockets.md | Page: WebSockets | Section: WebSockets
# WebSockets

When 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.

Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/)

It is provided directly by Starlette, but you can import it from `fastapi`:

```python
from fastapi import WebSocket
```

/// tip

When 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`.

///

::: fastapi.WebSocket
    options:
        members:
            - scope
            - app
            - url
            - base_url
            - headers
            - query_params
            - path_params
            - cookies
            - client
            - state
            - url_for
            - client_state
            - application_state
            - receive
            - send
            - accept
            - receive_text
            - receive_bytes
            - receive_json
            - iter_text
            - iter_bytes
            - iter_json
            - send_text
            - send_bytes
            - send_json
            - close


docs/en/docs/reference/websockets.md::WebSockets - additional classes::L49

# Doc: docs/en/docs/reference/websockets.md | Page: WebSockets | Section: WebSockets - additional classes
## WebSockets - additional classes

Additional classes for handling WebSockets.

Provided directly by Starlette, but you can import them from `fastapi`:

```python
from fastapi.websockets import WebSocketDisconnect, WebSocketState
```

::: fastapi.websockets.WebSocketDisconnect

When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch it.

You can import it directly from `fastapi`:

```python
from fastapi import WebSocketDisconnect
```

Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/#handling-disconnections-and-multiple-clients)

::: fastapi.websockets.WebSocketState

`WebSocketState` is an enumeration of the possible states of a WebSocket connection.


docs/en/docs/resources/index.md::Resources { #resources }::L1

# Doc: docs/en/docs/resources/index.md | Page: Resources { #resources } | Section: Resources { #resources }
# Resources { #resources }

Additional resources, external links, and more. ✈


# Doc: docs/en/docs/translation-banner.md | Page: docs/en/docs/translation-banner.md | Section: docs/en/docs/translation-banner.md
/// details | 🌐 Translation by AI and humans

This translation was made by AI guided by humans. 🤝

It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖

You can improve this translation by [helping us guide the AI LLM better](https://fastapi.tiangolo.com/contributing/#translations).

[English version](ENGLISH_VERSION_URL)

///


# Doc: docs/en/docs/translations.md | Page: Translations | Section: Translations
# Translations

Translation 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.


docs/en/docs/translations.md::LLM Prompt per Language::L5

# Doc: docs/en/docs/translations.md | Page: Translations | Section: LLM Prompt per Language
## LLM Prompt per Language

Each 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.

For example, for Spanish, the prompt is at: [`docs/es/llm-prompt.md`](https://github.com/fastapi/fastapi/blob/master/docs/es/llm-prompt.md).

If 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.

PRs with suggestions to the language-specific LLM prompt require approval from at least one native speaker. Your help here is very much appreciated!


docs/en/docs/translations.md::Request a New Language::L15

# Doc: docs/en/docs/translations.md | Page: Translations | Section: Request a New Language
## Request a New Language

Let's say that you want to request translations for a language that is not yet translated, not even some pages. For example, Latin.

* 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.
* Once there are at least 3 people that would be willing to commit to help maintain that language, you can continue the next steps.
* Create a new discussion following the template.
* Tag the other 2 people that will help with the language, and ask them to confirm in the comments that they will help.

Once there are several people in the discussion, the FastAPI team can evaluate it and can make it an official translation.

Then the docs will be automatically translated using LLMs, and the team of native speakers can review the translation, and help tweak the LLM prompts.

Once 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.


docs/en/docs/tutorial/background-tasks.md::Background Tasks { #background-tasks }::L1

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Background Tasks { #background-tasks }
# Background Tasks { #background-tasks }

You can define background tasks to be run *after* returning a response.

This 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.

This includes, for example:

* Email notifications sent after performing an action:
    * 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.
* Processing data:
    * 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.


docs/en/docs/tutorial/background-tasks.md::Using `BackgroundTasks` { #using-backgroundtasks }::L14

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Using `BackgroundTasks` { #using-backgroundtasks }
## Using `BackgroundTasks` { #using-backgroundtasks }

First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:

{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}

**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.


docs/en/docs/tutorial/background-tasks.md::Create a task function { #create-a-task-function }::L22

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Create a task function { #create-a-task-function }
## Create a task function { #create-a-task-function }

Create a function to be run as the background task.

It is just a standard function that can receive parameters.

It can be an `async def` or normal `def` function, **FastAPI** will know how to handle it correctly.

In this case, the task function will write to a file (simulating sending an email).

And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:

{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}


docs/en/docs/tutorial/background-tasks.md::Add the background task { #add-the-background-task }::L36

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Add the background task { #add-the-background-task }
## Add the background task { #add-the-background-task }

Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:

{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}

`.add_task()` receives as arguments:

* A task function to be run in the background (`write_notification`).
* Any sequence of arguments that should be passed to the task function in order (`email`).
* Any keyword arguments that should be passed to the task function (`message="some notification"`).


docs/en/docs/tutorial/background-tasks.md::Dependency Injection { #dependency-injection }::L48

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Dependency Injection { #dependency-injection }
## Dependency Injection { #dependency-injection }

Using `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.

**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:

{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}

In this example, the messages will be written to the `log.txt` file *after* the response is sent.

If there was a query in the request, it will be written to the log in a background task.

And then another background task generated at the *path operation function* will write a message using the `email` path parameter.


docs/en/docs/tutorial/background-tasks.md::Technical Details { #technical-details }::L64

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Technical Details { #technical-details }
## Technical Details { #technical-details }

The class `BackgroundTasks` comes directly from [`starlette.background`](https://www.starlette.dev/background/).

It 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`.

By 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.

It'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.

You can see more details in [Starlette's official docs for Background Tasks](https://www.starlette.dev/background/).


docs/en/docs/tutorial/background-tasks.md::Caveat { #caveat }::L76

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Caveat { #caveat }
## Caveat { #caveat }

If 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).

They 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.

But 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`.


docs/en/docs/tutorial/background-tasks.md::Recap { #recap }::L84

# Doc: docs/en/docs/tutorial/background-tasks.md | Page: Background Tasks { #background-tasks } | Section: Recap { #recap }
## Recap { #recap }

Import and use `BackgroundTasks` with parameters in *path operation functions* and dependencies to add background tasks.


docs/en/docs/tutorial/bigger-applications.md::Bigger Applications - Multiple Files { #bigger-applications-multiple-files }::L1

# 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 }
# Bigger Applications - Multiple Files { #bigger-applications-multiple-files }

If you are building an application or a web API, it's rarely the case that you can put everything in a single file.

**FastAPI** provides a convenience tool to structure your application while keeping all the flexibility.

/// note

If you come from Flask, this would be the equivalent of Flask's Blueprints.

///


docs/en/docs/tutorial/bigger-applications.md::An example file structure { #an-example-file-structure }::L13

# 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 }
## An example file structure { #an-example-file-structure }

Let's say you have a file structure like this:

```
.
├── app
│   ├── __init__.py
│   ├── main.py
│   ├── dependencies.py
│   └── routers
│   │   ├── __init__.py
│   │   ├── items.py
│   │   └── users.py
│   └── internal
│       ├── __init__.py
│       └── admin.py
```

/// tip

There are several `__init__.py` files: one in each directory or subdirectory.

This is what allows importing code from one file into another.

For example, in `app/main.py` you could have a line like:

```
from app.routers import items
```

///

* 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`.
* 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`.
* There's also an `app/dependencies.py` file, just like `app/main.py`, it is a "module": `app.dependencies`.
* There's a subdirectory `app/routers/` with another file `__init__.py`, so it's a "Python subpackage": `app.routers`.
* The file `app/routers/items.py` is inside a package, `app/routers/`, so, it's a submodule: `app.routers.items`.
* The same with `app/routers/users.py`, it's another submodule: `app.routers.users`.
* There's also a subdirectory `app/internal/` with another file `__init__.py`, so it's another "Python subpackage": `app.internal`.
* And the file `app/internal/admin.py` is another submodule: `app.internal.admin`.

<img src="/img/tutorial/bigger-applications/package.drawio.svg">

The same file structure with comments:

```bash
.
├── app                  # "app" is a Python package
│   ├── __init__.py      # this file makes "app" a "Python package"
│   ├── main.py          # "main" module, e.g. import app.main
│   ├── dependencies.py  # "dependencies" module, e.g. import app.dependencies
│   └── routers          # "routers" is a "Python subpackage"
│   │   ├── __init__.py  # makes "routers" a "Python subpackage"
│   │   ├── items.py     # "items" submodule, e.g. import app.routers.items
│   │   └── users.py     # "users" submodule, e.g. import app.routers.users
│   └── internal         # "internal" is a "Python subpackage"
│       ├── __init__.py  # makes "internal" a "Python subpackage"
│       └── admin.py     # "admin" submodule, e.g. import app.internal.admin
```


docs/en/docs/tutorial/bigger-applications.md::`APIRouter` { #apirouter }::L74

# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: `APIRouter` { #apirouter }
## `APIRouter` { #apirouter }

Let's say the file dedicated to handling just users is the submodule at `/app/routers/users.py`.

You want to have the *path operations* related to your users separated from the rest of the code, to keep it organized.

But it's still part of the same **FastAPI** application/web API (it's part of the same "Python Package").

You can create the *path operations* for that module using `APIRouter`.

### Import `APIRouter` { #import-apirouter }

You import it and create an "instance" the same way you would with the class `FastAPI`:

{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *}

### *Path operations* with `APIRouter` { #path-operations-with-apirouter }

And then you use it to declare your *path operations*.

Use it the same way you would use the `FastAPI` class:

{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *}

You can think of `APIRouter` as a "mini `FastAPI`" class.

All the same options are supported.

All the same `parameters`, `responses`, `dependencies`, `tags`, etc.

/// tip

In this example, the variable is called `router`, but you can name it however you want.

///

We are going to include this `APIRouter` in the main `FastAPI` app, but first, let's check the dependencies and another `APIRouter`.


docs/en/docs/tutorial/bigger-applications.md::Dependencies { #dependencies }::L112

# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: Dependencies { #dependencies }
## Dependencies { #dependencies }

We see that we are going to need some dependencies used in several places of the application.

So we put them in their own `dependencies` module (`app/dependencies.py`).

We will now use a simple dependency to read a custom `X-Token` header:

{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *}

/// tip

We are using an invented header to simplify this example.

But in real cases you will get better results using the integrated [Security utilities](security/index.md).

///


docs/en/docs/tutorial/bigger-applications.md::Another module with `APIRouter` { #another-module-with-apirouter }::L130

# 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 }
## Another module with `APIRouter` { #another-module-with-apirouter }

Let's say you also have the endpoints dedicated to handling "items" from your application in the module at `app/routers/items.py`.

You have *path operations* for:

* `/items/`
* `/items/{item_id}`

It's all the same structure as with `app/routers/users.py`.

But we want to be smarter and simplify the code a bit.

We know all the *path operations* in this module have the same:

* Path `prefix`: `/items`.
* `tags`: (just one tag: `items`).
* Extra `responses`.
* `dependencies`: they all need that `X-Token` dependency we created.

So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`.

{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *}

As the path of each *path operation* has to start with `/`, like in:

```Python hl_lines="1"
@router.get("/{item_id}")
async def read_item(item_id: str):
    ...
```

...the prefix must not include a final `/`.

So, the prefix in this case is `/items`.

We can also add a list of `tags` and extra `responses` that will be applied to all the *path operations* included in this router.

And 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.

/// tip

Note 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*.

///

The end result is that the item paths are now:

* `/items/`
* `/items/{item_id}`

...as we intended.

* They will be marked with a list of tags that contain a single string `"items"`.
    * These "tags" are especially useful for the automatic interactive documentation systems (using OpenAPI).
* All of them will include the predefined `responses`.
* All these *path operations* will have the list of `dependencies` evaluated/executed before them.
    * If you also declare dependencies in a specific *path operation*, **they will be executed too**.
    * 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.
    * You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md).

/// tip

Having `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.

///

/// tip

The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.

///

### Import the dependencies { #import-the-dependencies }

This code lives in the module `app.routers.items`, the file `app/routers/items.py`.

And we need to get the dependency function from the module `app.dependencies`, the file `app/dependencies.py`.

So we use a relative import with `..` for the dependencies:

{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *}

#### How relative imports work { #how-relative-imports-work }

/// tip

If you know perfectly how imports work, continue to the next section below.

///

A single dot `.`, like in:

```Python
from .dependencies import get_token_header
```

would mean:

* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...
* find the module `dependencies` (an imaginary file at `app/routers/dependencies.py`)...
* and from it, import the function `get_token_header`.

But that file doesn't exist, our dependencies are in a file at `app/dependencies.py`.

Remember what our app/file structure looks like:

<img src="/img/tutorial/bigger-applications/package.drawio.svg">

---

The two dots `..`, like in:

```Python
from ..dependencies import get_token_header
```

mean:

* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...
* go to the parent package (the directory `app/`)...
* and in there, find the module `dependencies` (the file at `app/dependencies.py`)...
* and from it, import the function `get_token_header`.

That works correctly! 🎉

---

The same way, if we had used three dots `...`, like in:

```Python
from ...dependencies import get_token_header
```

that would mean:

* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...
* go to the parent package (the directory `app/`)...
* then go to the parent of that package (there's no parent package, `app` is the top level 😱)...
* and in there, find the module `dependencies` (the file at `app/dependencies.py`)...
* and from it, import the function `get_token_header`.

That 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. 🚨

But now you know how it works, so you can use relative imports in your own apps no matter how complex they are. 🤓

### Add some custom `tags`, `responses`, and `dependencies` { #add-some-custom-tags-responses-and-dependencies }

We are not adding the prefix `/items` nor the `tags=["items"]` to each *path operation* because we added them to the `APIRouter`.

But 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*:

{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *}

/// tip

This last path operation will have the combination of tags: `["items", "custom"]`.

And it will also have both responses in the documentation, one for `404` and one for `403`.

///


docs/en/docs/tutorial/bigger-applications.md::The main `FastAPI` { #the-main-fastapi }::L292

# Doc: docs/en/docs/tutorial/bigger-applications.md | Page: Bigger Applications - Multiple Files { #bigger-applications-multiple-files } | Section: The main `FastAPI` { #the-main-fastapi }
## The main `FastAPI` { #the-main-fastapi }

Now, let's see the module at `app/main.py`.

Here's where you import and use the class `FastAPI`.

This will be the main file in your application that ties everything together.

And as most of your logic will now live in its own specific module, the main file will be quite simple.

### Import `FastAPI` { #import-fastapi }

You import and create a `FastAPI` class as normally.

And we can even declare [global dependencies](dependencies/global-dependencies.md) that will be combined with the dependencies for each `APIRouter`:

{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *}

### Import the `APIRouter` { #import-the-apirouter }

Now we import the other submodules that have `APIRouter`s:

{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *}

As 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".

### How the importing works { #how-the-importing-works }

The section:

```Python
from .routers import items, users
```

means:

* Starting in the same package that this module (the file `app/main.py`) lives in (the directory `app/`)...
* look for the subpackage `routers` (the directory at `app/routers/`)...
* and from it, import the submodule `items` (the file at `app/routers/items.py`) and `users` (the file at `app/routers/users.py`)...

The 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.

And then we do the same for the module `users`.

We could also import them like:

```Python
from app.routers import items, users
```

/// note

The first version is a "relative import":

```Python
from .routers import items, users
```

The second version is an "absolute import":

```Python
from app.routers import items, users
```

To learn more about Python Packages and Modules, read [the official Python documentation about Modules](https://docs.python.org/3/tutorial/modules.html).

///

### Avoid name collisions { #avoid-name-collisions }

We are importing the submodule `items` directly, instead of importing just its variable `router`.

This is because we also have another variable named `router` in the submodule `users`.

If we had imported one after the other, like:

```Python
from .routers.items import router
from .routers.users import router
```

the `router` from `users` would overwrite the one from `items` and we wouldn't be able to use them at the same time.

So, to be able to use both of them in the same file, we import the submodules directly:

{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *}

### Include the `APIRouter`s for `users` and `items` { #include-the-apirouters-for-users-and-items }

Now, let's include the `router`s from the submodules `users` and `items`:

{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *}

/// note

`users.router` contains the `APIRouter` inside of the file `app/routers/users.py`.

And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`.

///

With `app.include_router()` we can add each `APIRouter` to the main `FastAPI` application.

It will include all the routes from that router as part of it.

/// note | Technical Details

FastAPI keeps the original `APIRouter` and its `APIRoute`s active when the router is included in the main application.

That means custom `APIRouter` and `APIRoute` subclasses can still participate after the router is included.

///

/// tip

You don't have to worry about performance when including routers.

This is designed to be lightweight and to avoid adding overhead to each request.

So it won't affect performance. ⚡

///

### Include an `APIRouter` with a custom `prefix`, `tags`, `responses`, and `dependencies` { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }

Now, let's imagine your organization gave you the `app/internal/admin.py` file.

It contains an `APIRouter` with some admin *path operations* that your organization shares between several projects.

For 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`:

{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *}

But 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`.

We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`:

{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *}

That 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.

The result is that in our app, each of the *path operations* from the `admin` module will have:

* The prefix `/admin`.
* The tag `admin`.
* The dependency `get_token_header`.
* The response `418`. 🍵

But that will only affect that `APIRouter` in our app, not in any other code that uses it.

So, for example, other projects could use the same `APIRouter` with a different authentication method.

### Include a *path operation* { #include-a-path-operation }

We can also add *path operations* directly to the `FastAPI` app.

Here we do it... just to show that we can 🤷:

{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *}

and it will work correctly, together with all the other *path operations* added with `app.include_router()`.

/// note | Very Technical Details

**Note**: this is a very technical detail that you probably can **just skip**.

---

The `APIRouter`s are not "mounted", they are not isolated from the rest of the application.

This is because we want to include their *path operations* in the OpenAPI schema and the user interfaces.

FastAPI 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.

///


docs/en/docs/tutorial/bigger-applications.md::Configure the `entrypoint` in `pyproject.toml` { #configure-the-entrypoint-in-pyproject-toml }::L468

# 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 }
## Configure the `entrypoint` in `pyproject.toml` { #configure-the-entrypoint-in-pyproject-toml }

As your FastAPI `app` object lives in `app/main.py`, you can configure the `entrypoint` in your `pyproject.toml` file like this:

```toml
[tool.fastapi]
entrypoint = "app.main:app"
```

that is equivalent to importing like:

```python
from app.main import app
```

That way the `fastapi` command will know where to find your app.

/// Note

You could also pass the path to the command, like:

```console
$ fastapi dev app/main.py
```

But you would have to remember to pass the correct path every time you call the `fastapi` command.

Additionally, 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`.

///


docs/en/docs/tutorial/bigger-applications.md::Check the automatic API docs { #check-the-automatic-api-docs }::L499

# 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 }
## Check the automatic API docs { #check-the-automatic-api-docs }

Now, run your app:

```console
$ fastapi dev

<span style="color: green;">INFO</span>:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

And open the docs at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).

You will see the automatic API docs, including the paths from all the submodules, using the correct paths (and prefixes) and the correct tags:


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

# 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 }
## Include the same router multiple times with different `prefix` { #include-the-same-router-multiple-times-with-different-prefix }

You can also use `.include_router()` multiple times with the *same* router using different prefixes.

This could be useful, for example, to expose the same API under different prefixes, e.g. `/api/v1` and `/api/latest`.

This is an advanced usage that you might not really need, but it's there in case you do.


docs/en/docs/tutorial/bigger-applications.md::Include an `APIRouter` in another { #include-an-apirouter-in-another }::L527

# 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 }
## Include an `APIRouter` in another { #include-an-apirouter-in-another }

The same way you can include an `APIRouter` in a `FastAPI` application, you can include an `APIRouter` in another `APIRouter` using:

```Python
router.include_router(other_router)
```

You 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.

The same applies to *path operations* added later to the routers. They will be visible through the earlier inclusion too.

/// warning | Technical Details

Avoid 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.

Use documented APIs such as path operation decorators and `.include_router()` to add routes and routers.

Treat `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.

///


docs/en/docs/tutorial/body-fields.md::Body - Fields { #body-fields }::L1

# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Body - Fields { #body-fields }
# Body - Fields { #body-fields }

The 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`.


docs/en/docs/tutorial/body-fields.md::Import `Field` { #import-field }::L5

# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Import `Field` { #import-field }
## Import `Field` { #import-field }

First, you have to import it:

{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}

/// warning

Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).

///


docs/en/docs/tutorial/body-fields.md::Declare model attributes { #declare-model-attributes }::L18

# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Declare model attributes { #declare-model-attributes }
## Declare model attributes { #declare-model-attributes }

You can then use `Field` with model attributes:

{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}

`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.

/// note | Technical Details

Actually, `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.

And Pydantic's `Field` returns an instance of `FieldInfo` as well.

`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.

Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes.

///

/// tip

Notice 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`.

///


docs/en/docs/tutorial/body-fields.md::Add extra information { #add-extra-information }::L44

# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Add extra information { #add-extra-information }
## Add extra information { #add-extra-information }

You can declare extra information in `Field`, `Query`, `Body`, etc. And it will be included in the generated JSON Schema.

You will learn more about adding extra information later in the docs, when learning to declare examples.

/// warning

Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.
As 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.

///


docs/en/docs/tutorial/body-fields.md::Recap { #recap }::L57

# Doc: docs/en/docs/tutorial/body-fields.md | Page: Body - Fields { #body-fields } | Section: Recap { #recap }
## Recap { #recap }

You can use Pydantic's `Field` to declare extra validations and metadata for model attributes.

You can also use the extra keyword arguments to pass additional JSON Schema metadata.