docs/en/docs/tutorial/body-multiple-params.md::Body - Multiple Parameters { #body-multiple-parameters }::L1

# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Body - Multiple Parameters { #body-multiple-parameters }
# Body - Multiple Parameters { #body-multiple-parameters }

Now that we have seen how to use `Path` and `Query`, let's see more advanced uses of request body declarations.


docs/en/docs/tutorial/body-multiple-params.md::Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }::L5

# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }
## Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }

First, of course, you can mix `Path`, `Query` and request body parameter declarations freely and **FastAPI** will know what to do.

And you can also declare body parameters as optional, by setting the default to `None`:

{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}

/// note

Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.

///


docs/en/docs/tutorial/body-multiple-params.md::Multiple body parameters { #multiple-body-parameters }::L19

# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Multiple body parameters { #multiple-body-parameters }
## Multiple body parameters { #multiple-body-parameters }

In the previous example, the *path operations* would expect a JSON body with the attributes of an `Item`, like:

```JSON
{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2
}
```

But you can also declare multiple body parameters, e.g. `item` and `user`:

{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}

In this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models).

So, it will then use the parameter names as keys (field names) in the body, and expect a body like:

```JSON
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    }
}
```

/// note

Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`.

///

**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`.

It will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs.


docs/en/docs/tutorial/body-multiple-params.md::Singular values in body { #singular-values-in-body }::L66

# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Singular values in body { #singular-values-in-body }
## Singular values in body { #singular-values-in-body }

The same way there is a `Query` and `Path` to define extra data for query and path parameters, **FastAPI** provides an equivalent `Body`.

For example, extending the previous model, you could decide that you want to have another key `importance` in the same body, besides the `item` and `user`.

If you declare it as is, because it is a singular value, **FastAPI** will assume that it is a query parameter.

But you can instruct **FastAPI** to treat it as another body key using `Body`:

{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}

In this case, **FastAPI** will expect a body like:

```JSON
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    },
    "importance": 5
}
```

Again, it will convert the data types, validate, document, etc.


docs/en/docs/tutorial/body-multiple-params.md::Multiple body params and query { #multiple-body-params-and-query }::L99

# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Multiple body params and query { #multiple-body-params-and-query }
## Multiple body params and query { #multiple-body-params-and-query }

Of course, you can also declare additional query parameters whenever you need, additional to any body parameters.

As, by default, singular values are interpreted as query parameters, you don't have to explicitly add a `Query`, you can just do:

```Python
q: str | None = None
```

For example:

{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}

/// note

`Body` also has all the same extra validation and metadata parameters as `Query`, `Path` and others you will see later.

///


docs/en/docs/tutorial/body-multiple-params.md::Embed a single body parameter { #embed-a-single-body-parameter }::L120

# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Embed a single body parameter { #embed-a-single-body-parameter }
## Embed a single body parameter { #embed-a-single-body-parameter }

Let's say you only have a single `item` body parameter from a Pydantic model `Item`.

By default, **FastAPI** will then expect its body directly.

But if you want it to expect a JSON with a key `item` and inside of it the model contents, as it does when you declare extra body parameters, you can use the special `Body` parameter `embed`:

```Python
item: Annotated[Item, Body(embed=True)]
```

as in:

{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}

In this case **FastAPI** will expect a body like:

```JSON hl_lines="2"
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    }
}
```

instead of:

```JSON
{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2
}
```


docs/en/docs/tutorial/body-multiple-params.md::Recap { #recap }::L161

# Doc: docs/en/docs/tutorial/body-multiple-params.md | Page: Body - Multiple Parameters { #body-multiple-parameters } | Section: Recap { #recap }
## Recap { #recap }

You can add multiple body parameters to your *path operation function*, even though a request can only have a single body.

But **FastAPI** will handle it, give you the correct data in your function, and validate and document the correct schema in the *path operation*.

You can also declare singular values to be received as part of the body.

And you can instruct **FastAPI** to embed the body in a key even when there is only a single parameter declared.


docs/en/docs/tutorial/body-nested-models.md::Body - Nested Models { #body-nested-models }::L1

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Body - Nested Models { #body-nested-models }
# Body - Nested Models { #body-nested-models }

With **FastAPI**, you can define, validate, document, and use arbitrarily deeply nested models (thanks to Pydantic).


docs/en/docs/tutorial/body-nested-models.md::List fields { #list-fields }::L5

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: List fields { #list-fields }
## List fields { #list-fields }

You can define an attribute to be a subtype. For example, a Python `list`:

{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}

This will make `tags` be a list, although it doesn't declare the type of the elements of the list.


docs/en/docs/tutorial/body-nested-models.md::List fields with type parameter { #list-fields-with-type-parameter }::L13

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: List fields with type parameter { #list-fields-with-type-parameter }
## List fields with type parameter { #list-fields-with-type-parameter }

But Python has a specific way to declare lists with internal types, or "type parameters":

### Declare a `list` with a type parameter { #declare-a-list-with-a-type-parameter }

To declare types that have type parameters (internal types), like `list`, `dict`, `tuple`,
pass the internal type(s) as "type parameters" using square brackets: `[` and `]`

```Python
my_list: list[str]
```

That's all standard Python syntax for type declarations.

Use that same standard syntax for model attributes with internal types.

So, in our example, we can make `tags` be specifically a "list of strings":

{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}


docs/en/docs/tutorial/body-nested-models.md::Set types { #set-types }::L34

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Set types { #set-types }
## Set types { #set-types }

But then we think about it, and realize that tags shouldn't repeat, they would probably be unique strings.

And Python has a special data type for sets of unique items, the `set`.

Then we can declare `tags` as a set of strings:

{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}

With this, even if you receive a request with duplicate data, it will be converted to a set of unique items.

And whenever you output that data, even if the source had duplicates, it will be output as a set of unique items.

And it will be annotated / documented accordingly too.


docs/en/docs/tutorial/body-nested-models.md::Nested Models { #nested-models }::L50

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Nested Models { #nested-models }
## Nested Models { #nested-models }

Each attribute of a Pydantic model has a type.

But that type can itself be another Pydantic model.

So, you can declare deeply nested JSON "objects" with specific attribute names, types and validations.

All that, arbitrarily nested.

### Define a submodel { #define-a-submodel }

For example, we can define an `Image` model:

{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}

### Use the submodel as a type { #use-the-submodel-as-a-type }

And then we can use it as the type of an attribute:

{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}

This would mean that **FastAPI** would expect a body similar to:

```JSON
{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2,
    "tags": ["rock", "metal", "bar"],
    "image": {
        "url": "http://example.com/baz.jpg",
        "name": "The Foo live"
    }
}
```

Again, doing just that declaration, with **FastAPI** you get:

* Editor support (completion, etc.), even for nested models
* Data conversion
* Data validation
* Automatic documentation


docs/en/docs/tutorial/body-nested-models.md::Special types and validation { #special-types-and-validation }::L95

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Special types and validation { #special-types-and-validation }
## Special types and validation { #special-types-and-validation }

Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`.

To see all the options you have, check out [Pydantic's Type Overview](https://docs.pydantic.dev/latest/concepts/types/). You will see some examples in the next chapter.

For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`:

{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}

The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such.


docs/en/docs/tutorial/body-nested-models.md::Attributes with lists of submodels { #attributes-with-lists-of-submodels }::L107

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Attributes with lists of submodels { #attributes-with-lists-of-submodels }
## Attributes with lists of submodels { #attributes-with-lists-of-submodels }

You can also use Pydantic models as subtypes of `list`, `set`, etc.:

{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}

This will expect (convert, validate, document, etc.) a JSON body like:

```JSON hl_lines="11"
{
    "name": "Foo",
    "description": "The pretender",
    "price": 42.0,
    "tax": 3.2,
    "tags": [
        "rock",
        "metal",
        "bar"
    ],
    "images": [
        {
            "url": "http://example.com/baz.jpg",
            "name": "The Foo live"
        },
        {
            "url": "http://example.com/dave.jpg",
            "name": "The Baz"
        }
    ]
}
```

/// note

Notice how the `images` key now has a list of image objects.

///


docs/en/docs/tutorial/body-nested-models.md::Deeply nested models { #deeply-nested-models }::L145

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Deeply nested models { #deeply-nested-models }
## Deeply nested models { #deeply-nested-models }

You can define arbitrarily deeply nested models:

{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}

/// note

Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s

///


docs/en/docs/tutorial/body-nested-models.md::Bodies of pure lists { #bodies-of-pure-lists }::L157

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Bodies of pure lists { #bodies-of-pure-lists }
## Bodies of pure lists { #bodies-of-pure-lists }

If the top level value of the JSON body you expect is a JSON `array` (a Python `list`), you can declare the type in the parameter of the function, the same as in Pydantic models:

```Python
images: list[Image]
```

as in:

{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}


docs/en/docs/tutorial/body-nested-models.md::Editor support everywhere { #editor-support-everywhere }::L169

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Editor support everywhere { #editor-support-everywhere }
## Editor support everywhere { #editor-support-everywhere }

And you get editor support everywhere.

Even for items inside of lists:

<img src="/img/tutorial/body-nested-models/image01.png">

You couldn't get this kind of editor support if you were working directly with `dict` instead of Pydantic models.

But you don't have to worry about them either, incoming dicts are converted automatically and your output is converted automatically to JSON too.


docs/en/docs/tutorial/body-nested-models.md::Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }::L181

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }
## Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }

You can also declare a body as a `dict` with keys of some type and values of some other type.

This way, you don't have to know beforehand what the valid field/attribute names are (as would be the case with Pydantic models).

This would be useful if you want to receive keys that you don't already know.

---

Another useful case is when you want to have keys of another type (e.g., `int`).

That's what we are going to see here.

In this case, you would accept any `dict` as long as it has `int` keys with `float` values:

{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}

/// tip

Keep in mind that JSON only supports `str` as keys.

But Pydantic has automatic data conversion.

This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.

And the `dict` you receive as `weights` will actually have `int` keys and `float` values.

///


docs/en/docs/tutorial/body-nested-models.md::Recap { #recap }::L211

# Doc: docs/en/docs/tutorial/body-nested-models.md | Page: Body - Nested Models { #body-nested-models } | Section: Recap { #recap }
## Recap { #recap }

With **FastAPI** you have the maximum flexibility provided by Pydantic models, while keeping your code simple, short and elegant.

But with all the benefits:

* Editor support (completion everywhere!)
* Data conversion (a.k.a. parsing / serialization)
* Data validation
* Schema documentation
* Automatic docs


docs/en/docs/tutorial/body-updates.md::Update replacing with `PUT` { #update-replacing-with-put }::L3

# Doc: docs/en/docs/tutorial/body-updates.md | Page: Body - Updates { #body-updates } | Section: Update replacing with `PUT` { #update-replacing-with-put }
## Update replacing with `PUT` { #update-replacing-with-put }

To update an item you can use the [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) operation.

You can use the `jsonable_encoder` to convert the input data to data that can be stored as JSON (e.g. with a NoSQL database). For example, converting `datetime` to `str`.

{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}

`PUT` is used to receive data that should replace the existing data.

### Warning about replacing { #warning-about-replacing }

That means that if you want to update the item `bar` using `PUT` with a body containing:

```Python
{
    "name": "Barz",
    "price": 3,
    "description": None,
}
```

because it doesn't include the already stored attribute `"tax": 20.2`, the input model would take the default value of `"tax": 10.5`.

And the data would be saved with that "new" `tax` of `10.5`.


docs/en/docs/tutorial/body-updates.md::Partial updates with `PATCH` { #partial-updates-with-patch }::L29

# Doc: docs/en/docs/tutorial/body-updates.md | Page: Body - Updates { #body-updates } | Section: Partial updates with `PATCH` { #partial-updates-with-patch }
## Partial updates with `PATCH` { #partial-updates-with-patch }

You can also use the [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) operation to *partially* update data.

This means that you can send only the data that you want to update, leaving the rest intact.

/// note

`PATCH` is less commonly used and known than `PUT`.

And many teams use only `PUT`, even for partial updates.

You are **free** to use them however you want, **FastAPI** doesn't impose any restrictions.

But this guide shows you, more or less, how they are intended to be used.

///

### Using Pydantic's `exclude_unset` parameter { #using-pydantics-exclude-unset-parameter }

If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.model_dump()`.

Like `item.model_dump(exclude_unset=True)`.

That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values.

Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:

{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}

### Using Pydantic's `update` parameter { #using-pydantics-update-parameter }

Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update.

Like `stored_item_model.model_copy(update=update_data)`:

{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}

### Partial updates recap { #partial-updates-recap }

In summary, to apply partial updates you would:

* (Optionally) use `PATCH` instead of `PUT`.
* Retrieve the stored data.
* Put that data in a Pydantic model.
* Generate a `dict` without default values from the input model (using `exclude_unset`).
    * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model.
* Create a copy of the stored model, updating its attributes with the received partial updates (using the `update` parameter).
* Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`).
    * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`.
* Save the data to your DB.
* Return the updated model.

{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}

/// tip

You can actually use this same technique with an HTTP `PUT` operation.

But the example here uses `PATCH` because it was created for these use cases.

///

/// note

Notice that the input model is still validated.

So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`).

To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md).

///


docs/en/docs/tutorial/body.md::Request Body { #request-body }::L1

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

When you need to send data from a client (let's say, a browser) to your API, you send it as a **request body**.

A **request** body is data sent by the client to your API. A **response** body is the data your API sends to the client.

Your API almost always has to send a **response** body. But clients don't necessarily need to send **request bodies** all the time, sometimes they only request a path, maybe with some query parameters, but don't send a body.

To declare a **request** body, you use [Pydantic](https://docs.pydantic.dev/) models with all their power and benefits.

/// note

To send data, you should use one of: `POST` (the most common), `PUT`, `DELETE` or `PATCH`.

Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases.

As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it.

///


docs/en/docs/tutorial/body.md::Import Pydantic's `BaseModel` { #import-pydantics-basemodel }::L21

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Import Pydantic's `BaseModel` { #import-pydantics-basemodel }
## Import Pydantic's `BaseModel` { #import-pydantics-basemodel }

First, you need to import `BaseModel` from `pydantic`:

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


docs/en/docs/tutorial/body.md::Create your data model { #create-your-data-model }::L27

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Create your data model { #create-your-data-model }
## Create your data model { #create-your-data-model }

Then you declare your data model as a class that inherits from `BaseModel`.

Use standard Python types for all the attributes:

{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}

The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use `None` to make it just optional.

For example, this model above declares a JSON "`object`" (or Python `dict`) like:

```JSON
{
    "name": "Foo",
    "description": "An optional description",
    "price": 45.2,
    "tax": 3.5
}
```

...as `description` and `tax` are optional (with a default value of `None`), this JSON "`object`" would also be valid:

```JSON
{
    "name": "Foo",
    "price": 45.2
}
```


docs/en/docs/tutorial/body.md::Declare it as a parameter { #declare-it-as-a-parameter }::L58

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Declare it as a parameter { #declare-it-as-a-parameter }
## Declare it as a parameter { #declare-it-as-a-parameter }

To add it to your *path operation*, declare it the same way you declared path and query parameters:

{* ../../docs_src/body/tutorial001_py310.py hl[16] *}

...and declare its type as the model you created, `Item`.


docs/en/docs/tutorial/body.md::Results { #results }::L66

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Results { #results }
## Results { #results }

With just that Python type declaration, **FastAPI** will:

* Read the body of the request as JSON.
* Convert the corresponding types (if needed).
* Validate the data.
    * If the data is invalid, it will return a nice and clear error, indicating exactly where and what was the incorrect data.
* Give you the received data in the parameter `item`.
    * As you declared it in the function to be of type `Item`, you will also have all the editor support (completion, etc) for all of the attributes and their types.
* Generate [JSON Schema](https://json-schema.org) definitions for your model, you can also use them anywhere else you like if it makes sense for your project.
* Those schemas will be part of the generated OpenAPI schema, and used by the automatic documentation <abbr title="User Interfaces">UIs</abbr>.


docs/en/docs/tutorial/body.md::Automatic docs { #automatic-docs }::L79

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Automatic docs { #automatic-docs }
## Automatic docs { #automatic-docs }

The JSON Schemas of your models will be part of your OpenAPI generated schema, and will be shown in the interactive API docs:

And will also be used in the API docs inside each *path operation* that needs them:


docs/en/docs/tutorial/body.md::Editor support { #editor-support }::L89

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Editor support { #editor-support }
## Editor support { #editor-support }

In your editor, inside your function you will get type hints and completion everywhere (this wouldn't happen if you received a `dict` instead of a Pydantic model):

You also get error checks for incorrect type operations:

This is not by chance, the whole framework was built around that design.

And it was thoroughly tested at the design phase, before any implementation, to ensure it would work with all the editors.

There were even some changes to Pydantic itself to support this.

The previous screenshots were taken with [Visual Studio Code](https://code.visualstudio.com).

But you would get the same editor support with [PyCharm](https://www.jetbrains.com/pycharm/) and most of the other Python editors:

/// tip

If you use [PyCharm](https://www.jetbrains.com/pycharm/) as your editor, you can use the [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/).

It improves editor support for Pydantic models, with:

* auto-completion
* type checks
* refactoring
* searching
* inspections

///


docs/en/docs/tutorial/body.md::Use the model { #use-the-model }::L125

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Use the model { #use-the-model }
## Use the model { #use-the-model }

Inside of the function, you can access all the attributes of the model object directly:

{* ../../docs_src/body/tutorial002_py310.py *}


docs/en/docs/tutorial/body.md::Request body + path parameters { #request-body-path-parameters }::L131

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Request body + path parameters { #request-body-path-parameters }
## Request body + path parameters { #request-body-path-parameters }

You can declare path parameters and request body at the same time.

**FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**.

{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}


docs/en/docs/tutorial/body.md::Request body + path + query parameters { #request-body-path-query-parameters }::L140

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Request body + path + query parameters { #request-body-path-query-parameters }
## Request body + path + query parameters { #request-body-path-query-parameters }

You can also declare **body**, **path** and **query** parameters, all at the same time.

**FastAPI** will recognize each of them and take the data from the correct place.

{* ../../docs_src/body/tutorial004_py310.py hl[16] *}

The function parameters will be recognized as follows:

* If the parameter is also declared in the **path**, it will be used as a path parameter.
* If the parameter is of a **singular type** (like `int`, `float`, `str`, `bool`, etc) it will be interpreted as a **query** parameter.
* If the parameter is declared to be of the type of a **Pydantic model**, it will be interpreted as a request **body**.

/// note

FastAPI will know that the value of `q` is not required because of the default value `= None`.

The `str | None` is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`.

But adding the type annotations will allow your editor to give you better support and detect errors.

///


docs/en/docs/tutorial/body.md::Without Pydantic { #without-pydantic }::L164

# Doc: docs/en/docs/tutorial/body.md | Page: Request Body { #request-body } | Section: Without Pydantic { #without-pydantic }
## Without Pydantic { #without-pydantic }

If you don't want to use Pydantic models, you can also use **Body** parameters. See the docs for [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body).


docs/en/docs/tutorial/cookie-param-models.md::Cookie Parameter Models { #cookie-parameter-models }::L1

# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Cookie Parameter Models { #cookie-parameter-models }
# Cookie Parameter Models { #cookie-parameter-models }

If you have a group of **cookies** that are related, you can create a **Pydantic model** to declare them. 🍪

This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎

/// note

This is supported since FastAPI version `0.115.0`. 🤓

///

/// tip

This same technique applies to `Query`, `Cookie`, and `Header`. 😎

///


docs/en/docs/tutorial/cookie-param-models.md::Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }::L19

# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }
## Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }

Declare the **cookie** parameters that you need in a **Pydantic model**, and then declare the parameter as `Cookie`:

{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}

**FastAPI** will **extract** the data for **each field** from the **cookies** received in the request and give you the Pydantic model you defined.


docs/en/docs/tutorial/cookie-param-models.md::Check the Docs { #check-the-docs }::L27

# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Check the Docs { #check-the-docs }
## Check the Docs { #check-the-docs }

You can see the defined cookies in the docs UI at `/docs`:

/// note

Have in mind that, as **browsers handle cookies** in special ways and behind the scenes, they **don't** easily allow **JavaScript** to touch them.

If you go to the **API docs UI** at `/docs` you will be able to see the **documentation** for cookies for your *path operations*.

But even if you **fill the data** and click "Execute", because the docs UI works with **JavaScript**, the cookies won't be sent, and you will see an **error** message as if you didn't write any values.

///


docs/en/docs/tutorial/cookie-param-models.md::Forbid Extra Cookies { #forbid-extra-cookies }::L45

# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Forbid Extra Cookies { #forbid-extra-cookies }
## Forbid Extra Cookies { #forbid-extra-cookies }

In some special use cases (probably not very common), you might want to **restrict** the cookies that you want to receive.

Your API now has the power to control its own <dfn title="This is a joke, just in case. It has nothing to do with cookie consents, but it's funny that even the API can now reject the poor cookies. Have a cookie. 🍪">cookie consent</dfn>. 🤪🍪

You can use Pydantic's model configuration to `forbid` any `extra` fields:

{* ../../docs_src/cookie_param_models/tutorial002_an_py310.py hl[10] *}

If a client tries to send some **extra cookies**, they will receive an **error** response.

Poor cookie banners with all their effort to get your consent for the <dfn title="This is another joke. Don't pay attention to me. Have some coffee for your cookie. ☕">API to reject it</dfn>. 🍪

For example, if the client tries to send a `santa_tracker` cookie with a value of `good-list-please`, the client will receive an **error** response telling them that the `santa_tracker` <dfn title="Santa disapproves the lack of cookies. 🎅 Okay, no more cookie jokes.">cookie is not allowed</dfn>:

```json
{
    "detail": [
        {
            "type": "extra_forbidden",
            "loc": ["cookie", "santa_tracker"],
            "msg": "Extra inputs are not permitted",
            "input": "good-list-please",
        }
    ]
}
```


docs/en/docs/tutorial/cookie-param-models.md::Summary { #summary }::L74

# Doc: docs/en/docs/tutorial/cookie-param-models.md | Page: Cookie Parameter Models { #cookie-parameter-models } | Section: Summary { #summary }
## Summary { #summary }

You can use **Pydantic models** to declare <dfn title="Have a last cookie before you go. 🍪">**cookies**</dfn> in **FastAPI**. 😎


docs/en/docs/tutorial/cookie-params.md::Cookie Parameters { #cookie-parameters }::L1

# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Cookie Parameters { #cookie-parameters }
# Cookie Parameters { #cookie-parameters }

You can define Cookie parameters the same way you define `Query` and `Path` parameters.


docs/en/docs/tutorial/cookie-params.md::Import `Cookie` { #import-cookie }::L5

# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Import `Cookie` { #import-cookie }
## Import `Cookie` { #import-cookie }

First import `Cookie`:

{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *}


docs/en/docs/tutorial/cookie-params.md::Declare `Cookie` parameters { #declare-cookie-parameters }::L11

# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Declare `Cookie` parameters { #declare-cookie-parameters }
## Declare `Cookie` parameters { #declare-cookie-parameters }

Then declare the cookie parameters using the same structure as with `Path` and `Query`.

You can define the default value as well as all the extra validation or annotation parameters:

{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *}

/// note | Technical Details

`Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class.

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

///

/// note

To declare cookies, you need to use `Cookie`, because otherwise the parameters would be interpreted as query parameters.

///

/// note

Have in mind that, as **browsers handle cookies** in special ways and behind the scenes, they **don't** easily allow **JavaScript** to touch them.

If you go to the **API docs UI** at `/docs` you will be able to see the **documentation** for cookies for your *path operations*.

But even if you **fill the data** and click "Execute", because the docs UI works with **JavaScript**, the cookies won't be sent, and you will see an **error** message as if you didn't write any values.

///


docs/en/docs/tutorial/cookie-params.md::Recap { #recap }::L43

# Doc: docs/en/docs/tutorial/cookie-params.md | Page: Cookie Parameters { #cookie-parameters } | Section: Recap { #recap }
## Recap { #recap }

Declare cookies with `Cookie`, using the same common pattern as `Query` and `Path`.


docs/en/docs/tutorial/cors.md::CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing }::L1

# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing }
# CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing }

[CORS or "Cross-Origin Resource Sharing"](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) refers to the situations when a frontend running in a browser has JavaScript code that communicates with a backend, and the backend is in a different "origin" than the frontend.


docs/en/docs/tutorial/cors.md::Origin { #origin }::L5

# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Origin { #origin }
## Origin { #origin }

An origin is the combination of protocol (`http`, `https`), domain (`myapp.com`, `localhost`, `localhost.tiangolo.com`), and port (`80`, `443`, `8080`).

So, all these are different origins:

* `http://localhost`
* `https://localhost`
* `http://localhost:8080`

Even if they are all in `localhost`, they use different protocols or ports, so, they are different "origins".


docs/en/docs/tutorial/cors.md::Steps { #steps }::L17

# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Steps { #steps }
## Steps { #steps }

So, let's say you have a frontend running in your browser at `http://localhost:8080`, and its JavaScript is trying to communicate with a backend running at `http://localhost` (because we don't specify a port, the browser will assume the default port `80`).

Then, the browser will send an HTTP `OPTIONS` request to the `:80`-backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (`http://localhost:8080`) then the `:8080`-browser will let the JavaScript in the frontend send its request to the `:80`-backend.

To achieve this, the `:80`-backend must have a list of "allowed origins".

In this case, the list would have to include `http://localhost:8080` for the `:8080`-frontend to work correctly.


docs/en/docs/tutorial/cors.md::Wildcards { #wildcards }::L27

# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Wildcards { #wildcards }
## Wildcards { #wildcards }

It's also possible to declare the list as `"*"` (a "wildcard") to say that all are allowed.

But that will only allow certain types of communication, excluding everything that involves credentials: Cookies, Authorization headers like those used with Bearer Tokens, etc.

So, for everything to work correctly, it's better to specify explicitly the allowed origins.


docs/en/docs/tutorial/cors.md::Use `CORSMiddleware` { #use-corsmiddleware }::L35

# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: Use `CORSMiddleware` { #use-corsmiddleware }
## Use `CORSMiddleware` { #use-corsmiddleware }

You can configure it in your **FastAPI** application using the `CORSMiddleware`.

* Import `CORSMiddleware`.
* Create a list of allowed origins (as strings).
* Add it as a "middleware" to your **FastAPI** application.

You can also specify whether your backend allows:

* Credentials (Authorization headers, Cookies, etc).
* Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`.
* Specific HTTP headers or all of them with the wildcard `"*"`.

{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *}

The default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context.

The following arguments are supported:

* `allow_origins` - A list of origins that should be permitted to make cross-origin requests. E.g. `['https://example.org', 'https://www.example.org']`. You can use `['*']` to allow any origin.
* `allow_origin_regex` - A regex string to match against origins that should be permitted to make cross-origin requests. e.g. `'https://.*\.example\.org'`.
* `allow_methods` - A list of HTTP methods that should be allowed for cross-origin requests. Defaults to `['GET']`. You can use `['*']` to allow all standard methods.
* `allow_headers` - A list of HTTP request headers that should be supported for cross-origin requests. Defaults to `[]`. You can use `['*']` to allow all headers. The `Accept`, `Accept-Language`, `Content-Language` and `Content-Type` headers are always allowed for [simple CORS requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests).
* `allow_credentials` - Indicate that cookies should be supported for cross-origin requests. Defaults to `False`.

    None of `allow_origins`, `allow_methods` and `allow_headers` can be set to `['*']` if `allow_credentials` is set to `True`. All of them must be [explicitly specified](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#credentialed_requests_and_wildcards).

* `expose_headers` - Indicate any response headers that should be made accessible to the browser. Defaults to `[]`.
* `max_age` - Sets a maximum time in seconds for browsers to cache CORS responses. Defaults to `600`.

The middleware responds to two particular types of HTTP request...

### CORS preflight requests { #cors-preflight-requests }

These are any `OPTIONS` request with `Origin` and `Access-Control-Request-Method` headers.

In this case the middleware will intercept the incoming request and respond with appropriate CORS headers, and either a `200` or `400` response for informational purposes.

### Simple requests { #simple-requests }

Any request with an `Origin` header. In this case the middleware will pass the request through as normal, but will include appropriate CORS headers on the response.


docs/en/docs/tutorial/cors.md::More info { #more-info }::L79

# Doc: docs/en/docs/tutorial/cors.md | Page: CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } | Section: More info { #more-info }
## More info { #more-info }

For more info about <abbr title="Cross-Origin Resource Sharing">CORS</abbr>, check the [Mozilla CORS documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

/// note | Technical Details

You could also use `from starlette.middleware.cors import CORSMiddleware`.

**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.

///


docs/en/docs/tutorial/debugging.md::Debugging { #debugging }::L1

# Doc: docs/en/docs/tutorial/debugging.md | Page: Debugging { #debugging } | Section: Debugging { #debugging }
# Debugging { #debugging }

You can connect the debugger in your editor, for example with Visual Studio Code or PyCharm.


docs/en/docs/tutorial/debugging.md::Call `uvicorn` { #call-uvicorn }::L5

# Doc: docs/en/docs/tutorial/debugging.md | Page: Debugging { #debugging } | Section: Call `uvicorn` { #call-uvicorn }
## Call `uvicorn` { #call-uvicorn }

In your FastAPI application, import and run `uvicorn` directly:

{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *}

### About `__name__ == "__main__"` { #about-name-main }

The main purpose of the `__name__ == "__main__"` is to have some code that is executed when your file is called with:

```console
$ python myapp.py
```

but is not called when another file imports it, like in:

```Python
from myapp import app
```

#### More details { #more-details }

Let's say your file is named `myapp.py`.

If you run it with:

```console
$ python myapp.py
```

then the internal variable `__name__` in your file, created automatically by Python, will have as value the string `"__main__"`.

So, the section:

```Python
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

will run.

---

This won't happen if you import that module (file).

So, if you have another file `importer.py` with:

```Python
from myapp import app

# Some more code
```

in that case, the automatically created variable `__name__` inside of `myapp.py` will not have the value `"__main__"`.

So, the line:

```Python
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

will not be executed.

/// note

For more information, check [the official Python docs](https://docs.python.org/3/library/__main__.html).

///


docs/en/docs/tutorial/debugging.md::Run your code with your debugger { #run-your-code-with-your-debugger }::L81

# Doc: docs/en/docs/tutorial/debugging.md | Page: Debugging { #debugging } | Section: Run your code with your debugger { #run-your-code-with-your-debugger }
## Run your code with your debugger { #run-your-code-with-your-debugger }

Because you are running the Uvicorn server directly from your code, you can call your Python program (your FastAPI application) directly from the debugger.

---

For example, in Visual Studio Code, you can:

* Go to the "Debug" panel.
* "Add configuration...".
* Select "Python"
* Run the debugger with the option "`Python: Current File (Integrated Terminal)`".

It will then start the server with your **FastAPI** code, stop at your breakpoints, etc.

Here's how it might look:

---

If you use PyCharm, you can:

* Open the "Run" menu.
* Select the option "Debug...".
* Then a context menu shows up.
* Select the file to debug (in this case, `main.py`).

It will then start the server with your **FastAPI** code, stop at your breakpoints, etc.

Here's how it might look:


docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Classes as Dependencies { #classes-as-dependencies }::L1

# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Classes as Dependencies { #classes-as-dependencies }
# Classes as Dependencies { #classes-as-dependencies }

Before diving deeper into the **Dependency Injection** system, let's upgrade the previous example.


docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::A `dict` from the previous example { #a-dict-from-the-previous-example }::L5

# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: A `dict` from the previous example { #a-dict-from-the-previous-example }
## A `dict` from the previous example { #a-dict-from-the-previous-example }

In the previous example, we were returning a `dict` from our dependency ("dependable"):

{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}

But then we get a `dict` in the parameter `commons` of the *path operation function*.

And we know that editors can't provide a lot of support (like completion) for `dict`s, because they can't know their keys and value types.

We can do better...


docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::What makes a dependency { #what-makes-a-dependency }::L17

# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: What makes a dependency { #what-makes-a-dependency }
## What makes a dependency { #what-makes-a-dependency }

Up to now you have seen dependencies declared as functions.

But that's not the only way to declare dependencies (although it would probably be the more common).

The key factor is that a dependency should be a "callable".

A "**callable**" in Python is anything that Python can "call" like a function.

So, if you have an object `something` (that might _not_ be a function) and you can "call" it (execute it) like:

```Python
something()
```

or

```Python
something(some_argument, some_keyword_argument="foo")
```

then it is a "callable".


docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Classes as dependencies { #classes-as-dependencies_1 }::L41

# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Classes as dependencies { #classes-as-dependencies_1 }
## Classes as dependencies { #classes-as-dependencies_1 }

You might notice that to create an instance of a Python class, you use that same syntax.

For example:

```Python
class Cat:
    def __init__(self, name: str):
        self.name = name

fluffy = Cat(name="Mr Fluffy")
```

In this case, `fluffy` is an instance of the class `Cat`.

And to create `fluffy`, you are "calling" `Cat`.

So, a Python class is also a **callable**.

Then, in **FastAPI**, you could use a Python class as a dependency.

What FastAPI actually checks is that it is a "callable" (function, class or anything else) and the parameters defined.

If you pass a "callable" as a dependency in **FastAPI**, it will analyze the parameters for that "callable", and process them in the same way as the parameters for a *path operation function*. Including sub-dependencies.

That also applies to callables with no parameters at all. The same as it would be for *path operation functions* with no parameters.

Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`:

{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}

Pay attention to the `__init__` method used to create the instance of the class:

{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}

...it has the same parameters as our previous `common_parameters`:

{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}

Those parameters are what **FastAPI** will use to "solve" the dependency.

In both cases, it will have:

* An optional `q` query parameter that is a `str`.
* A `skip` query parameter that is an `int`, with a default of `0`.
* A `limit` query parameter that is an `int`, with a default of `100`.

In both cases the data will be converted, validated, documented on the OpenAPI schema, etc.


docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Use it { #use-it }::L92

# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Use it { #use-it }
## Use it { #use-it }

Now you can declare your dependency using this class.

{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}

**FastAPI** calls the `CommonQueryParams` class. This creates an "instance" of that class and the instance will be passed as the parameter `commons` to your function.


docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Type annotation vs `Depends` { #type-annotation-vs-depends }::L100

# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Type annotation vs `Depends` { #type-annotation-vs-depends }
## Type annotation vs `Depends` { #type-annotation-vs-depends }

Notice how we write `CommonQueryParams` twice in the above code:

//// tab | Python 3.10+

```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
```

////

//// tab | Python 3.10+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```

////

The last `CommonQueryParams`, in:

```Python
... Depends(CommonQueryParams)
```

...is what **FastAPI** will actually use to know what is the dependency.

It is from this one that FastAPI will extract the declared parameters and that is what FastAPI will actually call.

---

In this case, the first `CommonQueryParams`, in:

//// tab | Python 3.10+

```Python
commons: Annotated[CommonQueryParams, ...
```

////

//// tab | Python 3.10+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python
commons: CommonQueryParams ...
```

////

...doesn't have any special meaning for **FastAPI**. FastAPI won't use it for data conversion, validation, etc. (as it is using the `Depends(CommonQueryParams)` for that).

You could actually write just:

//// tab | Python 3.10+

```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
```

////

//// tab | Python 3.10+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python
commons = Depends(CommonQueryParams)
```

////

...as in:

{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}

But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc:

<img src="/img/tutorial/dependencies/image02.png">


docs/en/docs/tutorial/dependencies/classes-as-dependencies.md::Shortcut { #shortcut }::L196

# Doc: docs/en/docs/tutorial/dependencies/classes-as-dependencies.md | Page: Classes as Dependencies { #classes-as-dependencies } | Section: Shortcut { #shortcut }
## Shortcut { #shortcut }

But you see that we are having some code repetition here, writing `CommonQueryParams` twice:

//// tab | Python 3.10+

```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
```

////

//// tab | Python 3.10+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```

////

**FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will "call" to create an instance of the class itself.

For those specific cases, you can do the following:

Instead of writing:

//// tab | Python 3.10+

```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
```

////

//// tab | Python 3.10+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```

////

...you write:

//// tab | Python 3.10+

```Python
commons: Annotated[CommonQueryParams, Depends()]
```

////

//// tab | Python 3.10+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python
commons: CommonQueryParams = Depends()
```

////

You declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.

The same example would then look like:

{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}

...and **FastAPI** will know what to do.

/// tip

If that seems more confusing than helpful, disregard it, you don't *need* it.

It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition.

///


docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }::L1

# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }
# Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }

In some cases you don't really need the return value of a dependency inside your *path operation function*.

Or the dependency doesn't return a value.

But you still need it to be executed/solved.

For those cases, instead of declaring a *path operation function* parameter with `Depends`, you can add a `list` of `dependencies` to the *path operation decorator*.


docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }::L11

# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }
## Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }

The *path operation decorator* receives an optional argument `dependencies`.

It should be a `list` of `Depends()`:

{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}

These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.

/// tip

Some editors check for unused function parameters, and show them as errors.

Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors.

It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary.

///

/// note

In this example we use invented custom headers `X-Key` and `X-Token`.

But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md).

///


docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Dependencies errors and return values { #dependencies-errors-and-return-values }::L39

# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Dependencies errors and return values { #dependencies-errors-and-return-values }
## Dependencies errors and return values { #dependencies-errors-and-return-values }

You can use the same dependency *functions* you use normally.

### Dependency requirements { #dependency-requirements }

They can declare request requirements (like headers) or other sub-dependencies:

{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}

### Raise exceptions { #raise-exceptions }

These dependencies can `raise` exceptions, the same as normal dependencies:

{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}

### Return values { #return-values }

And they can return values or not, the values won't be used.

So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:

{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}


docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }::L63

# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }
## Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }

Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.


docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md::Global Dependencies { #global-dependencies }::L67

# Doc: docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md | Page: Dependencies in path operation decorators { #dependencies-in-path-operation-decorators } | Section: Global Dependencies { #global-dependencies }
## Global Dependencies { #global-dependencies }

Next we will see how to add dependencies to the whole `FastAPI` application, so that they apply to each *path operation*.


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with yield { #dependencies-with-yield }::L1

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with yield { #dependencies-with-yield }
# Dependencies with yield { #dependencies-with-yield }

FastAPI supports dependencies that do some <dfn title='sometimes also called "exit code", "cleanup code", "teardown code", "closing code", "context manager exit code", etc.'>extra steps after finishing</dfn>.

To do this, use `yield` instead of `return`, and write the extra steps (code) after.

/// tip

Make sure to use `yield` one single time per dependency.

///

/// note | Technical Details

Any function that is valid to use with:

* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) or
* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)

would be valid to use as a **FastAPI** dependency.

In fact, FastAPI uses those two decorators internally.

///


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::A database dependency with `yield` { #a-database-dependency-with-yield }::L26

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: A database dependency with `yield` { #a-database-dependency-with-yield }
## A database dependency with `yield` { #a-database-dependency-with-yield }

For example, you could use this to create a database session and close it after finishing.

Only the code prior to and including the `yield` statement is executed before creating a response:

{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}

The yielded value is what is injected into *path operations* and other dependencies:

{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}

The code following the `yield` statement is executed after the response:

{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}

/// tip

You can use `async` or regular functions.

**FastAPI** will do the right thing with each, the same as with normal dependencies.

///


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }::L50

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }
## A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }

If you use a `try` block in a dependency with `yield`, you'll receive any exception that was thrown when using the dependency.

For example, if some code at some point in the middle, in another dependency or in a *path operation*, made a database transaction "rollback" or created any other exception, you would receive the exception in your dependency.

So, you can look for that specific exception inside the dependency with `except SomeException`.

In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not.

{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Sub-dependencies with `yield` { #sub-dependencies-with-yield }::L62

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Sub-dependencies with `yield` { #sub-dependencies-with-yield }
## Sub-dependencies with `yield` { #sub-dependencies-with-yield }

You can have sub-dependencies and "trees" of sub-dependencies of any size and shape, and any or all of them can use `yield`.

**FastAPI** will make sure that the "exit code" in each dependency with `yield` is run in the correct order.

For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`:

{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}

And all of them can use `yield`.

In this case `dependency_c`, to execute its exit code, needs the value from `dependency_b` (here named `dep_b`) to still be available.

And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.

{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}

The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others.

And you could have a single dependency that requires several other dependencies with `yield`, etc.

You can have any combinations of dependencies that you want.

**FastAPI** will make sure everything is run in the correct order.

/// note | Technical Details

This works thanks to Python's [Context Managers](https://docs.python.org/3/library/contextlib.html).

**FastAPI** uses them internally to achieve this.

///


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }::L96

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }
## Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }

You saw that you can use dependencies with `yield` and have `try` blocks that try to execute some code and then run some exit code after `finally`.

You can also use `except` to catch the exception that was raised and do something with it.

For example, you can raise a different exception, like `HTTPException`.

/// tip

This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*.

But it's there for you if you need it. 🤓

///

{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}

If you want to catch exceptions and create a custom response based on that, create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers).


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }::L116

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }
## Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }

If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python:

{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}

In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱

### Always `raise` in Dependencies with `yield` and `except` { #always-raise-in-dependencies-with-yield-and-except }

If you catch an exception in a dependency with `yield`, unless you are raising another `HTTPException` or similar, **you should re-raise the original exception**.

You can re-raise the same exception using `raise`:

{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}

Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }::L134

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }
## Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }

The sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code.

```mermaid
sequenceDiagram

participant client as Client
participant handler as Exception handler
participant dep as Dep with yield
participant operation as Path Operation
participant tasks as Background tasks

    Note over client,operation: Can raise exceptions, including HTTPException
    client ->> dep: Start request
    Note over dep: Run code up to yield
    opt raise Exception
        dep -->> handler: Raise Exception
        handler -->> client: HTTP error response
    end
    dep ->> operation: Run dependency, e.g. DB session
    opt raise
        operation -->> dep: Raise Exception (e.g. HTTPException)
        opt handle
            dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
        end
        handler -->> client: HTTP error response
    end

    operation ->> client: Return response to client
    Note over client,operation: Response is already sent, can't change it anymore
    opt Tasks
        operation -->> tasks: Send background tasks
    end
    opt Raise other exception
        tasks -->> tasks: Handle exceptions in the background task code
    end
```

/// note

Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*.

After one of those responses is sent, no other response can be sent.

///

/// tip

If you raise any exception in the code from the *path operation function*, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled.

///


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Early exit and `scope` { #early-exit-and-scope }::L187

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Early exit and `scope` { #early-exit-and-scope }
## Early exit and `scope` { #early-exit-and-scope }

Normally the exit code of dependencies with `yield` is executed **after the response** is sent to the client.

But if you know that you won't need to use the dependency after returning from the *path operation function*, you can use `Depends(scope="function")` to tell FastAPI that it should close the dependency after the *path operation function* returns, but **before** the **response is sent**.

{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}

`Depends()` receives a `scope` parameter that can be:

* `"function"`: start the dependency before the *path operation function* that handles the request, end the dependency after the *path operation function* ends, but **before** the response is sent back to the client. So, the dependency function will be executed **around** the *path operation **function***.
* `"request"`: start the dependency before the *path operation function* that handles the request (similar to when using `"function"`), but end **after** the response is sent back to the client. So, the dependency function will be executed **around** the **request** and response cycle.

If not specified and the dependency has `yield`, it will have a `scope` of `"request"` by default.

### `scope` for sub-dependencies { #scope-for-sub-dependencies }

When you declare a dependency with a `scope="request"` (the default), any sub-dependency needs to also have a `scope` of `"request"`.

But a dependency with `scope` of `"function"` can have dependencies with `scope` of `"function"` and `scope` of `"request"`.

This is because any dependency needs to be able to run its exit code before the sub-dependencies, as it might need to still use them during its exit code.

```mermaid
sequenceDiagram

participant client as Client
participant dep_req as Dep scope="request"
participant dep_func as Dep scope="function"
participant operation as Path Operation

    client ->> dep_req: Start request
    Note over dep_req: Run code up to yield
    dep_req ->> dep_func: Pass dependency
    Note over dep_func: Run code up to yield
    dep_func ->> operation: Run path operation with dependency
    operation ->> dep_func: Return from path operation
    Note over dep_func: Run code after yield
    Note over dep_func: ✅ Dependency closed
    dep_func ->> client: Send response to client
    Note over client: Response sent
    Note over dep_req: Run code after yield
    Note over dep_req: ✅ Dependency closed
```


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }::L232

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }
## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }

Dependencies with `yield` have evolved over time to cover different use cases and fix some issues.

If you want to see what has changed in different versions of FastAPI, you can read more about it in the advanced guide, in [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).


docs/en/docs/tutorial/dependencies/dependencies-with-yield.md::Context Managers { #context-managers }::L238

# Doc: docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | Page: Dependencies with yield { #dependencies-with-yield } | Section: Context Managers { #context-managers }
## Context Managers { #context-managers }

### What are "Context Managers" { #what-are-context-managers }

"Context Managers" are any of those Python objects that you can use in a `with` statement.

For example, [you can use `with` to read a file](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):

```Python
with open("./somefile.txt") as f:
    contents = f.read()
    print(contents)
```

Underneath, the `open("./somefile.txt")` creates an object that is called a "Context Manager".

When the `with` block finishes, it makes sure to close the file, even if there were exceptions.

When you create a dependency with `yield`, **FastAPI** will internally create a context manager for it, and combine it with some other related tools.

### Using context managers in dependencies with `yield` { #using-context-managers-in-dependencies-with-yield }

/// warning

This is, more or less, an "advanced" idea.

If you are just starting with **FastAPI** you might want to skip it for now.

///

In Python, you can create Context Managers by [creating a class with two methods: `__enter__()` and `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).

You can also use them inside of **FastAPI** dependencies with `yield` by using
`with` or `async with` statements inside of the dependency function:

{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}

/// tip

Another way to create a context manager is with:

* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) or
* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)

using them to decorate a function with a single `yield`.

That's what **FastAPI** uses internally for dependencies with `yield`.

But you don't have to use the decorators for FastAPI dependencies (and you shouldn't).

FastAPI will do it for you internally.

///


docs/en/docs/tutorial/dependencies/global-dependencies.md::Global Dependencies { #global-dependencies }::L1

# Doc: docs/en/docs/tutorial/dependencies/global-dependencies.md | Page: Global Dependencies { #global-dependencies } | Section: Global Dependencies { #global-dependencies }
# Global Dependencies { #global-dependencies }

For some types of applications you might want to add dependencies to the whole application.

Similar to the way you can [add `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md), you can add them to the `FastAPI` application.

In that case, they will be applied to all the *path operations* in the application:

{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}

And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md) still apply, but in this case, to all of the *path operations* in the app.


docs/en/docs/tutorial/dependencies/global-dependencies.md::Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }::L14

# Doc: docs/en/docs/tutorial/dependencies/global-dependencies.md | Page: Global Dependencies { #global-dependencies } | Section: Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }
## Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }

Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.


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

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

**FastAPI** has a very powerful but intuitive **<dfn title="also known as components, resources, providers, services, injectables">Dependency Injection</dfn>** system.

It is designed to be very simple to use, and to make it very easy for any developer to integrate other components with **FastAPI**.


docs/en/docs/tutorial/dependencies/index.md::What is "Dependency Injection" { #what-is-dependency-injection }::L7

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: What is "Dependency Injection" { #what-is-dependency-injection }
## What is "Dependency Injection" { #what-is-dependency-injection }

**"Dependency Injection"** means, in programming, that there is a way for your code (in this case, your *path operation functions*) to declare things that it requires to work and use: "dependencies".

And then, that system (in this case **FastAPI**) will take care of doing whatever is needed to provide your code with those needed dependencies ("inject" the dependencies).

This is very useful when you need to:

* Have shared logic (the same code logic again and again).
* Share database connections.
* Enforce security, authentication, role requirements, etc.
* And many other things...

All these, while minimizing code repetition.


docs/en/docs/tutorial/dependencies/index.md::First Steps { #first-steps }::L22

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: First Steps { #first-steps }
## First Steps { #first-steps }

Let's see a very simple example. It will be so simple that it is not very useful, for now.

But this way we can focus on how the **Dependency Injection** system works.

### Create a dependency, or "dependable" { #create-a-dependency-or-dependable }

Let's first focus on the dependency.

It is just a function that can take all the same parameters that a *path operation function* can take:

{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}

That's it.

**2 lines**.

And it has the same shape and structure that all your *path operation functions* have.

You can think of it as a *path operation function* without the "decorator" (without the `@app.get("/some-path")`).

And it can return anything you want.

In this case, this dependency expects:

* An optional query parameter `q` that is a `str`.
* An optional query parameter `skip` that is an `int`, and by default is `0`.
* An optional query parameter `limit` that is an `int`, and by default is `100`.

And then it just returns a `dict` containing those values.

/// note

FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.

If you have an older version, you would get errors when trying to use `Annotated`.

Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions) to at least 0.95.1 before using `Annotated`.

///

### Import `Depends` { #import-depends }

{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}

### Declare the dependency, in the "dependant" { #declare-the-dependency-in-the-dependant }

The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter:

{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}

Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently.

You only give `Depends` a single parameter.

This parameter must be something like a function.

You **don't call it** directly (don't add the parenthesis at the end), you just pass it as a parameter to `Depends()`.

And that function takes parameters in the same way that *path operation functions* do.

/// tip

You'll see what other "things", apart from functions, can be used as dependencies in the next chapter.

///

Whenever a new request arrives, **FastAPI** will take care of:

* Calling your dependency ("dependable") function with the correct parameters.
* Get the result from your function.
* Assign that result to the parameter in your *path operation function*.

```mermaid
graph TB

common_parameters(["common_parameters"])
read_items["/items/"]
read_users["/users/"]

common_parameters --> read_items
common_parameters --> read_users
```

This way you write shared code once and **FastAPI** takes care of calling it for your *path operations*.

/// tip

Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar.

You just pass it to `Depends` and **FastAPI** knows how to do the rest.

///


docs/en/docs/tutorial/dependencies/index.md::Share `Annotated` dependencies { #share-annotated-dependencies }::L117

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Share `Annotated` dependencies { #share-annotated-dependencies }
## Share `Annotated` dependencies { #share-annotated-dependencies }

In the examples above, you see that there's a tiny bit of **code duplication**.

When you need to use the `common_parameters()` dependency, you have to write the whole parameter with the type annotation and `Depends()`:

```Python
commons: Annotated[dict, Depends(common_parameters)]
```

But because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places:

{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}

/// tip

This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**.

But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎

///

The dependencies will keep working as expected, and the **best part** is that the **type information will be preserved**, which means that your editor will be able to keep providing you with **autocompletion**, **inline errors**, etc. The same for other tools like `mypy`.

This will be especially useful when you use it in a **large code base** where you use **the same dependencies** over and over again in **many *path operations***.


docs/en/docs/tutorial/dependencies/index.md::To `async` or not to `async` { #to-async-or-not-to-async }::L143

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: To `async` or not to `async` { #to-async-or-not-to-async }
## To `async` or not to `async` { #to-async-or-not-to-async }

As dependencies will also be called by **FastAPI** (the same as your *path operation functions*), the same rules apply while defining your functions.

You can use `async def` or normal `def`.

And you can declare dependencies with `async def` inside of normal `def` *path operation functions*, or `def` dependencies inside of `async def` *path operation functions*, etc.

It doesn't matter. **FastAPI** will know what to do.

/// note

If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry) section about `async` and `await` in the docs.

///


docs/en/docs/tutorial/dependencies/index.md::Integrated with OpenAPI { #integrated-with-openapi }::L159

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Integrated with OpenAPI { #integrated-with-openapi }
## Integrated with OpenAPI { #integrated-with-openapi }

All the request declarations, validations and requirements of your dependencies (and sub-dependencies) will be integrated in the same OpenAPI schema.

So, the interactive docs will have all the information from these dependencies too:

<img src="/img/tutorial/dependencies/image01.png">


docs/en/docs/tutorial/dependencies/index.md::Simple usage { #simple-usage }::L167

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Simple usage { #simple-usage }
## Simple usage { #simple-usage }

If you look at it, *path operation functions* are declared to be used whenever a *path* and *operation* matches, and then **FastAPI** takes care of calling the function with the correct parameters, extracting the data from the request.

Actually, all (or most) of the web frameworks work in this same way.

You never call those functions directly. They are called by your framework (in this case, **FastAPI**).

With the Dependency Injection system, you can also tell **FastAPI** that your *path operation function* also "depends" on something else that should be executed before your *path operation function*, and **FastAPI** will take care of executing it and "injecting" the results.

Other common terms for this same idea of "dependency injection" are:

* resources
* providers
* services
* injectables
* components


docs/en/docs/tutorial/dependencies/index.md::**FastAPI** plug-ins { #fastapi-plug-ins }::L185

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: **FastAPI** plug-ins { #fastapi-plug-ins }
## **FastAPI** plug-ins { #fastapi-plug-ins }

Integrations and "plug-ins" can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*.

And dependencies can be created in a very simple and intuitive way that allows you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*.

You will see examples of this in the next chapters, about relational and NoSQL databases, security, etc.


docs/en/docs/tutorial/dependencies/index.md::**FastAPI** compatibility { #fastapi-compatibility }::L193

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

The simplicity of the dependency injection system makes **FastAPI** compatible with:

* all the relational databases
* NoSQL databases
* external packages
* external APIs
* authentication and authorization systems
* API usage monitoring systems
* response data injection systems
* etc.


docs/en/docs/tutorial/dependencies/index.md::Simple and Powerful { #simple-and-powerful }::L206

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Simple and Powerful { #simple-and-powerful }
## Simple and Powerful { #simple-and-powerful }

Although the hierarchical dependency injection system is very simple to define and use, it's still very powerful.

You can define dependencies that in turn can define dependencies themselves.

In the end, a hierarchical tree of dependencies is built, and the **Dependency Injection** system takes care of solving all these dependencies for you (and their sub-dependencies) and providing (injecting) the results at each step.

For example, let's say you have 4 API endpoints (*path operations*):

* `/items/public/`
* `/items/private/`
* `/users/{user_id}/activate`
* `/items/pro/`

then you could add different permission requirements for each of them just with dependencies and sub-dependencies:

```mermaid
graph TB

current_user(["current_user"])
active_user(["active_user"])
admin_user(["admin_user"])
paying_user(["paying_user"])

public["/items/public/"]
private["/items/private/"]
activate_user["/users/{user_id}/activate"]
pro_items["/items/pro/"]

current_user --> active_user
active_user --> admin_user
active_user --> paying_user

current_user --> public
active_user --> private
admin_user --> activate_user
paying_user --> pro_items
```


docs/en/docs/tutorial/dependencies/index.md::Integrated with **OpenAPI** { #integrated-with-openapi_1 }::L246

# Doc: docs/en/docs/tutorial/dependencies/index.md | Page: Dependencies { #dependencies } | Section: Integrated with **OpenAPI** { #integrated-with-openapi_1 }
## Integrated with **OpenAPI** { #integrated-with-openapi_1 }

All these dependencies, while declaring their requirements, also add parameters, validations, etc. to your *path operations*.

**FastAPI** will take care of adding it all to the OpenAPI schema, so that it is shown in the interactive documentation systems.


docs/en/docs/tutorial/dependencies/sub-dependencies.md::Sub-dependencies { #sub-dependencies }::L1

# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Sub-dependencies { #sub-dependencies }
# Sub-dependencies { #sub-dependencies }

You can create dependencies that have **sub-dependencies**.

They can be as **deep** as you need them to be.

**FastAPI** will take care of solving them.


docs/en/docs/tutorial/dependencies/sub-dependencies.md::First dependency "dependable" { #first-dependency-dependable }::L9

# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: First dependency "dependable" { #first-dependency-dependable }
## First dependency "dependable" { #first-dependency-dependable }

You could create a first dependency ("dependable") like:

{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}

It declares an optional query parameter `q` as a `str`, and then it just returns it.

This is quite simple (not very useful), but will help us focus on how the sub-dependencies work.


docs/en/docs/tutorial/dependencies/sub-dependencies.md::Second dependency, "dependable" and "dependant" { #second-dependency-dependable-and-dependant }::L19

# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Second dependency, "dependable" and "dependant" { #second-dependency-dependable-and-dependant }
## Second dependency, "dependable" and "dependant" { #second-dependency-dependable-and-dependant }

Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too):

{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}

Let's focus on the parameters declared:

* Even though this function is a dependency ("dependable") itself, it also declares another dependency (it "depends" on something else).
    * It depends on the `query_extractor`, and assigns the value returned by it to the parameter `q`.
* It also declares an optional `last_query` cookie, as a `str`.
    * If the user didn't provide any query `q`, we use the last query used, which we saved to a cookie before.


docs/en/docs/tutorial/dependencies/sub-dependencies.md::Use the dependency { #use-the-dependency }::L32

# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Use the dependency { #use-the-dependency }
## Use the dependency { #use-the-dependency }

Then we can use the dependency with:

{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}

/// note

Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.

But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it.

///

```mermaid
graph TB

query_extractor(["query_extractor"])
query_or_cookie_extractor(["query_or_cookie_extractor"])

read_query["/items/"]

query_extractor --> query_or_cookie_extractor --> read_query
```


docs/en/docs/tutorial/dependencies/sub-dependencies.md::Using the same dependency multiple times { #using-the-same-dependency-multiple-times }::L57

# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Using the same dependency multiple times { #using-the-same-dependency-multiple-times }
## Using the same dependency multiple times { #using-the-same-dependency-multiple-times }

If one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request.

And it will save the returned value in a <dfn title="A utility/system to store computed/generated values, to reuse them instead of computing them again.">"cache"</dfn> and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.

In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`:

//// tab | Python 3.10+

```Python hl_lines="1"
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
    return {"fresh_value": fresh_value}
```

////

//// tab | Python 3.10+ non-Annotated

/// tip

Prefer to use the `Annotated` version if possible.

///

```Python hl_lines="1"
async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
    return {"fresh_value": fresh_value}
```

////


docs/en/docs/tutorial/dependencies/sub-dependencies.md::Recap { #recap }::L89

# Doc: docs/en/docs/tutorial/dependencies/sub-dependencies.md | Page: Sub-dependencies { #sub-dependencies } | Section: Recap { #recap }
## Recap { #recap }

Apart from all the fancy words used here, the **Dependency Injection** system is quite simple.

Just functions that look the same as the *path operation functions*.

But still, it is very powerful, and allows you to declare arbitrarily deeply nested dependency "graphs" (trees).

/// tip

All this might not seem as useful with these simple examples.

But you will see how useful it is in the chapters about **security**.

And you will also see the amounts of code it will save you.

///


docs/en/docs/tutorial/encoder.md::JSON Compatible Encoder { #json-compatible-encoder }::L1

# Doc: docs/en/docs/tutorial/encoder.md | Page: JSON Compatible Encoder { #json-compatible-encoder } | Section: JSON Compatible Encoder { #json-compatible-encoder }
# JSON Compatible Encoder { #json-compatible-encoder }

There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a `dict`, `list`, etc).

For example, if you need to store it in a database.

For that, **FastAPI** provides a `jsonable_encoder()` function.


docs/en/docs/tutorial/encoder.md::Using the `jsonable_encoder` { #using-the-jsonable-encoder }::L9

# Doc: docs/en/docs/tutorial/encoder.md | Page: JSON Compatible Encoder { #json-compatible-encoder } | Section: Using the `jsonable_encoder` { #using-the-jsonable-encoder }
## Using the `jsonable_encoder` { #using-the-jsonable-encoder }

Let's imagine that you have a database `fake_db` that only receives JSON compatible data.

For example, it doesn't receive `datetime` objects, as those are not compatible with JSON.

So, a `datetime` object would have to be converted to a `str` containing the data in [ISO format](https://en.wikipedia.org/wiki/ISO_8601).

The same way, this database wouldn't receive a Pydantic model (an object with attributes), only a `dict`.

You can use `jsonable_encoder` for that.

It receives an object, like a Pydantic model, and returns a JSON compatible version:

{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}

In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`.

The result of calling it is something that can be encoded with the Python standard [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).

It doesn't return a large `str` containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a `dict`) with values and sub-values that are all compatible with JSON.

/// note

`jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios.

///