mirror of
https://github.com/fastapi/fastapi.git
synced 2025-12-25 23:29:34 -05:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d666ccb622 | ||
|
|
38f0cad517 | ||
|
|
bd90bed02a | ||
|
|
546392db98 | ||
|
|
0bc87ec77c | ||
|
|
fbfd53542e | ||
|
|
994ea1ad33 | ||
|
|
69673548bc | ||
|
|
166d348ea6 | ||
|
|
9eaed2eb37 | ||
|
|
f63b3ad53e | ||
|
|
375513f114 | ||
|
|
ef176c6631 | ||
|
|
7b7e86a307 | ||
|
|
25aabe05ce |
@@ -14,9 +14,41 @@ But you also want it to accept new items. And when the items didn't exist before
|
||||
|
||||
To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="4 26"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 23"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning
|
||||
When you return a `Response` directly, like in the example above, it will be returned directly.
|
||||
|
||||
@@ -18,9 +18,26 @@ Not the class itself (which is already a callable), but an instance of that clas
|
||||
|
||||
To do that, we declare a method `__call__`:
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.
|
||||
|
||||
@@ -28,9 +45,26 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition
|
||||
|
||||
And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.
|
||||
|
||||
@@ -38,9 +72,26 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use
|
||||
|
||||
We could create an instance of this class with:
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`.
|
||||
|
||||
@@ -56,9 +107,26 @@ checker(q="somequery")
|
||||
|
||||
...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`:
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!> ../../../docs_src/dependencies/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial011.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
All this might seem contrived. And it might not be very clear how is it useful yet.
|
||||
|
||||
@@ -16,18 +16,18 @@ If you are building a **frontend**, a very interesting alternative is <a href="h
|
||||
|
||||
Let's start with a simple FastAPI application:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9-11 14-15 18 19 23"
|
||||
{!> ../../../docs_src/generate_clients/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7-9 12-13 16-17 21"
|
||||
{!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9-11 14-15 18 19 23"
|
||||
{!> ../../../docs_src/generate_clients/tutorial001.py!}
|
||||
```
|
||||
|
||||
Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.
|
||||
|
||||
### API Docs
|
||||
@@ -128,19 +128,18 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to
|
||||
|
||||
For example, you could have a section for **items** and another section for **users**, and they could be separated by tags:
|
||||
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="23 28 36"
|
||||
{!> ../../../docs_src/generate_clients/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="21 26 34"
|
||||
{!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="23 28 36"
|
||||
{!> ../../../docs_src/generate_clients/tutorial002.py!}
|
||||
```
|
||||
|
||||
### Generate a TypeScript Client with Tags
|
||||
|
||||
If you generate a client for a FastAPI app using tags, it will normally also separate the client code based on the tags.
|
||||
@@ -186,18 +185,18 @@ For example, here it is using the first tag (you will probably have only one tag
|
||||
|
||||
You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="8-9 12"
|
||||
{!> ../../../docs_src/generate_clients/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6-7 10"
|
||||
{!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8-9 12"
|
||||
{!> ../../../docs_src/generate_clients/tutorial003.py!}
|
||||
```
|
||||
|
||||
### Generate a TypeScript Client with Custom Operation IDs
|
||||
|
||||
Now if you generate the client again, you will see that it has the improved method names:
|
||||
|
||||
@@ -20,9 +20,26 @@ Then, when you type that username and password, the browser sends them in the he
|
||||
* It returns an object of type `HTTPBasicCredentials`:
|
||||
* It contains the `username` and `password` sent.
|
||||
|
||||
```Python hl_lines="2 6 10"
|
||||
{!../../../docs_src/security/tutorial006.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 8 12"
|
||||
{!> ../../../docs_src/security/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="2 7 11"
|
||||
{!> ../../../docs_src/security/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 6 10"
|
||||
{!> ../../../docs_src/security/tutorial006.py!}
|
||||
```
|
||||
|
||||
When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password:
|
||||
|
||||
@@ -42,9 +59,26 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi
|
||||
|
||||
Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`.
|
||||
|
||||
```Python hl_lines="1 11-21"
|
||||
{!../../../docs_src/security/tutorial007.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1 12-24"
|
||||
{!> ../../../docs_src/security/tutorial007_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 12-24"
|
||||
{!> ../../../docs_src/security/tutorial007_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 11-21"
|
||||
{!> ../../../docs_src/security/tutorial007.py!}
|
||||
```
|
||||
|
||||
This would be similar to:
|
||||
|
||||
@@ -108,6 +142,23 @@ That way, using `secrets.compare_digest()` in your application code, it will be
|
||||
|
||||
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
|
||||
|
||||
```Python hl_lines="23-27"
|
||||
{!../../../docs_src/security/tutorial007.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="26-30"
|
||||
{!> ../../../docs_src/security/tutorial007_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="26-30"
|
||||
{!> ../../../docs_src/security/tutorial007_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="23-27"
|
||||
{!> ../../../docs_src/security/tutorial007.py!}
|
||||
```
|
||||
|
||||
@@ -56,9 +56,50 @@ They are normally used to declare specific security permissions, for example:
|
||||
|
||||
First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes:
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
Now let's review those changes step by step.
|
||||
|
||||
@@ -68,9 +109,51 @@ The first change is that now we are declaring the OAuth2 security scheme with tw
|
||||
|
||||
The `scopes` parameter receives a `dict` with each scope as a key and the description as the value:
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="63-66"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="61-64"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="62-65"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.
|
||||
|
||||
@@ -93,9 +176,50 @@ And we return the scopes as part of the JWT token.
|
||||
|
||||
But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
|
||||
|
||||
```Python hl_lines="153"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="155"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="155"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="156"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="152"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="153"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="153"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Declare scopes in *path operations* and dependencies
|
||||
|
||||
@@ -118,9 +242,50 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
|
||||
We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
|
||||
|
||||
```Python hl_lines="4 139 166"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 139 170"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 139 170"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="4 140 171"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 138 165"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 139 166"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 139 166"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! info "Technical Details"
|
||||
`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
|
||||
@@ -143,9 +308,50 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas
|
||||
|
||||
This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly).
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8 106"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7 104"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8 105"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Use the `scopes`
|
||||
|
||||
@@ -159,9 +365,50 @@ We create an `HTTPException` that we can re-use (`raise`) later at several point
|
||||
|
||||
In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec).
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="106 108-116"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="104 106-114"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="105 107-115"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Verify the `username` and data shape
|
||||
|
||||
@@ -177,9 +424,50 @@ Instead of, for example, a `dict`, or something else, as it could break the appl
|
||||
|
||||
We also verify that we have a user with that username, and if not, we raise that same exception we created before.
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="47 117-128"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="45 115-126"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="46 116-127"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Verify the `scopes`
|
||||
|
||||
@@ -187,9 +475,50 @@ We now verify that all the scopes required, by this dependency and all the depen
|
||||
|
||||
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
{!> ../../../docs_src/security/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="129-135"
|
||||
{!> ../../../docs_src/security/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="127-133"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="128-134"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Dependency tree and scopes
|
||||
|
||||
|
||||
@@ -216,9 +216,26 @@ Notice that now we don't create a default instance `settings = Settings()`.
|
||||
|
||||
Now we create a dependency that returns a new `config.Settings()`.
|
||||
|
||||
```Python hl_lines="5 11-12"
|
||||
{!../../../docs_src/settings/app02/main.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6 12-13"
|
||||
{!> ../../../docs_src/settings/app02_an_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="6 12-13"
|
||||
{!> ../../../docs_src/settings/app02_an/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="5 11-12"
|
||||
{!> ../../../docs_src/settings/app02/main.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
We'll discuss the `@lru_cache()` in a bit.
|
||||
@@ -227,9 +244,26 @@ Now we create a dependency that returns a new `config.Settings()`.
|
||||
|
||||
And then we can require it from the *path operation function* as a dependency and use it anywhere we need it.
|
||||
|
||||
```Python hl_lines="16 18-20"
|
||||
{!../../../docs_src/settings/app02/main.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="17 19-21"
|
||||
{!> ../../../docs_src/settings/app02_an_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="17 19-21"
|
||||
{!> ../../../docs_src/settings/app02_an/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="16 18-20"
|
||||
{!> ../../../docs_src/settings/app02/main.py!}
|
||||
```
|
||||
|
||||
### Settings and testing
|
||||
|
||||
@@ -304,9 +338,26 @@ we would create that object for each request, and we would be reading the `.env`
|
||||
|
||||
But as we are using the `@lru_cache()` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️
|
||||
|
||||
```Python hl_lines="1 10"
|
||||
{!../../../docs_src/settings/app03/main.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1 11"
|
||||
{!> ../../../docs_src/settings/app03_an_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 11"
|
||||
{!> ../../../docs_src/settings/app03_an/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 10"
|
||||
{!> ../../../docs_src/settings/app03/main.py!}
|
||||
```
|
||||
|
||||
Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.
|
||||
|
||||
|
||||
@@ -28,9 +28,41 @@ To override a dependency for testing, you put as a key the original dependency (
|
||||
|
||||
And then **FastAPI** will call that override instead of the original dependency.
|
||||
|
||||
```Python hl_lines="28-29 32"
|
||||
{!../../../docs_src/dependency_testing/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="26-27 30"
|
||||
{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="28-29 32"
|
||||
{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="29-30 33"
|
||||
{!> ../../../docs_src/dependency_testing/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="24-25 28"
|
||||
{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="28-29 32"
|
||||
{!> ../../../docs_src/dependency_testing/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
You can set a dependency override for a dependency used anywhere in your **FastAPI** application.
|
||||
|
||||
@@ -112,9 +112,41 @@ In WebSocket endpoints you can import from `fastapi` and use:
|
||||
|
||||
They work the same way as for other FastAPI endpoints/*path operations*:
|
||||
|
||||
```Python hl_lines="66-77 76-91"
|
||||
{!../../../docs_src/websockets/tutorial002.py!}
|
||||
```
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="68-69 82"
|
||||
{!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="68-69 82"
|
||||
{!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="69-70 83"
|
||||
{!> ../../../docs_src/websockets/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="66-67 79"
|
||||
{!> ../../../docs_src/websockets/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="68-69 81"
|
||||
{!> ../../../docs_src/websockets/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`.
|
||||
@@ -153,9 +185,17 @@ With that you can connect the WebSocket and then send and receive messages:
|
||||
|
||||
When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example.
|
||||
|
||||
```Python hl_lines="81-83"
|
||||
{!../../../docs_src/websockets/tutorial003.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="79-81"
|
||||
{!> ../../../docs_src/websockets/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="81-83"
|
||||
{!> ../../../docs_src/websockets/tutorial003.py!}
|
||||
```
|
||||
|
||||
To try it out:
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Python Types Intro
|
||||
|
||||
Python has support for optional "type hints".
|
||||
Python has support for optional "type hints" (also called "type annotations").
|
||||
|
||||
These **"type hints"** are a special syntax that allow declaring the <abbr title="for example: str, int, float, bool">type</abbr> of a variable.
|
||||
These **"type hints"** or annotations are a special syntax that allow declaring the <abbr title="for example: str, int, float, bool">type</abbr> of a variable.
|
||||
|
||||
By declaring types for your variables, editors and tools can give you better support.
|
||||
|
||||
@@ -158,13 +158,31 @@ The syntax using `typing` is **compatible** with all versions, from Python 3.6 t
|
||||
|
||||
As Python advances, **newer versions** come with improved support for these type annotations and in many cases you won't even need to import and use the `typing` module to declare the type annotations.
|
||||
|
||||
If you can choose a more recent version of Python for your project, you will be able to take advantage of that extra simplicity. See some examples below.
|
||||
If you can choose a more recent version of Python for your project, you will be able to take advantage of that extra simplicity.
|
||||
|
||||
In all the docs there are examples compatible with each version of Python (when there's a difference).
|
||||
|
||||
For example "**Python 3.6+**" means it's compatible with Python 3.6 or above (including 3.7, 3.8, 3.9, 3.10, etc). And "**Python 3.9+**" means it's compatible with Python 3.9 or above (including 3.10, etc).
|
||||
|
||||
If you can use the **latest versions of Python**, use the examples for the latest version, those will have the **best and simplest syntax**, for example, "**Python 3.10+**".
|
||||
|
||||
#### List
|
||||
|
||||
For example, let's define a variable to be a `list` of `str`.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
Declare the variable, with the same colon (`:`) syntax.
|
||||
|
||||
As the type, put `list`.
|
||||
|
||||
As the list is a type that contains some internal types, you put them in square brackets:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial006_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
From `typing`, import `List` (with a capital `L`):
|
||||
|
||||
@@ -182,18 +200,6 @@ For example, let's define a variable to be a `list` of `str`.
|
||||
{!> ../../../docs_src/python_types/tutorial006.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
|
||||
Declare the variable, with the same colon (`:`) syntax.
|
||||
|
||||
As the type, put `list`.
|
||||
|
||||
As the list is a type that contains some internal types, you put them in square brackets:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial006_py39.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
Those internal types in the square brackets are called "type parameters".
|
||||
|
||||
@@ -218,18 +224,18 @@ And still, the editor knows it is a `str`, and provides support for that.
|
||||
|
||||
You would do the same to declare `tuple`s and `set`s:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial007.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial007_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial007.py!}
|
||||
```
|
||||
|
||||
This means:
|
||||
|
||||
* The variable `items_t` is a `tuple` with 3 items, an `int`, another `int`, and a `str`.
|
||||
@@ -243,18 +249,18 @@ The first type parameter is for the keys of the `dict`.
|
||||
|
||||
The second type parameter is for the values of the `dict`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial008.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial008_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial008.py!}
|
||||
```
|
||||
|
||||
This means:
|
||||
|
||||
* The variable `prices` is a `dict`:
|
||||
@@ -267,20 +273,20 @@ You can declare that a variable can be any of **several types**, for example, an
|
||||
|
||||
In Python 3.6 and above (including Python 3.10) you can use the `Union` type from `typing` and put inside the square brackets the possible types to accept.
|
||||
|
||||
In Python 3.10 there's also an **alternative syntax** where you can put the possible types separated by a <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr>.
|
||||
In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr>.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial008b.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial008b_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial008b.py!}
|
||||
```
|
||||
|
||||
In both cases this means that `item` could be an `int` or a `str`.
|
||||
|
||||
#### Possibly `None`
|
||||
@@ -299,24 +305,24 @@ Using `Optional[str]` instead of just `str` will let the editor help you detecti
|
||||
|
||||
This also means that in Python 3.10, you can use `Something | None`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial009_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial009.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 and above - alternative"
|
||||
=== "Python 3.6+ alternative"
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial009b.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/python_types/tutorial009_py310.py!}
|
||||
```
|
||||
|
||||
#### Using `Union` or `Optional`
|
||||
|
||||
If you are using a Python version below 3.10, here's a tip from my very **subjective** point of view:
|
||||
@@ -360,32 +366,7 @@ And then you won't have to worry about names like `Optional` and `Union`. 😎
|
||||
|
||||
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
* `List`
|
||||
* `Tuple`
|
||||
* `Set`
|
||||
* `Dict`
|
||||
* `Union`
|
||||
* `Optional`
|
||||
* ...and others.
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
|
||||
You can use the same builtin types as generics (with square brackets and types inside):
|
||||
|
||||
* `list`
|
||||
* `tuple`
|
||||
* `set`
|
||||
* `dict`
|
||||
|
||||
And the same as with Python 3.6, from the `typing` module:
|
||||
|
||||
* `Union`
|
||||
* `Optional`
|
||||
* ...and others.
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
You can use the same builtin types as generics (with square brackets and types inside):
|
||||
|
||||
@@ -400,7 +381,32 @@ These types that take type parameters in square brackets are called **Generic ty
|
||||
* `Optional` (the same as with Python 3.6)
|
||||
* ...and others.
|
||||
|
||||
In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr> to declare unions of types.
|
||||
In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the <abbr title='also called "bitwise or operator", but that meaning is not relevant here'>vertical bar (`|`)</abbr> to declare unions of types, that's a lot better and simpler.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
You can use the same builtin types as generics (with square brackets and types inside):
|
||||
|
||||
* `list`
|
||||
* `tuple`
|
||||
* `set`
|
||||
* `dict`
|
||||
|
||||
And the same as with Python 3.6, from the `typing` module:
|
||||
|
||||
* `Union`
|
||||
* `Optional`
|
||||
* ...and others.
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
* `List`
|
||||
* `Tuple`
|
||||
* `Set`
|
||||
* `Dict`
|
||||
* `Union`
|
||||
* `Optional`
|
||||
* ...and others.
|
||||
|
||||
### Classes as types
|
||||
|
||||
@@ -422,6 +428,10 @@ And then, again, you get all the editor support:
|
||||
|
||||
<img src="/img/python-types/image06.png">
|
||||
|
||||
Notice that this means "`one_person` is an **instance** of the class `Person`".
|
||||
|
||||
It doesn't mean "`one_person` is the **class** called `Person`".
|
||||
|
||||
## Pydantic models
|
||||
|
||||
<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> is a Python library to perform data validation.
|
||||
@@ -436,22 +446,22 @@ And you get all the editor support with that resulting object.
|
||||
|
||||
An example from the official Pydantic docs:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/python_types/tutorial011.py!}
|
||||
{!> ../../../docs_src/python_types/tutorial011_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/python_types/tutorial011_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/python_types/tutorial011_py310.py!}
|
||||
{!> ../../../docs_src/python_types/tutorial011.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
@@ -464,6 +474,43 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t
|
||||
!!! tip
|
||||
Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
|
||||
|
||||
## Type Hints with Metadata Annotations
|
||||
|
||||
Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial013_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
|
||||
|
||||
It will already be installed with **FastAPI**.
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!> ../../../docs_src/python_types/tutorial013.py!}
|
||||
```
|
||||
|
||||
Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.
|
||||
|
||||
But you can use this space in `Annotated` to provide **FastAPI** with additional metadata about how you want your application to behave.
|
||||
|
||||
The important thing to remember is that **the first *type parameter*** you pass to `Annotated` is the **actual type**. The rest, is just metadata for other tools.
|
||||
|
||||
For now, you just need to know that `Annotated` exists, and that it's standard Python. 😎
|
||||
|
||||
Later you will see how **powerful** it can be.
|
||||
|
||||
!!! tip
|
||||
The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
|
||||
|
||||
And also that your code will be very compatible with many other Python tools and libraries. 🚀
|
||||
|
||||
## Type hints in **FastAPI**
|
||||
|
||||
**FastAPI** takes advantage of these type hints to do several things.
|
||||
|
||||
@@ -3,6 +3,121 @@
|
||||
## Latest Changes
|
||||
|
||||
|
||||
## 0.95.0
|
||||
|
||||
### Highlights
|
||||
|
||||
This release adds support for dependencies and parameters using `Annotated` and recommends its usage. ✨
|
||||
|
||||
This has **several benefits**, one of the main ones is that now the parameters of your functions with `Annotated` would **not be affected** at all.
|
||||
|
||||
If you call those functions in **other places in your code**, the actual **default values** will be kept, your editor will help you notice missing **required arguments**, Python will require you to pass required arguments at **runtime**, you will be able to **use the same functions** for different things and with different libraries (e.g. **Typer** will soon support `Annotated` too, then you could use the same function for an API and a CLI), etc.
|
||||
|
||||
Because `Annotated` is **standard Python**, you still get all the **benefits** from editors and tools, like **autocompletion**, **inline errors**, etc.
|
||||
|
||||
One of the **biggest benefits** is that now you can create `Annotated` dependencies that are then shared by multiple *path operation functions*, this will allow you to **reduce** a lot of **code duplication** in your codebase, while keeping all the support from editors and tools.
|
||||
|
||||
For example, you could have code like this:
|
||||
|
||||
```Python
|
||||
def get_current_user(token: str):
|
||||
# authenticate user
|
||||
return User()
|
||||
|
||||
|
||||
@app.get("/items/")
|
||||
def read_items(user: User = Depends(get_current_user)):
|
||||
...
|
||||
|
||||
|
||||
@app.post("/items/")
|
||||
def create_item(*, user: User = Depends(get_current_user), item: Item):
|
||||
...
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
def read_item(*, user: User = Depends(get_current_user), item_id: int):
|
||||
...
|
||||
|
||||
|
||||
@app.delete("/items/{item_id}")
|
||||
def delete_item(*, user: User = Depends(get_current_user), item_id: int):
|
||||
...
|
||||
```
|
||||
|
||||
There's a bit of code duplication for the dependency:
|
||||
|
||||
```Python
|
||||
user: User = Depends(get_current_user)
|
||||
```
|
||||
|
||||
...the bigger the codebase, the more noticeable it is.
|
||||
|
||||
Now you can create an annotated dependency once, like this:
|
||||
|
||||
```Python
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
```
|
||||
|
||||
And then you can reuse this `Annotated` dependency:
|
||||
|
||||
```Python
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
|
||||
|
||||
@app.get("/items/")
|
||||
def read_items(user: CurrentUser):
|
||||
...
|
||||
|
||||
|
||||
@app.post("/items/")
|
||||
def create_item(user: CurrentUser, item: Item):
|
||||
...
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
def read_item(user: CurrentUser, item_id: int):
|
||||
...
|
||||
|
||||
|
||||
@app.delete("/items/{item_id}")
|
||||
def delete_item(user: CurrentUser, item_id: int):
|
||||
...
|
||||
```
|
||||
|
||||
...and `CurrentUser` has all the typing information as `User`, so your editor will work as expected (autocompletion and everything), and **FastAPI** will be able to understand the dependency defined in `Annotated`. 😎
|
||||
|
||||
Roughly **all the docs** have been rewritten to use `Annotated` as the main way to declare **parameters** and **dependencies**. All the **examples** in the docs now include a version with `Annotated` and a version without it, for each of the specific Python versions (when there are small differences/improvements in more recent versions). There were around 23K new lines added between docs, examples, and tests. 🚀
|
||||
|
||||
The key updated docs are:
|
||||
|
||||
* Python Types Intro:
|
||||
* [Type Hints with Metadata Annotations](https://fastapi.tiangolo.com/python-types/#type-hints-with-metadata-annotations).
|
||||
* Tutorial:
|
||||
* [Query Parameters and String Validations - Additional validation](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#additional-validation)
|
||||
* [Advantages of `Annotated`](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#advantages-of-annotated)
|
||||
* [Path Parameters and Numeric Validations - Order the parameters as you need, tricks](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#order-the-parameters-as-you-need-tricks)
|
||||
* [Better with `Annotated`](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#better-with-annotated)
|
||||
* [Dependencies - First Steps - Share `Annotated` dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/#share-annotated-dependencies)
|
||||
|
||||
Special thanks to [@nzig](https://github.com/nzig) for the core implementation and to [@adriangb](https://github.com/adriangb) for the inspiration and idea with [Xpresso](https://github.com/adriangb/xpresso)! 🚀
|
||||
|
||||
### Features
|
||||
|
||||
* ✨Add support for PEP-593 `Annotated` for specifying dependencies and parameters. PR [#4871](https://github.com/tiangolo/fastapi/pull/4871) by [@nzig](https://github.com/nzig).
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Tweak tip recommending `Annotated` in docs. PR [#9270](https://github.com/tiangolo/fastapi/pull/9270) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update order of examples, latest Python version first, and simplify version tab names. PR [#9269](https://github.com/tiangolo/fastapi/pull/9269) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update all docs to use `Annotated` as the main recommendation, with new examples and tests. PR [#9268](https://github.com/tiangolo/fastapi/pull/9268) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.94.1
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🎨 Fix types for lifespan, upgrade Starlette to 0.26.1. PR [#9245](https://github.com/tiangolo/fastapi/pull/9245) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.94.0
|
||||
|
||||
### Upgrades
|
||||
|
||||
@@ -57,18 +57,42 @@ Using `BackgroundTasks` also works with the dependency injection system, you can
|
||||
|
||||
**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002.py!}
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="14 16 23 26"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11 13 20 23"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002.py!}
|
||||
```
|
||||
|
||||
In this example, the messages will be written to the `log.txt` file *after* the response is sent.
|
||||
|
||||
If there was a query in the request, it will be written to the log in a background task.
|
||||
|
||||
@@ -112,9 +112,26 @@ So we put them in their own `dependencies` module (`app/dependencies.py`).
|
||||
|
||||
We will now use a simple dependency to read a custom `X-Token` header:
|
||||
|
||||
```Python hl_lines="1 4-6"
|
||||
{!../../../docs_src/bigger_applications/app/dependencies.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3 6-8"
|
||||
{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 5-7"
|
||||
{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 4-6"
|
||||
{!> ../../../docs_src/bigger_applications/app/dependencies.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
We are using an invented header to simplify this example.
|
||||
|
||||
@@ -6,18 +6,42 @@ The same way you can declare additional validation and metadata in *path operati
|
||||
|
||||
First, you have to import it:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning
|
||||
Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).
|
||||
|
||||
@@ -25,18 +49,42 @@ First, you have to import it:
|
||||
|
||||
You can then use `Field` with model attributes:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="11-14"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11-14"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12-15"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9-12"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11-14"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.
|
||||
|
||||
!!! note "Technical Details"
|
||||
|
||||
@@ -8,18 +8,42 @@ First, of course, you can mix `Path`, `Query` and request body parameter declara
|
||||
|
||||
And you can also declare body parameters as optional, by setting the default to `None`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19-21"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
|
||||
```Python hl_lines="18-20"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18-20"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="19-21"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17-19"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="19-21"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note
|
||||
Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.
|
||||
|
||||
@@ -38,18 +62,18 @@ In the previous example, the *path operations* would expect a JSON body with the
|
||||
|
||||
But you can also declare multiple body parameters, e.g. `item` and `user`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
In this case, **FastAPI** will notice that there are more than one body parameters in the function (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:
|
||||
@@ -87,18 +111,42 @@ If you declare it as is, because it is a singular value, **FastAPI** will assume
|
||||
|
||||
But you can instruct **FastAPI** to treat it as another body key using `Body`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
|
||||
```Python hl_lines="23"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="23"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
In this case, **FastAPI** will expect a body like:
|
||||
|
||||
```JSON
|
||||
@@ -137,18 +185,42 @@ q: str | None = None
|
||||
|
||||
For example:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="27"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="27"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="28"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="25"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="27"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
|
||||
```Python hl_lines="26"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
|
||||
|
||||
@@ -166,18 +238,42 @@ item: Item = Body(embed=True)
|
||||
|
||||
as in:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
|
||||
```
|
||||
|
||||
In this case **FastAPI** will expect a body like:
|
||||
|
||||
```JSON hl_lines="2"
|
||||
|
||||
@@ -6,18 +6,18 @@ With **FastAPI**, you can define, validate, document, and use arbitrarily deeply
|
||||
|
||||
You can define an attribute to be a subtype. For example, a Python `list`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
This will make `tags` be a list, although it doesn't declare the type of the elements of the list.
|
||||
|
||||
## List fields with type parameter
|
||||
@@ -61,22 +61,22 @@ 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":
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial002.py!}
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
## Set types
|
||||
@@ -87,22 +87,22 @@ And Python has a special data type for sets of unique items, the `set`.
|
||||
|
||||
Then we can declare `tags` as a set of strings:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1 14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial003.py!}
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
|
||||
```Python hl_lines="1 14"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial003.py!}
|
||||
```
|
||||
|
||||
With this, even if you receive a request with duplicate data, it will be converted to a set of unique items.
|
||||
@@ -125,44 +125,44 @@ All that, arbitrarily nested.
|
||||
|
||||
For example, we can define an `Image` model:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9-11"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004.py!}
|
||||
```Python hl_lines="7-9"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9-11"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="7-9"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
|
||||
```Python hl_lines="9-11"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
### Use the submodel as a type
|
||||
|
||||
And then we can use it as the type of an attribute:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004.py!}
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
This would mean that **FastAPI** would expect a body similar to:
|
||||
@@ -196,22 +196,22 @@ To see all the options you have, checkout the docs for <a href="https://pydantic
|
||||
|
||||
For example, as in the `Image` model we have a `url` field, we can declare it to be instead of a `str`, a Pydantic's `HttpUrl`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 10"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial005.py!}
|
||||
```Python hl_lines="2 8"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 10"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="2 8"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
|
||||
```Python hl_lines="4 10"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial005.py!}
|
||||
```
|
||||
|
||||
The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such.
|
||||
@@ -220,22 +220,22 @@ The string will be checked to be a valid URL, and documented in JSON Schema / Op
|
||||
|
||||
You can also use Pydantic models as subtypes of `list`, `set`, etc:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial006.py!}
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial006.py!}
|
||||
```
|
||||
|
||||
This will expect (convert, validate, document, etc) a JSON body like:
|
||||
@@ -271,22 +271,22 @@ This will expect (convert, validate, document, etc) a JSON body like:
|
||||
|
||||
You can define arbitrarily deeply nested models:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9 14 20 23 27"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial007.py!}
|
||||
```Python hl_lines="7 12 18 21 25"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9 14 20 23 27"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="7 12 18 21 25"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
|
||||
```Python hl_lines="9 14 20 23 27"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial007.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
@@ -308,18 +308,18 @@ images: list[Image]
|
||||
|
||||
as in:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial008.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial008.py!}
|
||||
```
|
||||
|
||||
## Editor support everywhere
|
||||
|
||||
And you get editor support everywhere.
|
||||
@@ -348,18 +348,18 @@ 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:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial009.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/body_nested_models/tutorial009.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Have in mind that JSON only supports `str` as keys.
|
||||
|
||||
|
||||
@@ -6,22 +6,22 @@ To update an item you can use the <a href="https://developer.mozilla.org/en-US/d
|
||||
|
||||
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`.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="30-35"
|
||||
{!> ../../../docs_src/body_updates/tutorial001.py!}
|
||||
```Python hl_lines="28-33"
|
||||
{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="30-35"
|
||||
{!> ../../../docs_src/body_updates/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="28-33"
|
||||
{!> ../../../docs_src/body_updates/tutorial001_py310.py!}
|
||||
```Python hl_lines="30-35"
|
||||
{!> ../../../docs_src/body_updates/tutorial001.py!}
|
||||
```
|
||||
|
||||
`PUT` is used to receive data that should replace the existing data.
|
||||
@@ -67,22 +67,22 @@ That would generate a `dict` with only the data that was set when creating the `
|
||||
|
||||
Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="34"
|
||||
{!> ../../../docs_src/body_updates/tutorial002.py!}
|
||||
```Python hl_lines="32"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="34"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="32"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
|
||||
```Python hl_lines="34"
|
||||
{!> ../../../docs_src/body_updates/tutorial002.py!}
|
||||
```
|
||||
|
||||
### Using Pydantic's `update` parameter
|
||||
@@ -91,22 +91,22 @@ Now, you can create a copy of the existing model using `.copy()`, and pass the `
|
||||
|
||||
Like `stored_item_model.copy(update=update_data)`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="35"
|
||||
{!> ../../../docs_src/body_updates/tutorial002.py!}
|
||||
```Python hl_lines="33"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="35"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="33"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
|
||||
```Python hl_lines="35"
|
||||
{!> ../../../docs_src/body_updates/tutorial002.py!}
|
||||
```
|
||||
|
||||
### Partial updates recap
|
||||
@@ -124,22 +124,22 @@ In summary, to apply partial updates you would:
|
||||
* Save the data to your DB.
|
||||
* Return the updated model.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="30-37"
|
||||
{!> ../../../docs_src/body_updates/tutorial002.py!}
|
||||
```Python hl_lines="28-35"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="30-37"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="28-35"
|
||||
{!> ../../../docs_src/body_updates/tutorial002_py310.py!}
|
||||
```Python hl_lines="30-37"
|
||||
{!> ../../../docs_src/body_updates/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
|
||||
@@ -19,36 +19,36 @@ To declare a **request** body, you use <a href="https://pydantic-docs.helpmanual
|
||||
|
||||
First, you need to import `BaseModel` from `pydantic`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="2"
|
||||
{!> ../../../docs_src/body/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body/tutorial001.py!}
|
||||
```
|
||||
|
||||
## 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:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="7-11"
|
||||
{!> ../../../docs_src/body/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="5-9"
|
||||
{!> ../../../docs_src/body/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="7-11"
|
||||
{!> ../../../docs_src/body/tutorial001.py!}
|
||||
```
|
||||
|
||||
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:
|
||||
@@ -75,18 +75,18 @@ For example, this model above declares a JSON "`object`" (or Python `dict`) like
|
||||
|
||||
To add it to your *path operation*, declare it the same way you declared path and query parameters:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/body/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body/tutorial001.py!}
|
||||
```
|
||||
|
||||
...and declare its type as the model you created, `Item`.
|
||||
|
||||
## Results
|
||||
@@ -149,54 +149,54 @@ But you would get the same editor support with <a href="https://www.jetbrains.co
|
||||
|
||||
Inside of the function, you can access all the attributes of the model object directly:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!> ../../../docs_src/body/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/body/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!> ../../../docs_src/body/tutorial002.py!}
|
||||
```
|
||||
|
||||
## 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**.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="17-18"
|
||||
{!> ../../../docs_src/body/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="15-16"
|
||||
{!> ../../../docs_src/body/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="17-18"
|
||||
{!> ../../../docs_src/body/tutorial003.py!}
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/body/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/body/tutorial004.py!}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
@@ -6,36 +6,84 @@ You can define Cookie parameters the same way you define `Query` and `Path` para
|
||||
|
||||
First import `Cookie`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Declare `Cookie` parameters
|
||||
|
||||
Then declare the cookie parameters using the same structure as with `Path` and `Query`.
|
||||
|
||||
The first value is the default value, you can pass all the extra validation or annotation parameters:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "Technical Details"
|
||||
`Cookie` is a "sister" class of `Path` and `Query`. It also inherits from the same common `Param` class.
|
||||
|
||||
|
||||
@@ -6,18 +6,42 @@ Before diving deeper into the **Dependency Injection** system, let's upgrade the
|
||||
|
||||
In the previous example, we were returning a `dict` from our dependency ("dependable"):
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -79,46 +103,118 @@ That also applies to callables with no parameters at all. The same as it would b
|
||||
|
||||
Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12-16"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9-13"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
Pay attention to the `__init__` method used to create the instance of the class:
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="12"
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
Pay attention to the `__init__` method used to create the instance of the class:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
...it has the same parameters as our previous `common_parameters`:
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
...it has the same parameters as our previous `common_parameters`:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
Those parameters are what **FastAPI** will use to "solve" the dependency.
|
||||
|
||||
In both cases, it will have:
|
||||
@@ -133,32 +229,67 @@ In both cases the data will be converted, validated, documented on the OpenAPI s
|
||||
|
||||
Now you can declare your dependency using this class.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
**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.
|
||||
|
||||
## Type annotation vs `Depends`
|
||||
|
||||
Notice how we write `CommonQueryParams` twice in the above code:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
|
||||
```
|
||||
|
||||
The last `CommonQueryParams`, in:
|
||||
|
||||
```Python
|
||||
... = Depends(CommonQueryParams)
|
||||
... Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
...is what **FastAPI** will actually use to know what is the dependency.
|
||||
@@ -169,32 +300,78 @@ From it is that FastAPI will extract the declared parameters and that is what Fa
|
||||
|
||||
In this case, the first `CommonQueryParams`, in:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams ...
|
||||
```
|
||||
=== "Python 3.6+"
|
||||
|
||||
...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).
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, ...
|
||||
```
|
||||
|
||||
=== "Python 3.6+ 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:
|
||||
|
||||
```Python
|
||||
commons = Depends(CommonQueryParams)
|
||||
```
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[Any, Depends(CommonQueryParams)]
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python
|
||||
commons = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
..as in:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003.py!}
|
||||
```
|
||||
|
||||
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">
|
||||
@@ -203,9 +380,20 @@ But declaring the type is encouraged as that way your editor will know what will
|
||||
|
||||
But you see that we are having some code repetition here, writing `CommonQueryParams` twice:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[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.
|
||||
|
||||
@@ -213,32 +401,78 @@ For those specific cases, you can do the following:
|
||||
|
||||
Instead of writing:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
...you write:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends()
|
||||
```
|
||||
=== "Python 3.6+"
|
||||
|
||||
You declare the dependency as the type of the parameter, and you use `Depends()` as its "default" value (that after the `=`) for that function's parameter, without any parameter in `Depends()`, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.
|
||||
```Python
|
||||
commons: Annotated[CommonQueryParams, Depends()]
|
||||
```
|
||||
|
||||
=== "Python 3.6 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:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004.py!}
|
||||
```
|
||||
|
||||
...and **FastAPI** will know what to do.
|
||||
|
||||
!!! tip
|
||||
|
||||
@@ -14,9 +14,26 @@ The *path operation decorator* receives an optional argument `dependencies`.
|
||||
|
||||
It should be a `list` of `Depends()`:
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
These dependencies will be executed/solved the same way normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.
|
||||
|
||||
@@ -40,17 +57,51 @@ You can use the same dependency *functions* you use normally.
|
||||
|
||||
They can declare request requirements (like headers) or other sub-dependencies:
|
||||
|
||||
```Python hl_lines="6 11"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="7 12"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6 11"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
### Raise exceptions
|
||||
|
||||
These dependencies can `raise` exceptions, the same as normal dependencies:
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
### Return values
|
||||
|
||||
@@ -58,9 +109,26 @@ And they can return values or not, the values won't be used.
|
||||
|
||||
So, you can re-use 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:
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11 16"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/dependencies/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
{!> ../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
## Dependencies for a group of *path operations*
|
||||
|
||||
|
||||
@@ -66,9 +66,26 @@ You can have sub-dependencies and "trees" of sub-dependencies of any size and sh
|
||||
|
||||
For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`:
|
||||
|
||||
```Python hl_lines="4 12 20"
|
||||
{!../../../docs_src/dependencies/tutorial008.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6 14 22"
|
||||
{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="5 13 21"
|
||||
{!> ../../../docs_src/dependencies/tutorial008_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 12 20"
|
||||
{!> ../../../docs_src/dependencies/tutorial008.py!}
|
||||
```
|
||||
|
||||
And all of them can use `yield`.
|
||||
|
||||
@@ -76,9 +93,26 @@ In this case `dependency_c`, to execute its exit code, needs the value from `dep
|
||||
|
||||
And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.
|
||||
|
||||
```Python hl_lines="16-17 24-25"
|
||||
{!../../../docs_src/dependencies/tutorial008.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18-19 26-27"
|
||||
{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="17-18 25-26"
|
||||
{!> ../../../docs_src/dependencies/tutorial008_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="16-17 24-25"
|
||||
{!> ../../../docs_src/dependencies/tutorial008.py!}
|
||||
```
|
||||
|
||||
The same way, you could have dependencies with `yield` and `return` mixed.
|
||||
|
||||
|
||||
@@ -6,9 +6,26 @@ Similar to the way you can [add `dependencies` to the *path operation decorators
|
||||
|
||||
In that case, they will be applied to all the *path operations* in the application:
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!../../../docs_src/dependencies/tutorial012.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/dependencies/tutorial012_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!> ../../../docs_src/dependencies/tutorial012.py!}
|
||||
```
|
||||
|
||||
And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app.
|
||||
|
||||
|
||||
@@ -31,18 +31,42 @@ 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:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8-11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```Python hl_lines="8-9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8-11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9-12"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6-7"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8-11"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
That's it.
|
||||
|
||||
**2 lines**.
|
||||
@@ -63,40 +87,90 @@ And then it just returns a `dict` containing those values.
|
||||
|
||||
### Import `Depends`
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="15 20"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```Python hl_lines="13 18"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="15 20"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="16 21"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11 16"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="15 20"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
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
|
||||
@@ -126,6 +200,45 @@ This way you write shared code once and **FastAPI** takes care of calling it for
|
||||
|
||||
You just pass it to `Depends` and **FastAPI** knows how to do the rest.
|
||||
|
||||
## 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:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="12 16 21"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="14 18 23"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="15 19 24"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
|
||||
```
|
||||
|
||||
!!! 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***.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -10,18 +10,42 @@ They can be as **deep** as you need them to be.
|
||||
|
||||
You could create a first dependency ("dependable") like:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8-9"
|
||||
{!> ../../../docs_src/dependencies/tutorial005.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8-9"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6-7"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8-9"
|
||||
{!> ../../../docs_src/dependencies/tutorial005.py!}
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -30,18 +54,42 @@ This is quite simple (not very useful), but will help us focus on how the sub-de
|
||||
|
||||
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):
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/dependencies/tutorial005.py!}
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/dependencies/tutorial005.py!}
|
||||
```
|
||||
|
||||
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).
|
||||
@@ -53,18 +101,42 @@ Let's focus on the parameters declared:
|
||||
|
||||
Then we can use the dependency with:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/dependencies/tutorial005.py!}
|
||||
```Python hl_lines="23"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="23"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/dependencies/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.
|
||||
|
||||
@@ -89,10 +161,22 @@ And it will save the returned value in a <abbr title="A utility/system to store
|
||||
|
||||
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`:
|
||||
|
||||
```Python hl_lines="1"
|
||||
async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
|
||||
return {"fresh_value": fresh_value}
|
||||
```
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
|
||||
return {"fresh_value": fresh_value}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ 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}
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@@ -20,18 +20,18 @@ You can use `jsonable_encoder` for that.
|
||||
|
||||
It receives an object, like a Pydantic model, and returns a JSON compatible version:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="5 22"
|
||||
{!> ../../../docs_src/encoder/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 21"
|
||||
{!> ../../../docs_src/encoder/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="5 22"
|
||||
{!> ../../../docs_src/encoder/tutorial001.py!}
|
||||
```
|
||||
|
||||
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 <a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a>.
|
||||
|
||||
@@ -55,28 +55,76 @@ Here are some of the additional data types you can use:
|
||||
|
||||
Here's an example *path operation* with parameters using some of the above types.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1 3 12-16"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001.py!}
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1 3 12-16"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 3 13-17"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 2 11-15"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like:
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
```Python hl_lines="1 2 12-16"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="19-20"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17-18"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/extra_data_types/tutorial001.py!}
|
||||
```
|
||||
|
||||
@@ -17,18 +17,18 @@ This is especially the case for user models, because:
|
||||
|
||||
Here's a general idea of how the models could look like with their password fields and the places where they are used:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
|
||||
{!> ../../../docs_src/extra_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
|
||||
{!> ../../../docs_src/extra_models/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
|
||||
{!> ../../../docs_src/extra_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
### About `**user_in.dict()`
|
||||
|
||||
#### Pydantic's `.dict()`
|
||||
@@ -158,18 +158,18 @@ All the data conversion, validation, documentation, etc. will still work as norm
|
||||
|
||||
That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password):
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9 15-16 19-20 23-24"
|
||||
{!> ../../../docs_src/extra_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7 13-14 17-18 21-22"
|
||||
{!> ../../../docs_src/extra_models/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9 15-16 19-20 23-24"
|
||||
{!> ../../../docs_src/extra_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
## `Union` or `anyOf`
|
||||
|
||||
You can declare a response to be the `Union` of two types, that means, that the response would be any of the two.
|
||||
@@ -181,18 +181,18 @@ To do that, use the standard Python type hint <a href="https://docs.python.org/3
|
||||
!!! note
|
||||
When defining a <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a>, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="1 14-15 18-20 33"
|
||||
{!> ../../../docs_src/extra_models/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1 14-15 18-20 33"
|
||||
{!> ../../../docs_src/extra_models/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 14-15 18-20 33"
|
||||
{!> ../../../docs_src/extra_models/tutorial003.py!}
|
||||
```
|
||||
|
||||
### `Union` in Python 3.10
|
||||
|
||||
In this example we pass `Union[PlaneItem, CarItem]` as the value of the argument `response_model`.
|
||||
@@ -213,18 +213,18 @@ The same way, you can declare responses of lists of objects.
|
||||
|
||||
For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above):
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="1 20"
|
||||
{!> ../../../docs_src/extra_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/extra_models/tutorial004_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 20"
|
||||
{!> ../../../docs_src/extra_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Response with arbitrary `dict`
|
||||
|
||||
You can also declare a response using a plain arbitrary `dict`, declaring just the type of the keys and values, without using a Pydantic model.
|
||||
@@ -233,18 +233,18 @@ This is useful if you don't know the valid field/attribute names (that would be
|
||||
|
||||
In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above):
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="1 8"
|
||||
{!> ../../../docs_src/extra_models/tutorial005.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!> ../../../docs_src/extra_models/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 8"
|
||||
{!> ../../../docs_src/extra_models/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
Use multiple Pydantic models and inherit freely for each case.
|
||||
|
||||
@@ -6,36 +6,84 @@ You can define Header parameters the same way you define `Query`, `Path` and `Co
|
||||
|
||||
First import `Header`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/header_params/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/header_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Declare `Header` parameters
|
||||
|
||||
Then declare the header parameters using the same structure as with `Path`, `Query` and `Cookie`.
|
||||
|
||||
The first value is the default value, you can pass all the extra validation or annotation parameters:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
{!> ../../../docs_src/header_params/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/header_params/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/header_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "Technical Details"
|
||||
`Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class.
|
||||
|
||||
@@ -60,18 +108,42 @@ So, you can use `user_agent` as you normally would in Python code, instead of ne
|
||||
|
||||
If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/header_params/tutorial002.py!}
|
||||
{!> ../../../docs_src/header_params/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/header_params/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/header_params/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/header_params/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/header_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! warning
|
||||
Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.
|
||||
|
||||
@@ -85,22 +157,49 @@ You will receive all the values from the duplicate header as a Python `list`.
|
||||
|
||||
For example, to declare a header of `X-Token` that can appear more than once, you can write:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial003.py!}
|
||||
{!> ../../../docs_src/header_params/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/header_params/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/header_params/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/header_params/tutorial003_py310.py!}
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
If you communicate with that *path operation* sending two HTTP headers like:
|
||||
|
||||
@@ -13,22 +13,22 @@ You can pass directly the `int` code, like `404`.
|
||||
|
||||
But if you don't remember what each number code is for, you can use the shortcut constants in `status`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3 17"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
|
||||
```Python hl_lines="1 15"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3 17"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 15"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
|
||||
```Python hl_lines="3 17"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
|
||||
```
|
||||
|
||||
That status code will be used in the response and will be added to the OpenAPI schema.
|
||||
@@ -42,22 +42,22 @@ That status code will be used in the response and will be added to the OpenAPI s
|
||||
|
||||
You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`):
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="17 22 27"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
|
||||
```Python hl_lines="15 20 25"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="17 22 27"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="15 20 25"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
|
||||
```Python hl_lines="17 22 27"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
|
||||
```
|
||||
|
||||
They will be added to the OpenAPI schema and used by the automatic documentation interfaces:
|
||||
@@ -80,22 +80,22 @@ In these cases, it could make sense to store the tags in an `Enum`.
|
||||
|
||||
You can add a `summary` and `description`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="20-21"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="20-21"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
|
||||
```Python hl_lines="20-21"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
|
||||
```
|
||||
|
||||
## Description from docstring
|
||||
@@ -104,22 +104,22 @@ As descriptions tend to be long and cover multiple lines, you can declare the *p
|
||||
|
||||
You can write <a href="https://en.wikipedia.org/wiki/Markdown" class="external-link" target="_blank">Markdown</a> in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19-27"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
|
||||
```Python hl_lines="17-25"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19-27"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="17-25"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
|
||||
```Python hl_lines="19-27"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
|
||||
```
|
||||
|
||||
It will be used in the interactive docs:
|
||||
@@ -130,22 +130,22 @@ It will be used in the interactive docs:
|
||||
|
||||
You can specify the response description with the parameter `response_description`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
|
||||
```Python hl_lines="21"
|
||||
{!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
|
||||
@@ -4,38 +4,86 @@ In the same way that you can declare more validations and metadata for query par
|
||||
|
||||
## Import Path
|
||||
|
||||
First, import `Path` from `fastapi`:
|
||||
First, import `Path` from `fastapi`, and import `Annotated`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```Python hl_lines="1 3"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="1 3"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3-4"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Declare metadata
|
||||
|
||||
You can declare all the same parameters as for `Query`.
|
||||
|
||||
For example, to declare a `title` metadata value for the path parameter `item_id` you can type:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note
|
||||
A path parameter is always required as it has to be part of the path.
|
||||
|
||||
@@ -45,11 +93,14 @@ For example, to declare a `title` metadata value for the path parameter `item_id
|
||||
|
||||
## Order the parameters as you need
|
||||
|
||||
!!! tip
|
||||
This is probably not as important or necessary if you use `Annotated`.
|
||||
|
||||
Let's say that you want to declare the query parameter `q` as a required `str`.
|
||||
|
||||
And you don't need to declare anything else for that parameter, so you don't really need to use `Query`.
|
||||
|
||||
But you still need to use `Path` for the `item_id` path parameter.
|
||||
But you still need to use `Path` for the `item_id` path parameter. And you don't want to use `Annotated` for some reason.
|
||||
|
||||
Python will complain if you put a value with a "default" before a value that doesn't have a "default".
|
||||
|
||||
@@ -59,13 +110,44 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
|
||||
|
||||
So, you can declare your function as:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
|
||||
```
|
||||
=== "Python 3.6 non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
|
||||
```
|
||||
|
||||
But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
## Order the parameters as you need, tricks
|
||||
|
||||
If you want to declare the `q` query parameter without a `Query` nor any default value, and the path parameter `item_id` using `Path`, and have them in a different order, Python has a little special syntax for that.
|
||||
!!! tip
|
||||
This is probably not as important or necessary if you use `Annotated`.
|
||||
|
||||
Here's a **small trick** that can be handy, but you won't need it often.
|
||||
|
||||
If you want to:
|
||||
|
||||
* declare the `q` query parameter without a `Query` nor any default value
|
||||
* declare the path parameter `item_id` using `Path`
|
||||
* have them in a different order
|
||||
* not use `Annotated`
|
||||
|
||||
...Python has a little special syntax for that.
|
||||
|
||||
Pass `*`, as the first parameter of the function.
|
||||
|
||||
@@ -75,15 +157,48 @@ Python won't do anything with that `*`, but it will know that all the following
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
|
||||
```
|
||||
|
||||
### Better with `Annotated`
|
||||
|
||||
Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and yo probably won't need to use `*`.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
## Number validations: greater than or equal
|
||||
|
||||
With `Query` and `Path` (and others you'll see later) you can declare number constraints.
|
||||
|
||||
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Number validations: greater than and less than or equal
|
||||
|
||||
@@ -92,9 +207,26 @@ The same applies for:
|
||||
* `gt`: `g`reater `t`han
|
||||
* `le`: `l`ess than or `e`qual
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
|
||||
```
|
||||
|
||||
## Number validations: floats, greater than and less than
|
||||
|
||||
@@ -106,9 +238,26 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
|
||||
|
||||
And the same for <abbr title="less than"><code>lt</code></abbr>.
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@@ -4,18 +4,18 @@
|
||||
|
||||
Let's take this application as example:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
|
||||
|
||||
!!! note
|
||||
@@ -27,39 +27,117 @@ The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python
|
||||
|
||||
We are going to enforce that even though `q` is optional, whenever it is provided, **its length doesn't exceed 50 characters**.
|
||||
|
||||
### Import `Query`
|
||||
### Import `Query` and `Annotated`
|
||||
|
||||
To achieve that, first import `Query` from `fastapi`:
|
||||
To achieve that, first import:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
* `Query` from `fastapi`
|
||||
* `Annotated` from `typing` (or from `typing_extensions` in Python below 3.9)
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
|
||||
=== "Python 3.10+"
|
||||
|
||||
In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`.
|
||||
|
||||
```Python hl_lines="1 3"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
|
||||
In versions of Python below Python 3.9 you import `Annotation` from `typing_extensions`.
|
||||
|
||||
It will already be installed with FastAPI.
|
||||
|
||||
```Python hl_lines="3-4"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
## Use `Query` as the default value
|
||||
## Use `Annotated` in the type for the `q` parameter
|
||||
|
||||
And now use it as the default value of your parameter, setting the parameter `max_length` to 50:
|
||||
Remember I told you before that `Annotated` can be used to add metadata to your parameters in the [Python Types Intro](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}?
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
Now it's the time to use it with FastAPI. 🚀
|
||||
|
||||
We had this type annotation:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python
|
||||
q: str | None = None
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
q: Union[str, None] = None
|
||||
```
|
||||
|
||||
What we will do is wrap that with `Annotated`, so it becomes:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python
|
||||
q: Annotated[str | None] = None
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
q: Annotated[Union[str, None]] = None
|
||||
```
|
||||
|
||||
Both of those versions mean the same thing, `q` is a parameter that can be a `str` or `None`, and by default, it is `None`.
|
||||
|
||||
Now let's jump to the fun stuff. 🎉
|
||||
|
||||
## Add `Query` to `Annotated` in the `q` parameter
|
||||
|
||||
Now that we have this `Annotated` where we can put more metadata, add `Query` to it, and set the parameter `max_length` to 50:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
Notice that the default value is still `None`, so the parameter is still optional.
|
||||
|
||||
But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to extract this value from the query parameters (this would have been the default anyway 🤷) and that we want to have **additional validation** for this value (that's why we do this, to get the additional validation). 😎
|
||||
|
||||
FastAPI wll now:
|
||||
|
||||
* **Validate** the data making sure that the max length is 50 characters
|
||||
* Show a **clear error** for the client when the data is not valid
|
||||
* **Document** the parameter in the OpenAPI schema *path operation* (so it will show up in the **automatic docs UI**)
|
||||
|
||||
## Alternative (old) `Query` as the default value
|
||||
|
||||
Previous versions of FastAPI (before <abbr title="before 2023-03">0.95.0</abbr>) required you to use `Query` as the default value of your parameter, instead of putting it in `Annotated`, there's a high chance that you will see code using it around, so I'll explain it to you.
|
||||
|
||||
!!! tip
|
||||
For new code and whenever possible, use `Annotated` as explained above. There are multiple advantages (explained below) and no disadvantages. 🍰
|
||||
|
||||
This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
As we have to replace the default value `None` in the function with `Query()`, we can now set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value.
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
|
||||
```
|
||||
|
||||
As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI).
|
||||
|
||||
So:
|
||||
|
||||
@@ -67,7 +145,7 @@ So:
|
||||
q: Union[str, None] = Query(default=None)
|
||||
```
|
||||
|
||||
...makes the parameter optional, the same as:
|
||||
...makes the parameter optional, with a default value of `None`, the same as:
|
||||
|
||||
```Python
|
||||
q: Union[str, None] = None
|
||||
@@ -79,7 +157,7 @@ And in Python 3.10 and above:
|
||||
q: str | None = Query(default=None)
|
||||
```
|
||||
|
||||
...makes the parameter optional, the same as:
|
||||
...makes the parameter optional, with a default value of `None`, the same as:
|
||||
|
||||
```Python
|
||||
q: str | None = None
|
||||
@@ -112,38 +190,124 @@ q: Union[str, None] = Query(default=None, max_length=50)
|
||||
|
||||
This will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema *path operation*.
|
||||
|
||||
### `Query` as the default value or in `Annotated`
|
||||
|
||||
Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
|
||||
|
||||
Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent.
|
||||
|
||||
For example, this is not allowed:
|
||||
|
||||
```Python
|
||||
q: Annotated[str Query(default="rick")] = "morty"
|
||||
```
|
||||
|
||||
...because it's not clear if the default value should be `"rick"` or `"morty"`.
|
||||
|
||||
So, you would use (preferably):
|
||||
|
||||
```Python
|
||||
q: Annotated[str, Query()] = "rick"
|
||||
```
|
||||
|
||||
...or in older code bases you will find:
|
||||
|
||||
```Python
|
||||
q: str = Query(default="rick")
|
||||
```
|
||||
|
||||
### Advantages of `Annotated`
|
||||
|
||||
**Using `Annotated` is recommended** instead of the default value in function parameters, it is **better** for multiple reasons. 🤓
|
||||
|
||||
The **default** value of the **function parameter** is the **actual default** value, that's more intuitive with Python in general. 😌
|
||||
|
||||
You could **call** that same function in **other places** without FastAPI, and it would **work as expected**. If there's a **required** parameter (without a default value), your **editor** will let you know with an error, **Python** will also complain if you run it without passing the required parameter.
|
||||
|
||||
When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other place**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out.
|
||||
|
||||
Because `Annotated` can have more than one metadata annotation, you could now even use the same function with other tools, like <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">Typer</a>. 🚀
|
||||
|
||||
## Add more validations
|
||||
|
||||
You can also add a parameter `min_length`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
|
||||
```
|
||||
|
||||
## Add regular expressions
|
||||
|
||||
You can define a <abbr title="A regular expression, regex or regexp is a sequence of characters that define a search pattern for strings.">regular expression</abbr> that the parameter should match:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
|
||||
```
|
||||
|
||||
This specific regular expression checks that the received parameter value:
|
||||
|
||||
* `^`: starts with the following characters, doesn't have characters before.
|
||||
@@ -156,16 +320,33 @@ But whenever you need them and go and learn them, know that you can already use
|
||||
|
||||
## Default values
|
||||
|
||||
The same way that you can pass `None` as the value for the `default` parameter, you can pass other values.
|
||||
You can, of course, use default values other than `None`.
|
||||
|
||||
Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/query_params_str_validations/tutorial005.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! note
|
||||
Having a default value also makes the parameter optional.
|
||||
Having a default value of any type, including `None`, makes the parameter optional (not required).
|
||||
|
||||
## Make it required
|
||||
|
||||
@@ -183,23 +364,70 @@ q: Union[str, None] = None
|
||||
|
||||
But we are now declaring it with `Query`, for example like:
|
||||
|
||||
```Python
|
||||
q: Union[str, None] = Query(default=None, min_length=3)
|
||||
```
|
||||
=== "Annotated"
|
||||
|
||||
```Python
|
||||
q: Annotated[Union[str, None], Query(min_length=3)] = None
|
||||
```
|
||||
|
||||
=== "non-Annotated"
|
||||
|
||||
```Python
|
||||
q: Union[str, None] = Query(default=None, min_length=3)
|
||||
```
|
||||
|
||||
So, when you need to declare a value as required while using `Query`, you can simply not declare a default value:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/query_params_str_validations/tutorial006.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`.
|
||||
|
||||
Still, probably better to use the `Annotated` version. 😉
|
||||
|
||||
### Required with Ellipsis (`...`)
|
||||
|
||||
There's an alternative way to explicitly declare that a value is required. You can set the `default` parameter to the literal value `...`:
|
||||
There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>.
|
||||
@@ -212,20 +440,44 @@ This will let **FastAPI** know that this parameter is required.
|
||||
|
||||
You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`.
|
||||
|
||||
To do that, you can declare that `None` is a valid type but still use `default=...`:
|
||||
To do that, you can declare that `None` is a valid type but still use `...` as the default:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
|
||||
|
||||
@@ -233,12 +485,29 @@ To do that, you can declare that `None` is a valid type but still use `default=.
|
||||
|
||||
If you feel uncomfortable using `...`, you can also import and use `Required` from Pydantic:
|
||||
|
||||
```Python hl_lines="2 8"
|
||||
{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="2 9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 8"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial006d.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Remember that in most of the cases, when something is required, you can simply omit the `default` parameter, so you normally don't have to use `...` nor `Required`.
|
||||
Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...` nor `Required`.
|
||||
|
||||
## Query parameter list / multiple values
|
||||
|
||||
@@ -246,22 +515,49 @@ When you define a query parameter explicitly with `Query` you can also declare i
|
||||
|
||||
For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
|
||||
```
|
||||
|
||||
Then, with a URL like:
|
||||
@@ -294,18 +590,36 @@ The interactive API docs will update accordingly, to allow multiple values:
|
||||
|
||||
And you can also define a default `list` of values if none are provided:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
|
||||
```
|
||||
|
||||
If you go to:
|
||||
|
||||
```
|
||||
@@ -327,9 +641,26 @@ the default of `q` will be: `["foo", "bar"]` and your response will be:
|
||||
|
||||
You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+):
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/query_params_str_validations/tutorial013.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
|
||||
```
|
||||
|
||||
!!! note
|
||||
Have in mind that in this case, FastAPI won't check the contents of the list.
|
||||
@@ -349,32 +680,80 @@ That information will be included in the generated OpenAPI and used by the docum
|
||||
|
||||
You can add a `title`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
|
||||
```
|
||||
|
||||
And a `description`:
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
And a `description`:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
|
||||
```
|
||||
|
||||
## Alias parameters
|
||||
|
||||
Imagine that you want the parameter to be `item-query`.
|
||||
@@ -393,18 +772,42 @@ But you still need it to be exactly `item-query`...
|
||||
|
||||
Then you can declare an `alias`, and that alias is what will be used to find the parameter value:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
|
||||
```
|
||||
|
||||
## Deprecating parameters
|
||||
|
||||
Now let's say you don't like this parameter anymore.
|
||||
@@ -413,18 +816,42 @@ You have to leave it there a while because there are clients using it, but you w
|
||||
|
||||
Then pass the parameter `deprecated=True` to `Query`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
|
||||
```
|
||||
|
||||
The docs will show it like this:
|
||||
|
||||
<img src="/img/tutorial/query-params-str-validations/image01.png">
|
||||
@@ -433,18 +860,42 @@ The docs will show it like this:
|
||||
|
||||
To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
You can declare additional validations and metadata for your parameters.
|
||||
|
||||
@@ -63,18 +63,18 @@ The parameter values in your function will be:
|
||||
|
||||
The same way, you can declare optional query parameters, by setting their default to `None`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
In this case, the function parameter `q` will be optional, and will be `None` by default.
|
||||
|
||||
!!! check
|
||||
@@ -84,18 +84,18 @@ In this case, the function parameter `q` will be optional, and will be `None` by
|
||||
|
||||
You can also declare `bool` types, and they will be converted:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
In this case, if you go to:
|
||||
|
||||
```
|
||||
@@ -137,18 +137,18 @@ And you don't have to declare them in any specific order.
|
||||
|
||||
They will be detected by name:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="8 10"
|
||||
{!> ../../../docs_src/query_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="6 8"
|
||||
{!> ../../../docs_src/query_params/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8 10"
|
||||
{!> ../../../docs_src/query_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Required query parameters
|
||||
|
||||
When you declare a default value for non-path parameters (for now, we have only seen query parameters), then it is not required.
|
||||
@@ -203,18 +203,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
|
||||
|
||||
And of course, you can define some parameters as required, some as having a default value, and some entirely optional:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params/tutorial006.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params/tutorial006_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params/tutorial006.py!}
|
||||
```
|
||||
|
||||
In this case, there are 3 query parameters:
|
||||
|
||||
* `needy`, a required `str`.
|
||||
|
||||
@@ -13,17 +13,51 @@ You can define files to be uploaded by the client using `File`.
|
||||
|
||||
Import `File` and `UploadFile` from `fastapi`:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/request_files/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/request_files/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/request_files/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Define `File` Parameters
|
||||
|
||||
Create file parameters the same way you would for `Body` or `Form`:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/request_files/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/request_files/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/request_files/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
`File` is a class that inherits directly from `Form`.
|
||||
@@ -45,9 +79,26 @@ But there are several cases in which you might benefit from using `UploadFile`.
|
||||
|
||||
Define a file parameter with a type of `UploadFile`:
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!../../../docs_src/request_files/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!> ../../../docs_src/request_files/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/request_files/tutorial001.py!}
|
||||
```
|
||||
|
||||
Using `UploadFile` has several advantages over `bytes`:
|
||||
|
||||
@@ -118,25 +169,66 @@ The way HTML forms (`<form></form>`) sends the data to the server normally uses
|
||||
|
||||
You can make a file optional by using standard type annotations and setting a default value of `None`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9 17"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9 17"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10 18"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7 15"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9 17"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
|
||||
```Python hl_lines="7 14"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
|
||||
```
|
||||
|
||||
## `UploadFile` with Additional Metadata
|
||||
|
||||
You can also use `File()` with `UploadFile`, for example, to set additional metadata:
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!../../../docs_src/request_files/tutorial001_03.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9 15"
|
||||
{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8 14"
|
||||
{!> ../../../docs_src/request_files/tutorial001_03_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7 13"
|
||||
{!> ../../../docs_src/request_files/tutorial001_03.py!}
|
||||
```
|
||||
|
||||
## Multiple File Uploads
|
||||
|
||||
@@ -146,18 +238,36 @@ They would be associated to the same "form field" sent using "form data".
|
||||
|
||||
To use that, declare a list of `bytes` or `UploadFile`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/request_files/tutorial002.py!}
|
||||
{!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11 16"
|
||||
{!> ../../../docs_src/request_files/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!> ../../../docs_src/request_files/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/request_files/tutorial002.py!}
|
||||
```
|
||||
|
||||
You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
|
||||
|
||||
!!! note "Technical Details"
|
||||
@@ -169,18 +279,36 @@ You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
|
||||
|
||||
And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/request_files/tutorial003.py!}
|
||||
```Python hl_lines="11 18-20"
|
||||
{!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
```Python hl_lines="12 19-21"
|
||||
{!> ../../../docs_src/request_files/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="9 16"
|
||||
{!> ../../../docs_src/request_files/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="11 18"
|
||||
{!> ../../../docs_src/request_files/tutorial003.py!}
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
Use `File`, `bytes`, and `UploadFile` to declare files to be uploaded in the request, sent as form data.
|
||||
|
||||
@@ -9,17 +9,51 @@ You can define files and form fields at the same time using `File` and `Form`.
|
||||
|
||||
## Import `File` and `Form`
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/request_forms_and_files/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Define `File` and `Form` parameters
|
||||
|
||||
Create file and form parameters the same way you would for `Body` or `Query`:
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!../../../docs_src/request_forms_and_files/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="10-12"
|
||||
{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9-11"
|
||||
{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/request_forms_and_files/tutorial001.py!}
|
||||
```
|
||||
|
||||
The files and form fields will be uploaded as form data and you will receive the files and form fields.
|
||||
|
||||
|
||||
@@ -11,17 +11,51 @@ When you need to receive form fields instead of JSON, you can use `Form`.
|
||||
|
||||
Import `Form` from `fastapi`:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/request_forms/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/request_forms/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Define `Form` parameters
|
||||
|
||||
Create form parameters the same way you would for `Body` or `Query`:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/request_forms/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/request_forms/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/request_forms/tutorial001.py!}
|
||||
```
|
||||
|
||||
For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields.
|
||||
|
||||
|
||||
@@ -4,22 +4,22 @@ You can declare the type used for the response by annotating the *path operation
|
||||
|
||||
You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="18 23"
|
||||
{!> ../../../docs_src/response_model/tutorial001_01.py!}
|
||||
```Python hl_lines="16 21"
|
||||
{!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="18 23"
|
||||
{!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="16 21"
|
||||
{!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
|
||||
```Python hl_lines="18 23"
|
||||
{!> ../../../docs_src/response_model/tutorial001_01.py!}
|
||||
```
|
||||
|
||||
FastAPI will use this return type to:
|
||||
@@ -53,22 +53,22 @@ You can use the `response_model` parameter in any of the *path operations*:
|
||||
* `@app.delete()`
|
||||
* etc.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="17 22 24-27"
|
||||
{!> ../../../docs_src/response_model/tutorial001.py!}
|
||||
{!> ../../../docs_src/response_model/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="17 22 24-27"
|
||||
{!> ../../../docs_src/response_model/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="17 22 24-27"
|
||||
{!> ../../../docs_src/response_model/tutorial001_py310.py!}
|
||||
{!> ../../../docs_src/response_model/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note
|
||||
@@ -95,18 +95,18 @@ You can also use `response_model=None` to disable creating a response model for
|
||||
|
||||
Here we are declaring a `UserIn` model, it will contain a plaintext password:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9 11"
|
||||
{!> ../../../docs_src/response_model/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7 9"
|
||||
{!> ../../../docs_src/response_model/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9 11"
|
||||
{!> ../../../docs_src/response_model/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
To use `EmailStr`, first install <a href="https://github.com/JoshData/python-email-validator" class="external-link" target="_blank">`email_validator`</a>.
|
||||
|
||||
@@ -115,18 +115,18 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password:
|
||||
|
||||
And we are using this model to declare our input and the same model to declare our output:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/response_model/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/response_model/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/response_model/tutorial002.py!}
|
||||
```
|
||||
|
||||
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
|
||||
|
||||
In this case, it might not be a problem, because it's the same user sending the password.
|
||||
@@ -140,46 +140,46 @@ But if we use the same model for another *path operation*, we could be sending o
|
||||
|
||||
We can instead create an input model with the plaintext password and an output model without it:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9 11 16"
|
||||
{!> ../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9 11 16"
|
||||
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9 11 16"
|
||||
{!> ../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
Here, even though our *path operation function* is returning the same input user that contains the password:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/response_model/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
|
||||
|
||||
### `response_model` or Return Type
|
||||
@@ -202,18 +202,18 @@ But in most of the cases where we need to do something like this, we want the mo
|
||||
|
||||
And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9-13 15-16 20"
|
||||
{!> ../../../docs_src/response_model/tutorial003_01.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7-10 13-14 18"
|
||||
{!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9-13 15-16 20"
|
||||
{!> ../../../docs_src/response_model/tutorial003_01.py!}
|
||||
```
|
||||
|
||||
With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.
|
||||
|
||||
How does this work? Let's check that out. 🤓
|
||||
@@ -278,18 +278,18 @@ But when you return some other arbitrary object that is not a valid Pydantic typ
|
||||
|
||||
The same would happen if you had something like a <abbr title='A union between multiple types means "any of these types".'>union</abbr> between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/response_model/tutorial003_04.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/response_model/tutorial003_04.py!}
|
||||
```
|
||||
|
||||
...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.
|
||||
|
||||
### Disable Response Model
|
||||
@@ -300,40 +300,40 @@ But you might want to still keep the return type annotation in the function to g
|
||||
|
||||
In this case, you can disable the response model generation by setting `response_model=None`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/response_model/tutorial003_05.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/response_model/tutorial003_05.py!}
|
||||
```
|
||||
|
||||
This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓
|
||||
|
||||
## Response Model encoding parameters
|
||||
|
||||
Your response model could have default values, like:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="11 13-14"
|
||||
{!> ../../../docs_src/response_model/tutorial004.py!}
|
||||
```Python hl_lines="9 11-12"
|
||||
{!> ../../../docs_src/response_model/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="11 13-14"
|
||||
{!> ../../../docs_src/response_model/tutorial004_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9 11-12"
|
||||
{!> ../../../docs_src/response_model/tutorial004_py310.py!}
|
||||
```Python hl_lines="11 13-14"
|
||||
{!> ../../../docs_src/response_model/tutorial004.py!}
|
||||
```
|
||||
|
||||
* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.
|
||||
@@ -348,22 +348,22 @@ For example, if you have models with many optional attributes in a NoSQL databas
|
||||
|
||||
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/response_model/tutorial004.py!}
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/response_model/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/response_model/tutorial004_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/response_model/tutorial004_py310.py!}
|
||||
```Python hl_lines="24"
|
||||
{!> ../../../docs_src/response_model/tutorial004.py!}
|
||||
```
|
||||
|
||||
and those default values won't be included in the response, only the values actually set.
|
||||
@@ -441,18 +441,18 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan
|
||||
|
||||
This also applies to `response_model_by_alias` that works similarly.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="31 37"
|
||||
{!> ../../../docs_src/response_model/tutorial005.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="29 35"
|
||||
{!> ../../../docs_src/response_model/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="31 37"
|
||||
{!> ../../../docs_src/response_model/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
The syntax `{"name", "description"}` creates a `set` with those two values.
|
||||
|
||||
@@ -462,18 +462,18 @@ This can be used as a quick shortcut if you have only one Pydantic model and wan
|
||||
|
||||
If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="31 37"
|
||||
{!> ../../../docs_src/response_model/tutorial006.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="29 35"
|
||||
{!> ../../../docs_src/response_model/tutorial006_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="31 37"
|
||||
{!> ../../../docs_src/response_model/tutorial006.py!}
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
Use the *path operation decorator's* parameter `response_model` to define response models and especially to ensure private data is filtered out.
|
||||
|
||||
@@ -8,18 +8,18 @@ Here are several ways to do it.
|
||||
|
||||
You can declare an `example` for a Pydantic model using `Config` and `schema_extra`, as described in <a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic's docs: Schema customization</a>:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="15-23"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="13-21"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="15-23"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial001.py!}
|
||||
```
|
||||
|
||||
That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs.
|
||||
|
||||
!!! tip
|
||||
@@ -33,18 +33,18 @@ When using `Field()` with Pydantic models, you can also declare extra info for t
|
||||
|
||||
You can use this to add `example` for each field:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="4 10-13"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="2 8-11"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="4 10-13"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! warning
|
||||
Keep in mind that those extra arguments passed won't add any validation, only extra information, for documentation purposes.
|
||||
|
||||
@@ -66,18 +66,39 @@ you can also declare a data `example` or a group of `examples` with additional i
|
||||
|
||||
Here we pass an `example` of the data expected in `Body()`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="20-25"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
|
||||
```Python hl_lines="22-27"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="22-27"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="23-28"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
```Python hl_lines="18-23"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="20-25"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
|
||||
```
|
||||
|
||||
### Example in the docs UI
|
||||
|
||||
With any of the methods above it would look like this in the `/docs`:
|
||||
@@ -97,18 +118,39 @@ Each specific example `dict` in the `examples` can contain:
|
||||
* `value`: This is the actual example shown, e.g. a `dict`.
|
||||
* `externalValue`: alternative to `value`, a URL pointing to the example. Although this might not be supported by as many tools as `value`.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="21-47"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
|
||||
```Python hl_lines="23-49"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="23-49"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="24-50"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
```Python hl_lines="19-45"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="21-47"
|
||||
{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
|
||||
```
|
||||
|
||||
### Examples in the docs UI
|
||||
|
||||
With `examples` added to `Body()` the `/docs` would look like:
|
||||
|
||||
@@ -20,9 +20,27 @@ Let's first just use the code and see how it works, and then we'll come back to
|
||||
|
||||
Copy the example in a file `main.py`:
|
||||
|
||||
```Python
|
||||
{!../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/security/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/security/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
|
||||
|
||||
## Run it
|
||||
|
||||
@@ -116,9 +134,26 @@ In this example we are going to use **OAuth2**, with the **Password** flow, usin
|
||||
|
||||
When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token.
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/security/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/security/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!> ../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
|
||||
@@ -150,9 +185,26 @@ So, it can be used with `Depends`.
|
||||
|
||||
Now you can pass that `oauth2_scheme` in a dependency with `Depends`.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/security/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/security/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
|
||||
This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*.
|
||||
|
||||
|
||||
@@ -2,9 +2,26 @@
|
||||
|
||||
In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/security/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!> ../../../docs_src/security/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/security/tutorial001.py!}
|
||||
```
|
||||
|
||||
But that is still not that useful.
|
||||
|
||||
@@ -16,18 +33,42 @@ First, let's create a Pydantic user model.
|
||||
|
||||
The same way we use Pydantic to declare bodies, we can use it anywhere else:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="5 12-16"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
{!> ../../../docs_src/security/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="5 12-16"
|
||||
{!> ../../../docs_src/security/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="5 13-17"
|
||||
{!> ../../../docs_src/security/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 10-14"
|
||||
{!> ../../../docs_src/security/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="5 12-16"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
```
|
||||
|
||||
## Create a `get_current_user` dependency
|
||||
|
||||
Let's create a dependency `get_current_user`.
|
||||
@@ -38,50 +79,122 @@ Remember that dependencies can have sub-dependencies?
|
||||
|
||||
The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="25"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
{!> ../../../docs_src/security/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="25"
|
||||
{!> ../../../docs_src/security/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="26"
|
||||
{!> ../../../docs_src/security/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="23"
|
||||
{!> ../../../docs_src/security/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="25"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
```
|
||||
|
||||
## Get the user
|
||||
|
||||
`get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="19-22 26-27"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
{!> ../../../docs_src/security/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="19-22 26-27"
|
||||
{!> ../../../docs_src/security/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="20-23 27-28"
|
||||
{!> ../../../docs_src/security/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="17-20 24-25"
|
||||
{!> ../../../docs_src/security/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="19-22 26-27"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
```
|
||||
|
||||
## Inject the current user
|
||||
|
||||
So now we can use the same `Depends` with our `get_current_user` in the *path operation*:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="31"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
{!> ../../../docs_src/security/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="31"
|
||||
{!> ../../../docs_src/security/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="32"
|
||||
{!> ../../../docs_src/security/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="29"
|
||||
{!> ../../../docs_src/security/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="31"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
```
|
||||
|
||||
Notice that we declare the type of `current_user` as the Pydantic model `User`.
|
||||
|
||||
This will help us inside of the function with all the completion and type checks.
|
||||
@@ -128,18 +241,42 @@ And all of them (or any portion of them that you want) can take the advantage of
|
||||
|
||||
And all these thousands of *path operations* can be as small as 3 lines:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="30-32"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
{!> ../../../docs_src/security/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="30-32"
|
||||
{!> ../../../docs_src/security/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="31-33"
|
||||
{!> ../../../docs_src/security/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="28-30"
|
||||
{!> ../../../docs_src/security/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="30-32"
|
||||
{!> ../../../docs_src/security/tutorial002.py!}
|
||||
```
|
||||
|
||||
## Recap
|
||||
|
||||
You can now get the current user directly in your *path operation function*.
|
||||
|
||||
@@ -109,18 +109,42 @@ And another utility to verify if a received password matches the hash stored.
|
||||
|
||||
And another one to authenticate and return a user.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7 48 55-56 59-60 69-75"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7 48 55-56 59-60 69-75"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="7 49 56-57 60-61 70-76"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6 47 54-55 58-59 68-74"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="7 48 55-56 59-60 69-75"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
!!! note
|
||||
If you check the new (fake) database `fake_users_db`, you will see how the hashed password looks like now: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`.
|
||||
|
||||
@@ -152,18 +176,42 @@ Define a Pydantic Model that will be used in the token endpoint for the response
|
||||
|
||||
Create a utility function to generate a new access token.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="6 12-14 28-30 78-86"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6 12-14 28-30 78-86"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="6 13-15 29-31 79-87"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="5 11-13 27-29 77-85"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="6 12-14 28-30 78-86"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Update the dependencies
|
||||
|
||||
Update `get_current_user` to receive the same token as before, but this time, using JWT tokens.
|
||||
@@ -172,36 +220,84 @@ Decode the received token, verify it, and return the current user.
|
||||
|
||||
If the token is invalid, return an HTTP error right away.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="89-106"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="89-106"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="90-107"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="88-105"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="89-106"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Update the `/token` *path operation*
|
||||
|
||||
Create a `timedelta` with the expiration time of the token.
|
||||
|
||||
Create a real JWT access token and return it.
|
||||
Create a real JWT access token and return it
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="115-128"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```Python hl_lines="117-132"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="117-132"
|
||||
{!> ../../../docs_src/security/tutorial004_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="118-133"
|
||||
{!> ../../../docs_src/security/tutorial004_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="114-127"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="115-128"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
### Technical details about the JWT "subject" `sub`
|
||||
|
||||
The JWT specification says that there's a key `sub`, with the subject of the token.
|
||||
|
||||
@@ -49,18 +49,42 @@ Now let's use the utilities provided by **FastAPI** to handle this.
|
||||
|
||||
First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 76"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```Python hl_lines="4 78"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 78"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="4 79"
|
||||
{!> ../../../docs_src/security/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 74"
|
||||
{!> ../../../docs_src/security/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 76"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```
|
||||
|
||||
`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:
|
||||
|
||||
* The `username`.
|
||||
@@ -98,18 +122,42 @@ If there is no such user, we return an error saying "incorrect username or passw
|
||||
|
||||
For the error, we use the exception `HTTPException`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3 77-79"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```Python hl_lines="3 79-81"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3 79-81"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3 80-82"
|
||||
{!> ../../../docs_src/security/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 75-77"
|
||||
{!> ../../../docs_src/security/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 77-79"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```
|
||||
|
||||
### Check the password
|
||||
|
||||
At this point we have the user data from our database, but we haven't checked the password.
|
||||
@@ -134,18 +182,42 @@ If your database is stolen, the thief won't have your users' plaintext passwords
|
||||
|
||||
So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="80-83"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```Python hl_lines="82-85"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="82-85"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="83-86"
|
||||
{!> ../../../docs_src/security/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="78-81"
|
||||
{!> ../../../docs_src/security/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="80-83"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```
|
||||
|
||||
#### About `**user_dict`
|
||||
|
||||
`UserInDB(**user_dict)` means:
|
||||
@@ -180,18 +252,42 @@ For this simple example, we are going to just be completely insecure and return
|
||||
|
||||
But for now, let's focus on the specific details we need.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="85"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```Python hl_lines="87"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="87"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="88"
|
||||
{!> ../../../docs_src/security/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="83"
|
||||
{!> ../../../docs_src/security/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="85"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
|
||||
|
||||
@@ -213,18 +309,42 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex
|
||||
|
||||
So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="58-66 69-74 94"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="58-66 69-74 94"
|
||||
{!> ../../../docs_src/security/tutorial003_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="59-67 70-75 95"
|
||||
{!> ../../../docs_src/security/tutorial003_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="56-64 67-70 88"
|
||||
{!> ../../../docs_src/security/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="58-66 69-72 90"
|
||||
{!> ../../../docs_src/security/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
|
||||
```Python hl_lines="55-64 67-70 88"
|
||||
{!> ../../../docs_src/security/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
|
||||
|
||||
|
||||
@@ -262,22 +262,22 @@ So, the user will also have a `password` when creating it.
|
||||
|
||||
But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3 6-8 11-12 23-24 27-28"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```Python hl_lines="1 4-6 9-10 21-22 25-26"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3 6-8 11-12 23-24 27-28"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 4-6 9-10 21-22 25-26"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```Python hl_lines="3 6-8 11-12 23-24 27-28"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
#### SQLAlchemy style and Pydantic style
|
||||
@@ -306,22 +306,22 @@ The same way, when reading a user, we can now declare that `items` will contain
|
||||
|
||||
Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="15-17 31-34"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```Python hl_lines="13-15 29-32"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="15-17 31-34"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="13-15 29-32"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```Python hl_lines="15-17 31-34"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
@@ -335,22 +335,22 @@ This <a href="https://pydantic-docs.helpmanual.io/usage/model_config/" class="ex
|
||||
|
||||
In the `Config` class, set the attribute `orm_mode = True`.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="15 19-20 31 36-37"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```Python hl_lines="13 17-18 29 34-35"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="15 19-20 31 36-37"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="13 17-18 29 34-35"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```Python hl_lines="15 19-20 31 36-37"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
@@ -481,18 +481,18 @@ And now in the file `sql_app/main.py` let's integrate and use all the other part
|
||||
|
||||
In a very simplistic way create the database tables:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
#### Alembic Note
|
||||
|
||||
Normally you would probably initialize your database (create tables, etc) with <a href="https://alembic.sqlalchemy.org/en/latest/" class="external-link" target="_blank">Alembic</a>.
|
||||
@@ -515,18 +515,18 @@ For that, we will create a new dependency with `yield`, as explained before in t
|
||||
|
||||
Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="15-20"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="13-18"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="15-20"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
We put the creation of the `SessionLocal()` and handling of the requests in a `try` block.
|
||||
|
||||
@@ -540,18 +540,18 @@ And then, when using the dependency in a *path operation function*, we declare i
|
||||
|
||||
This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="24 32 38 47 53"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="22 30 36 45 51"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="24 32 38 47 53"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
!!! info "Technical Details"
|
||||
The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided.
|
||||
|
||||
@@ -561,18 +561,18 @@ This will then give us better editor support inside the *path operation function
|
||||
|
||||
Now, finally, here's the standard **FastAPI** *path operations* code.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards.
|
||||
|
||||
And then we can create the required dependency in the *path operation function*, to get that session directly.
|
||||
@@ -654,22 +654,22 @@ For example, in a background task worker with <a href="https://docs.celeryq.dev"
|
||||
|
||||
* `sql_app/schemas.py`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
* `sql_app/crud.py`:
|
||||
@@ -680,18 +680,18 @@ For example, in a background task worker with <a href="https://docs.celeryq.dev"
|
||||
|
||||
* `sql_app/main.py`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
## Check it
|
||||
|
||||
You can copy this code and use it as is.
|
||||
@@ -739,18 +739,18 @@ A "middleware" is basically a function that is always executed for each request,
|
||||
|
||||
The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="14-22"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12-20"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="14-22"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
We put the creation of the `SessionLocal()` and handling of the requests in a `try` block.
|
||||
|
||||
|
||||
@@ -110,18 +110,42 @@ It has a `POST` operation that could return several errors.
|
||||
|
||||
Both *path operations* require an `X-Token` header.
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b/main.py!}
|
||||
{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b_an/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+ non-Annotated"
|
||||
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b/main.py!}
|
||||
```
|
||||
|
||||
### Extended testing file
|
||||
|
||||
You could then update `test_main.py` with the extended tests:
|
||||
|
||||
@@ -74,18 +74,18 @@
|
||||
|
||||
これらの *path operation* には `X-Token` ヘッダーが必要です。
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b_py310/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/app_testing/app_b/main.py!}
|
||||
```
|
||||
|
||||
### 拡張版テストファイル
|
||||
|
||||
次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。
|
||||
|
||||
@@ -8,18 +8,18 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ
|
||||
|
||||
E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`:
|
||||
|
||||
=== "Python 3.6 e superiores"
|
||||
|
||||
```Python hl_lines="19-21"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e superiores"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="17-19"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="19-21"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! nota
|
||||
Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão.
|
||||
|
||||
@@ -38,18 +38,18 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten
|
||||
|
||||
Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`:
|
||||
|
||||
=== "Python 3.6 e superiores"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e superiores"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic).
|
||||
|
||||
Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo, e espera um corpo como:
|
||||
@@ -87,13 +87,13 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir
|
||||
|
||||
Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`:
|
||||
|
||||
=== "Python 3.6 e superiores"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e superiores"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
|
||||
@@ -137,18 +137,18 @@ q: str | None = None
|
||||
|
||||
Por exemplo:
|
||||
|
||||
=== "Python 3.6 e superiores"
|
||||
|
||||
```Python hl_lines="27"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e superiores"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="26"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="27"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
!!! info "Informação"
|
||||
`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois.
|
||||
|
||||
@@ -166,18 +166,18 @@ item: Item = Body(embed=True)
|
||||
|
||||
como em:
|
||||
|
||||
=== "Python 3.6 e superiores"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e superiores"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/body_multiple_params/tutorial005.py!}
|
||||
```
|
||||
|
||||
Neste caso o **FastAPI** esperará um corpo como:
|
||||
|
||||
```JSON hl_lines="2"
|
||||
|
||||
@@ -20,18 +20,18 @@ Você pode usar a função `jsonable_encoder` para resolver isso.
|
||||
|
||||
A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON:
|
||||
|
||||
=== "Python 3.6 e acima"
|
||||
|
||||
```Python hl_lines="5 22"
|
||||
{!> ../../../docs_src/encoder/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e acima"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 21"
|
||||
{!> ../../../docs_src/encoder/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="5 22"
|
||||
{!> ../../../docs_src/encoder/tutorial001.py!}
|
||||
```
|
||||
|
||||
Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`.
|
||||
|
||||
O resultado de chamar a função é algo que pode ser codificado com o padrão do Python <a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a>.
|
||||
|
||||
@@ -6,36 +6,36 @@ Você pode definir parâmetros de Cabeçalho da mesma maneira que define paramê
|
||||
|
||||
Primeiro importe `Header`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/header_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Declare parâmetros de `Header`
|
||||
|
||||
Então declare os paramêtros de cabeçalho usando a mesma estrutura que em `Path`, `Query` e `Cookie`.
|
||||
|
||||
O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/header_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "Detalhes Técnicos"
|
||||
`Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`.
|
||||
|
||||
@@ -60,18 +60,18 @@ Portanto, você pode usar `user_agent` como faria normalmente no código Python,
|
||||
|
||||
Se por algum motivo você precisar desabilitar a conversão automática de sublinhados para hífens, defina o parâmetro `convert_underscores` de `Header` para `False`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/header_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/header_params/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/header_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! warning "Aviso"
|
||||
Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados.
|
||||
|
||||
@@ -85,22 +85,22 @@ Você receberá todos os valores do cabeçalho duplicado como uma `list` Python.
|
||||
|
||||
Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de uma vez, você pode escrever:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial003.py!}
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/header_params/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 and above"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/header_params/tutorial003_py310.py!}
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/header_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como:
|
||||
|
||||
@@ -6,36 +6,36 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme
|
||||
|
||||
Primeiro, importe `Path` de `fastapi`:
|
||||
|
||||
=== "Python 3.6 e superiores"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e superiores"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Declare metadados
|
||||
|
||||
Você pode declarar todos os parâmetros da mesma maneira que na `Query`.
|
||||
|
||||
Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar:
|
||||
|
||||
=== "Python 3.6 e superiores"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 e superiores"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "Nota"
|
||||
Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota.
|
||||
|
||||
|
||||
@@ -63,18 +63,18 @@ Os valores dos parâmetros na sua função serão:
|
||||
|
||||
Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão.
|
||||
|
||||
!!! check "Verificar"
|
||||
@@ -85,18 +85,18 @@ Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrã
|
||||
|
||||
Você também pode declarar tipos `bool`, e eles serão convertidos:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
Nesse caso, se você for para:
|
||||
|
||||
```
|
||||
@@ -137,18 +137,18 @@ E você não precisa declarar eles em nenhuma ordem específica.
|
||||
|
||||
Eles serão detectados pelo nome:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="8 10"
|
||||
{!> ../../../docs_src/query_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="6 8"
|
||||
{!> ../../../docs_src/query_params/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="8 10"
|
||||
{!> ../../../docs_src/query_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Parâmetros de consulta obrigatórios
|
||||
|
||||
Quando você declara um valor padrão para parâmetros que não são de rota (até agora, nós vimos apenas parâmetros de consulta), então eles não são obrigatórios.
|
||||
@@ -203,17 +203,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
|
||||
|
||||
E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params/tutorial006_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params/tutorial006.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params/tutorial006_py310.py!}
|
||||
```
|
||||
Nesse caso, existem 3 parâmetros de consulta:
|
||||
|
||||
* `needy`, um `str` obrigatório.
|
||||
|
||||
@@ -57,18 +57,18 @@
|
||||
|
||||
**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
|
||||
|
||||
=== "Python 3.6 и выше"
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 и выше"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="11 13 20 23"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002.py!}
|
||||
```
|
||||
|
||||
В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
|
||||
|
||||
Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`).
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||
Сначала вы должны импортировать его:
|
||||
|
||||
=== "Python 3.6 и выше"
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 и выше"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="2"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning "Внимание"
|
||||
Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
|
||||
|
||||
@@ -25,18 +25,18 @@
|
||||
|
||||
Вы можете использовать функцию `Field` с атрибутами модели:
|
||||
|
||||
=== "Python 3.6 и выше"
|
||||
|
||||
```Python hl_lines="11-14"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 и выше"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9-12"
|
||||
{!> ../../../docs_src/body_fields/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="11-14"
|
||||
{!> ../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
Функция `Field` работает так же, как `Query`, `Path` и `Body`, у ее такие же параметры и т.д.
|
||||
|
||||
!!! note "Технические детали"
|
||||
|
||||
@@ -6,36 +6,36 @@
|
||||
|
||||
Сначала импортируйте `Cookie`:
|
||||
|
||||
=== "Python 3.6 и выше"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 и выше"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Объявление параметров `Cookie`
|
||||
|
||||
Затем объявляйте параметры cookie, используя ту же структуру, что и с `Path` и `Query`.
|
||||
|
||||
Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации:
|
||||
|
||||
=== "Python 3.6 и выше"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 и выше"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/cookie_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "Технические детали"
|
||||
`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`.
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||
在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`:
|
||||
|
||||
=== "Python 3.6 以及 以上"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 以及以上"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。
|
||||
|
||||
我们知道编辑器不能为 `dict` 提供很多支持(比如补全),因为编辑器不知道 `dict` 的键和值类型。
|
||||
@@ -79,46 +79,46 @@ fluffy = Cat(name="Mr Fluffy")
|
||||
|
||||
所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`:
|
||||
|
||||
=== "Python 3.6 以及 以上"
|
||||
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 以及 以上"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="9-13"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
注意用于创建类实例的 `__init__` 方法:
|
||||
=== "Python 3.6+"
|
||||
|
||||
=== "Python 3.6 以及 以上"
|
||||
|
||||
```Python hl_lines="12"
|
||||
```Python hl_lines="11-15"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 以及 以上"
|
||||
注意用于创建类实例的 `__init__` 方法:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
...它与我们以前的 `common_parameters` 具有相同的参数:
|
||||
=== "Python 3.6+"
|
||||
|
||||
=== "Python 3.6 以及 以上"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```Python hl_lines="12"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 以及 以上"
|
||||
...它与我们以前的 `common_parameters` 具有相同的参数:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
这些参数就是 **FastAPI** 用来 "处理" 依赖项的。
|
||||
|
||||
在两个例子下,都有:
|
||||
@@ -133,18 +133,18 @@ fluffy = Cat(name="Mr Fluffy")
|
||||
|
||||
现在,您可以使用这个类来声明你的依赖项了。
|
||||
|
||||
=== "Python 3.6 以及 以上"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 以及 以上"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
**FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。
|
||||
|
||||
## 类型注解 vs `Depends`
|
||||
@@ -183,18 +183,18 @@ commons = Depends(CommonQueryParams)
|
||||
|
||||
..就像:
|
||||
|
||||
=== "Python 3.6 以及 以上"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 以及 以上"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial003.py!}
|
||||
```
|
||||
|
||||
但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等:
|
||||
|
||||
<img src="/img/tutorial/dependencies/image02.png">
|
||||
@@ -227,18 +227,18 @@ commons: CommonQueryParams = Depends()
|
||||
|
||||
同样的例子看起来像这样:
|
||||
|
||||
=== "Python 3.6 以及 以上"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 以及 以上"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!> ../../../docs_src/dependencies/tutorial004.py!}
|
||||
```
|
||||
|
||||
... **FastAPI** 会知道怎么处理。
|
||||
|
||||
!!! tip
|
||||
|
||||
@@ -20,18 +20,18 @@
|
||||
|
||||
它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本:
|
||||
|
||||
=== "Python 3.6 and above"
|
||||
|
||||
```Python hl_lines="5 22"
|
||||
{!> ../../../docs_src/encoder/tutorial001.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 and above"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 21"
|
||||
{!> ../../../docs_src/encoder/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="5 22"
|
||||
{!> ../../../docs_src/encoder/tutorial001.py!}
|
||||
```
|
||||
|
||||
在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。
|
||||
|
||||
调用它的结果后就可以使用Python标准编码中的<a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a>。
|
||||
|
||||
@@ -124,18 +124,18 @@ contents = myfile.file.read()
|
||||
|
||||
您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="9 17"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7 14"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9 17"
|
||||
{!> ../../../docs_src/request_files/tutorial001_02.py!}
|
||||
```
|
||||
|
||||
## 带有额外元数据的 `UploadFile`
|
||||
|
||||
您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
|
||||
@@ -152,18 +152,18 @@ FastAPI 支持同时上传多个文件。
|
||||
|
||||
上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`):
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/request_files/tutorial002.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!> ../../../docs_src/request_files/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="10 15"
|
||||
{!> ../../../docs_src/request_files/tutorial002.py!}
|
||||
```
|
||||
|
||||
接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。
|
||||
|
||||
|
||||
@@ -177,18 +177,18 @@ FastAPI 支持同时上传多个文件。
|
||||
|
||||
和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`:
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/request_files/tutorial003.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!> ../../../docs_src/request_files/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!> ../../../docs_src/request_files/tutorial003.py!}
|
||||
```
|
||||
|
||||
## 小结
|
||||
|
||||
本节介绍了如何用 `File` 把上传文件声明为(表单数据的)输入参数。
|
||||
|
||||
@@ -246,22 +246,22 @@ connect_args={"check_same_thread": False}
|
||||
|
||||
但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如用户请求时不应该从 API 返回响应中包含它。
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="3 6-8 11-12 23-24 27-28"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```Python hl_lines="1 4-6 9-10 21-22 25-26"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3 6-8 11-12 23-24 27-28"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 及以上版本"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="1 4-6 9-10 21-22 25-26"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```Python hl_lines="3 6-8 11-12 23-24 27-28"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
#### SQLAlchemy 风格和 Pydantic 风格
|
||||
@@ -290,22 +290,22 @@ name: str
|
||||
|
||||
不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`.
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="15-17 31-34"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```Python hl_lines="13-15 29-32"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="15-17 31-34"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 及以上版本"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="13-15 29-32"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```Python hl_lines="15-17 31-34"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
@@ -319,22 +319,22 @@ name: str
|
||||
|
||||
在`Config`类中,设置属性`orm_mode = True`。
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="15 19-20 31 36-37"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```Python hl_lines="13 17-18 29 34-35"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="15 19-20 31 36-37"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 及以上版本"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="13 17-18 29 34-35"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```Python hl_lines="15 19-20 31 36-37"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
@@ -465,18 +465,18 @@ current_user.items
|
||||
|
||||
以非常简单的方式创建数据库表:
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
#### Alembic 注意
|
||||
|
||||
通常你可能会使用 <a href="https://alembic.sqlalchemy.org/en/latest/" class="external-link" target="_blank">Alembic</a>,来进行格式化数据库(创建表等)。
|
||||
@@ -499,18 +499,18 @@ current_user.items
|
||||
|
||||
我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="15-20"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="13-18"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="15-20"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
|
||||
|
||||
@@ -524,18 +524,18 @@ current_user.items
|
||||
|
||||
*这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`:
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="24 32 38 47 53"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="22 30 36 45 51"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="24 32 38 47 53"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
!!! info "技术细节"
|
||||
参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。
|
||||
|
||||
@@ -545,18 +545,18 @@ current_user.items
|
||||
|
||||
现在,到了最后,编写标准的**FastAPI** *路径操作*代码。
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="21-26 29-32 35-40 43-47 50-53"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="23-28 31-34 37-42 45-49 52-55"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。
|
||||
|
||||
所以我们就可以在*路径操作函数*中创建需要的依赖,就能直接获取会话。
|
||||
@@ -638,22 +638,22 @@ def read_user(user_id: int, db: Session = Depends(get_db)):
|
||||
|
||||
* `sql_app/schemas.py`:
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10 及以上版本"
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
|
||||
{!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
|
||||
```
|
||||
|
||||
* `sql_app/crud.py`:
|
||||
@@ -664,18 +664,18 @@ def read_user(user_id: int, db: Session = Depends(get_db)):
|
||||
|
||||
* `sql_app/main.py`:
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/sql_databases/sql_app/main.py!}
|
||||
```
|
||||
|
||||
## 执行项目
|
||||
|
||||
您可以复制这些代码并按原样使用它。
|
||||
@@ -723,18 +723,18 @@ $ uvicorn sql_app.main:app --reload
|
||||
|
||||
我们将添加中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。
|
||||
|
||||
=== "Python 3.6 及以上版本"
|
||||
|
||||
```Python hl_lines="14-22"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9 及以上版本"
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="12-20"
|
||||
{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.6+"
|
||||
|
||||
```Python hl_lines="14-22"
|
||||
{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。
|
||||
|
||||
|
||||
26
docs_src/additional_status_codes/tutorial001_an.py
Normal file
26
docs_src/additional_status_codes/tutorial001_an.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from typing import Union
|
||||
|
||||
from fastapi import Body, FastAPI, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from typing_extensions import Annotated
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def upsert_item(
|
||||
item_id: str,
|
||||
name: Annotated[Union[str, None], Body()] = None,
|
||||
size: Annotated[Union[int, None], Body()] = None,
|
||||
):
|
||||
if item_id in items:
|
||||
item = items[item_id]
|
||||
item["name"] = name
|
||||
item["size"] = size
|
||||
return item
|
||||
else:
|
||||
item = {"name": name, "size": size}
|
||||
items[item_id] = item
|
||||
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
|
||||
25
docs_src/additional_status_codes/tutorial001_an_py310.py
Normal file
25
docs_src/additional_status_codes/tutorial001_an_py310.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Body, FastAPI, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def upsert_item(
|
||||
item_id: str,
|
||||
name: Annotated[str | None, Body()] = None,
|
||||
size: Annotated[int | None, Body()] = None,
|
||||
):
|
||||
if item_id in items:
|
||||
item = items[item_id]
|
||||
item["name"] = name
|
||||
item["size"] = size
|
||||
return item
|
||||
else:
|
||||
item = {"name": name, "size": size}
|
||||
items[item_id] = item
|
||||
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
|
||||
25
docs_src/additional_status_codes/tutorial001_an_py39.py
Normal file
25
docs_src/additional_status_codes/tutorial001_an_py39.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from typing import Annotated, Union
|
||||
|
||||
from fastapi import Body, FastAPI, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def upsert_item(
|
||||
item_id: str,
|
||||
name: Annotated[Union[str, None], Body()] = None,
|
||||
size: Annotated[Union[int, None], Body()] = None,
|
||||
):
|
||||
if item_id in items:
|
||||
item = items[item_id]
|
||||
item["name"] = name
|
||||
item["size"] = size
|
||||
return item
|
||||
else:
|
||||
item = {"name": name, "size": size}
|
||||
items[item_id] = item
|
||||
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
|
||||
23
docs_src/additional_status_codes/tutorial001_py310.py
Normal file
23
docs_src/additional_status_codes/tutorial001_py310.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from fastapi import Body, FastAPI, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
items = {"foo": {"name": "Fighters", "size": 6}, "bar": {"name": "Tenders", "size": 3}}
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def upsert_item(
|
||||
item_id: str,
|
||||
name: str | None = Body(default=None),
|
||||
size: int | None = Body(default=None),
|
||||
):
|
||||
if item_id in items:
|
||||
item = items[item_id]
|
||||
item["name"] = name
|
||||
item["size"] = size
|
||||
return item
|
||||
else:
|
||||
item = {"name": name, "size": size}
|
||||
items[item_id] = item
|
||||
return JSONResponse(status_code=status.HTTP_201_CREATED, content=item)
|
||||
0
docs_src/app_testing/app_b_an/__init__.py
Normal file
0
docs_src/app_testing/app_b_an/__init__.py
Normal file
39
docs_src/app_testing/app_b_an/main.py
Normal file
39
docs_src/app_testing/app_b_an/main.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from typing import Union
|
||||
|
||||
from fastapi import FastAPI, Header, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing_extensions import Annotated
|
||||
|
||||
fake_secret_token = "coneofsilence"
|
||||
|
||||
fake_db = {
|
||||
"foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
|
||||
"bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
|
||||
}
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
description: Union[str, None] = None
|
||||
|
||||
|
||||
@app.get("/items/{item_id}", response_model=Item)
|
||||
async def read_main(item_id: str, x_token: Annotated[str, Header()]):
|
||||
if x_token != fake_secret_token:
|
||||
raise HTTPException(status_code=400, detail="Invalid X-Token header")
|
||||
if item_id not in fake_db:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return fake_db[item_id]
|
||||
|
||||
|
||||
@app.post("/items/", response_model=Item)
|
||||
async def create_item(item: Item, x_token: Annotated[str, Header()]):
|
||||
if x_token != fake_secret_token:
|
||||
raise HTTPException(status_code=400, detail="Invalid X-Token header")
|
||||
if item.id in fake_db:
|
||||
raise HTTPException(status_code=400, detail="Item already exists")
|
||||
fake_db[item.id] = item
|
||||
return item
|
||||
65
docs_src/app_testing/app_b_an/test_main.py
Normal file
65
docs_src/app_testing/app_b_an/test_main.py
Normal file
@@ -0,0 +1,65 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from .main import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_read_item():
|
||||
response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": "foo",
|
||||
"title": "Foo",
|
||||
"description": "There goes my hero",
|
||||
}
|
||||
|
||||
|
||||
def test_read_item_bad_token():
|
||||
response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Invalid X-Token header"}
|
||||
|
||||
|
||||
def test_read_inexistent_item():
|
||||
response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "Item not found"}
|
||||
|
||||
|
||||
def test_create_item():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "coneofsilence"},
|
||||
json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": "foobar",
|
||||
"title": "Foo Bar",
|
||||
"description": "The Foo Barters",
|
||||
}
|
||||
|
||||
|
||||
def test_create_item_bad_token():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "hailhydra"},
|
||||
json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Invalid X-Token header"}
|
||||
|
||||
|
||||
def test_create_existing_item():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "coneofsilence"},
|
||||
json={
|
||||
"id": "foo",
|
||||
"title": "The Foo ID Stealers",
|
||||
"description": "There goes my stealer",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Item already exists"}
|
||||
0
docs_src/app_testing/app_b_an_py310/__init__.py
Normal file
0
docs_src/app_testing/app_b_an_py310/__init__.py
Normal file
38
docs_src/app_testing/app_b_an_py310/main.py
Normal file
38
docs_src/app_testing/app_b_an_py310/main.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import FastAPI, Header, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
fake_secret_token = "coneofsilence"
|
||||
|
||||
fake_db = {
|
||||
"foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
|
||||
"bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
|
||||
}
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
description: str | None = None
|
||||
|
||||
|
||||
@app.get("/items/{item_id}", response_model=Item)
|
||||
async def read_main(item_id: str, x_token: Annotated[str, Header()]):
|
||||
if x_token != fake_secret_token:
|
||||
raise HTTPException(status_code=400, detail="Invalid X-Token header")
|
||||
if item_id not in fake_db:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return fake_db[item_id]
|
||||
|
||||
|
||||
@app.post("/items/", response_model=Item)
|
||||
async def create_item(item: Item, x_token: Annotated[str, Header()]):
|
||||
if x_token != fake_secret_token:
|
||||
raise HTTPException(status_code=400, detail="Invalid X-Token header")
|
||||
if item.id in fake_db:
|
||||
raise HTTPException(status_code=400, detail="Item already exists")
|
||||
fake_db[item.id] = item
|
||||
return item
|
||||
65
docs_src/app_testing/app_b_an_py310/test_main.py
Normal file
65
docs_src/app_testing/app_b_an_py310/test_main.py
Normal file
@@ -0,0 +1,65 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from .main import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_read_item():
|
||||
response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": "foo",
|
||||
"title": "Foo",
|
||||
"description": "There goes my hero",
|
||||
}
|
||||
|
||||
|
||||
def test_read_item_bad_token():
|
||||
response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Invalid X-Token header"}
|
||||
|
||||
|
||||
def test_read_inexistent_item():
|
||||
response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "Item not found"}
|
||||
|
||||
|
||||
def test_create_item():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "coneofsilence"},
|
||||
json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": "foobar",
|
||||
"title": "Foo Bar",
|
||||
"description": "The Foo Barters",
|
||||
}
|
||||
|
||||
|
||||
def test_create_item_bad_token():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "hailhydra"},
|
||||
json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Invalid X-Token header"}
|
||||
|
||||
|
||||
def test_create_existing_item():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "coneofsilence"},
|
||||
json={
|
||||
"id": "foo",
|
||||
"title": "The Foo ID Stealers",
|
||||
"description": "There goes my stealer",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Item already exists"}
|
||||
0
docs_src/app_testing/app_b_an_py39/__init__.py
Normal file
0
docs_src/app_testing/app_b_an_py39/__init__.py
Normal file
38
docs_src/app_testing/app_b_an_py39/main.py
Normal file
38
docs_src/app_testing/app_b_an_py39/main.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from typing import Annotated, Union
|
||||
|
||||
from fastapi import FastAPI, Header, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
fake_secret_token = "coneofsilence"
|
||||
|
||||
fake_db = {
|
||||
"foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
|
||||
"bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
|
||||
}
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
description: Union[str, None] = None
|
||||
|
||||
|
||||
@app.get("/items/{item_id}", response_model=Item)
|
||||
async def read_main(item_id: str, x_token: Annotated[str, Header()]):
|
||||
if x_token != fake_secret_token:
|
||||
raise HTTPException(status_code=400, detail="Invalid X-Token header")
|
||||
if item_id not in fake_db:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return fake_db[item_id]
|
||||
|
||||
|
||||
@app.post("/items/", response_model=Item)
|
||||
async def create_item(item: Item, x_token: Annotated[str, Header()]):
|
||||
if x_token != fake_secret_token:
|
||||
raise HTTPException(status_code=400, detail="Invalid X-Token header")
|
||||
if item.id in fake_db:
|
||||
raise HTTPException(status_code=400, detail="Item already exists")
|
||||
fake_db[item.id] = item
|
||||
return item
|
||||
65
docs_src/app_testing/app_b_an_py39/test_main.py
Normal file
65
docs_src/app_testing/app_b_an_py39/test_main.py
Normal file
@@ -0,0 +1,65 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from .main import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_read_item():
|
||||
response = client.get("/items/foo", headers={"X-Token": "coneofsilence"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": "foo",
|
||||
"title": "Foo",
|
||||
"description": "There goes my hero",
|
||||
}
|
||||
|
||||
|
||||
def test_read_item_bad_token():
|
||||
response = client.get("/items/foo", headers={"X-Token": "hailhydra"})
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Invalid X-Token header"}
|
||||
|
||||
|
||||
def test_read_inexistent_item():
|
||||
response = client.get("/items/baz", headers={"X-Token": "coneofsilence"})
|
||||
assert response.status_code == 404
|
||||
assert response.json() == {"detail": "Item not found"}
|
||||
|
||||
|
||||
def test_create_item():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "coneofsilence"},
|
||||
json={"id": "foobar", "title": "Foo Bar", "description": "The Foo Barters"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"id": "foobar",
|
||||
"title": "Foo Bar",
|
||||
"description": "The Foo Barters",
|
||||
}
|
||||
|
||||
|
||||
def test_create_item_bad_token():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "hailhydra"},
|
||||
json={"id": "bazz", "title": "Bazz", "description": "Drop the bazz"},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Invalid X-Token header"}
|
||||
|
||||
|
||||
def test_create_existing_item():
|
||||
response = client.post(
|
||||
"/items/",
|
||||
headers={"X-Token": "coneofsilence"},
|
||||
json={
|
||||
"id": "foo",
|
||||
"title": "The Foo ID Stealers",
|
||||
"description": "There goes my stealer",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.json() == {"detail": "Item already exists"}
|
||||
27
docs_src/background_tasks/tutorial002_an.py
Normal file
27
docs_src/background_tasks/tutorial002_an.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from typing import Union
|
||||
|
||||
from fastapi import BackgroundTasks, Depends, FastAPI
|
||||
from typing_extensions import Annotated
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
def write_log(message: str):
|
||||
with open("log.txt", mode="a") as log:
|
||||
log.write(message)
|
||||
|
||||
|
||||
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
|
||||
if q:
|
||||
message = f"found query: {q}\n"
|
||||
background_tasks.add_task(write_log, message)
|
||||
return q
|
||||
|
||||
|
||||
@app.post("/send-notification/{email}")
|
||||
async def send_notification(
|
||||
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
|
||||
):
|
||||
message = f"message to {email}\n"
|
||||
background_tasks.add_task(write_log, message)
|
||||
return {"message": "Message sent"}
|
||||
26
docs_src/background_tasks/tutorial002_an_py310.py
Normal file
26
docs_src/background_tasks/tutorial002_an_py310.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import BackgroundTasks, Depends, FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
def write_log(message: str):
|
||||
with open("log.txt", mode="a") as log:
|
||||
log.write(message)
|
||||
|
||||
|
||||
def get_query(background_tasks: BackgroundTasks, q: str | None = None):
|
||||
if q:
|
||||
message = f"found query: {q}\n"
|
||||
background_tasks.add_task(write_log, message)
|
||||
return q
|
||||
|
||||
|
||||
@app.post("/send-notification/{email}")
|
||||
async def send_notification(
|
||||
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
|
||||
):
|
||||
message = f"message to {email}\n"
|
||||
background_tasks.add_task(write_log, message)
|
||||
return {"message": "Message sent"}
|
||||
26
docs_src/background_tasks/tutorial002_an_py39.py
Normal file
26
docs_src/background_tasks/tutorial002_an_py39.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from typing import Annotated, Union
|
||||
|
||||
from fastapi import BackgroundTasks, Depends, FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
def write_log(message: str):
|
||||
with open("log.txt", mode="a") as log:
|
||||
log.write(message)
|
||||
|
||||
|
||||
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
|
||||
if q:
|
||||
message = f"found query: {q}\n"
|
||||
background_tasks.add_task(write_log, message)
|
||||
return q
|
||||
|
||||
|
||||
@app.post("/send-notification/{email}")
|
||||
async def send_notification(
|
||||
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
|
||||
):
|
||||
message = f"message to {email}\n"
|
||||
background_tasks.add_task(write_log, message)
|
||||
return {"message": "Message sent"}
|
||||
0
docs_src/bigger_applications/app_an/__init__.py
Normal file
0
docs_src/bigger_applications/app_an/__init__.py
Normal file
12
docs_src/bigger_applications/app_an/dependencies.py
Normal file
12
docs_src/bigger_applications/app_an/dependencies.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from fastapi import Header, HTTPException
|
||||
from typing_extensions import Annotated
|
||||
|
||||
|
||||
async def get_token_header(x_token: Annotated[str, Header()]):
|
||||
if x_token != "fake-super-secret-token":
|
||||
raise HTTPException(status_code=400, detail="X-Token header invalid")
|
||||
|
||||
|
||||
async def get_query_token(token: str):
|
||||
if token != "jessica":
|
||||
raise HTTPException(status_code=400, detail="No Jessica token provided")
|
||||
8
docs_src/bigger_applications/app_an/internal/admin.py
Normal file
8
docs_src/bigger_applications/app_an/internal/admin.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def update_admin():
|
||||
return {"message": "Admin getting schwifty"}
|
||||
23
docs_src/bigger_applications/app_an/main.py
Normal file
23
docs_src/bigger_applications/app_an/main.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from fastapi import Depends, FastAPI
|
||||
|
||||
from .dependencies import get_query_token, get_token_header
|
||||
from .internal import admin
|
||||
from .routers import items, users
|
||||
|
||||
app = FastAPI(dependencies=[Depends(get_query_token)])
|
||||
|
||||
|
||||
app.include_router(users.router)
|
||||
app.include_router(items.router)
|
||||
app.include_router(
|
||||
admin.router,
|
||||
prefix="/admin",
|
||||
tags=["admin"],
|
||||
dependencies=[Depends(get_token_header)],
|
||||
responses={418: {"description": "I'm a teapot"}},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "Hello Bigger Applications!"}
|
||||
38
docs_src/bigger_applications/app_an/routers/items.py
Normal file
38
docs_src/bigger_applications/app_an/routers/items.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from ..dependencies import get_token_header
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/items",
|
||||
tags=["items"],
|
||||
dependencies=[Depends(get_token_header)],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def read_items():
|
||||
return fake_items_db
|
||||
|
||||
|
||||
@router.get("/{item_id}")
|
||||
async def read_item(item_id: str):
|
||||
if item_id not in fake_items_db:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return {"name": fake_items_db[item_id]["name"], "item_id": item_id}
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{item_id}",
|
||||
tags=["custom"],
|
||||
responses={403: {"description": "Operation forbidden"}},
|
||||
)
|
||||
async def update_item(item_id: str):
|
||||
if item_id != "plumbus":
|
||||
raise HTTPException(
|
||||
status_code=403, detail="You can only update the item: plumbus"
|
||||
)
|
||||
return {"item_id": item_id, "name": "The great Plumbus"}
|
||||
18
docs_src/bigger_applications/app_an/routers/users.py
Normal file
18
docs_src/bigger_applications/app_an/routers/users.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/users/", tags=["users"])
|
||||
async def read_users():
|
||||
return [{"username": "Rick"}, {"username": "Morty"}]
|
||||
|
||||
|
||||
@router.get("/users/me", tags=["users"])
|
||||
async def read_user_me():
|
||||
return {"username": "fakecurrentuser"}
|
||||
|
||||
|
||||
@router.get("/users/{username}", tags=["users"])
|
||||
async def read_user(username: str):
|
||||
return {"username": username}
|
||||
13
docs_src/bigger_applications/app_an_py39/dependencies.py
Normal file
13
docs_src/bigger_applications/app_an_py39/dependencies.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
|
||||
async def get_token_header(x_token: Annotated[str, Header()]):
|
||||
if x_token != "fake-super-secret-token":
|
||||
raise HTTPException(status_code=400, detail="X-Token header invalid")
|
||||
|
||||
|
||||
async def get_query_token(token: str):
|
||||
if token != "jessica":
|
||||
raise HTTPException(status_code=400, detail="No Jessica token provided")
|
||||
@@ -0,0 +1,8 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def update_admin():
|
||||
return {"message": "Admin getting schwifty"}
|
||||
23
docs_src/bigger_applications/app_an_py39/main.py
Normal file
23
docs_src/bigger_applications/app_an_py39/main.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from fastapi import Depends, FastAPI
|
||||
|
||||
from .dependencies import get_query_token, get_token_header
|
||||
from .internal import admin
|
||||
from .routers import items, users
|
||||
|
||||
app = FastAPI(dependencies=[Depends(get_query_token)])
|
||||
|
||||
|
||||
app.include_router(users.router)
|
||||
app.include_router(items.router)
|
||||
app.include_router(
|
||||
admin.router,
|
||||
prefix="/admin",
|
||||
tags=["admin"],
|
||||
dependencies=[Depends(get_token_header)],
|
||||
responses={418: {"description": "I'm a teapot"}},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "Hello Bigger Applications!"}
|
||||
38
docs_src/bigger_applications/app_an_py39/routers/items.py
Normal file
38
docs_src/bigger_applications/app_an_py39/routers/items.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from ..dependencies import get_token_header
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/items",
|
||||
tags=["items"],
|
||||
dependencies=[Depends(get_token_header)],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def read_items():
|
||||
return fake_items_db
|
||||
|
||||
|
||||
@router.get("/{item_id}")
|
||||
async def read_item(item_id: str):
|
||||
if item_id not in fake_items_db:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return {"name": fake_items_db[item_id]["name"], "item_id": item_id}
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{item_id}",
|
||||
tags=["custom"],
|
||||
responses={403: {"description": "Operation forbidden"}},
|
||||
)
|
||||
async def update_item(item_id: str):
|
||||
if item_id != "plumbus":
|
||||
raise HTTPException(
|
||||
status_code=403, detail="You can only update the item: plumbus"
|
||||
)
|
||||
return {"item_id": item_id, "name": "The great Plumbus"}
|
||||
18
docs_src/bigger_applications/app_an_py39/routers/users.py
Normal file
18
docs_src/bigger_applications/app_an_py39/routers/users.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/users/", tags=["users"])
|
||||
async def read_users():
|
||||
return [{"username": "Rick"}, {"username": "Morty"}]
|
||||
|
||||
|
||||
@router.get("/users/me", tags=["users"])
|
||||
async def read_user_me():
|
||||
return {"username": "fakecurrentuser"}
|
||||
|
||||
|
||||
@router.get("/users/{username}", tags=["users"])
|
||||
async def read_user(username: str):
|
||||
return {"username": username}
|
||||
22
docs_src/body_fields/tutorial001_an.py
Normal file
22
docs_src/body_fields/tutorial001_an.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from typing import Union
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel, Field
|
||||
from typing_extensions import Annotated
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = Field(
|
||||
default=None, title="The description of the item", max_length=300
|
||||
)
|
||||
price: float = Field(gt=0, description="The price must be greater than zero")
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
|
||||
results = {"item_id": item_id, "item": item}
|
||||
return results
|
||||
21
docs_src/body_fields/tutorial001_an_py310.py
Normal file
21
docs_src/body_fields/tutorial001_an_py310.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: str | None = Field(
|
||||
default=None, title="The description of the item", max_length=300
|
||||
)
|
||||
price: float = Field(gt=0, description="The price must be greater than zero")
|
||||
tax: float | None = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
|
||||
results = {"item_id": item_id, "item": item}
|
||||
return results
|
||||
21
docs_src/body_fields/tutorial001_an_py39.py
Normal file
21
docs_src/body_fields/tutorial001_an_py39.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from typing import Annotated, Union
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = Field(
|
||||
default=None, title="The description of the item", max_length=300
|
||||
)
|
||||
price: float = Field(gt=0, description="The price must be greater than zero")
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
|
||||
results = {"item_id": item_id, "item": item}
|
||||
return results
|
||||
28
docs_src/body_multiple_params/tutorial001_an.py
Normal file
28
docs_src/body_multiple_params/tutorial001_an.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from typing import Union
|
||||
|
||||
from fastapi import FastAPI, Path
|
||||
from pydantic import BaseModel
|
||||
from typing_extensions import Annotated
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = None
|
||||
price: float
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
|
||||
q: Union[str, None] = None,
|
||||
item: Union[Item, None] = None,
|
||||
):
|
||||
results = {"item_id": item_id}
|
||||
if q:
|
||||
results.update({"q": q})
|
||||
if item:
|
||||
results.update({"item": item})
|
||||
return results
|
||||
27
docs_src/body_multiple_params/tutorial001_an_py310.py
Normal file
27
docs_src/body_multiple_params/tutorial001_an_py310.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import FastAPI, Path
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: str | None = None
|
||||
price: float
|
||||
tax: float | None = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
|
||||
q: str | None = None,
|
||||
item: Item | None = None,
|
||||
):
|
||||
results = {"item_id": item_id}
|
||||
if q:
|
||||
results.update({"q": q})
|
||||
if item:
|
||||
results.update({"item": item})
|
||||
return results
|
||||
27
docs_src/body_multiple_params/tutorial001_an_py39.py
Normal file
27
docs_src/body_multiple_params/tutorial001_an_py39.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from typing import Annotated, Union
|
||||
|
||||
from fastapi import FastAPI, Path
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = None
|
||||
price: float
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
|
||||
q: Union[str, None] = None,
|
||||
item: Union[Item, None] = None,
|
||||
):
|
||||
results = {"item_id": item_id}
|
||||
if q:
|
||||
results.update({"q": q})
|
||||
if item:
|
||||
results.update({"item": item})
|
||||
return results
|
||||
27
docs_src/body_multiple_params/tutorial003_an.py
Normal file
27
docs_src/body_multiple_params/tutorial003_an.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from typing import Union
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel
|
||||
from typing_extensions import Annotated
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = None
|
||||
price: float
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
full_name: Union[str, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
|
||||
):
|
||||
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
|
||||
return results
|
||||
26
docs_src/body_multiple_params/tutorial003_an_py310.py
Normal file
26
docs_src/body_multiple_params/tutorial003_an_py310.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: str | None = None
|
||||
price: float
|
||||
tax: float | None = None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
full_name: str | None = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
|
||||
):
|
||||
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
|
||||
return results
|
||||
26
docs_src/body_multiple_params/tutorial003_an_py39.py
Normal file
26
docs_src/body_multiple_params/tutorial003_an_py39.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from typing import Annotated, Union
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = None
|
||||
price: float
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
full_name: Union[str, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
|
||||
):
|
||||
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
|
||||
return results
|
||||
34
docs_src/body_multiple_params/tutorial004_an.py
Normal file
34
docs_src/body_multiple_params/tutorial004_an.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from typing import Union
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel
|
||||
from typing_extensions import Annotated
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = None
|
||||
price: float
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
full_name: Union[str, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
*,
|
||||
item_id: int,
|
||||
item: Item,
|
||||
user: User,
|
||||
importance: Annotated[int, Body(gt=0)],
|
||||
q: Union[str, None] = None,
|
||||
):
|
||||
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
|
||||
if q:
|
||||
results.update({"q": q})
|
||||
return results
|
||||
33
docs_src/body_multiple_params/tutorial004_an_py310.py
Normal file
33
docs_src/body_multiple_params/tutorial004_an_py310.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: str | None = None
|
||||
price: float
|
||||
tax: float | None = None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
full_name: str | None = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
*,
|
||||
item_id: int,
|
||||
item: Item,
|
||||
user: User,
|
||||
importance: Annotated[int, Body(gt=0)],
|
||||
q: str | None = None,
|
||||
):
|
||||
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
|
||||
if q:
|
||||
results.update({"q": q})
|
||||
return results
|
||||
33
docs_src/body_multiple_params/tutorial004_an_py39.py
Normal file
33
docs_src/body_multiple_params/tutorial004_an_py39.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from typing import Annotated, Union
|
||||
|
||||
from fastapi import Body, FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = None
|
||||
price: float
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
username: str
|
||||
full_name: Union[str, None] = None
|
||||
|
||||
|
||||
@app.put("/items/{item_id}")
|
||||
async def update_item(
|
||||
*,
|
||||
item_id: int,
|
||||
item: Item,
|
||||
user: User,
|
||||
importance: Annotated[int, Body(gt=0)],
|
||||
q: Union[str, None] = None,
|
||||
):
|
||||
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
|
||||
if q:
|
||||
results.update({"q": q})
|
||||
return results
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user