diff --git a/README.md b/README.md
index 9ad50f271..5e9e97a2a 100644
--- a/README.md
+++ b/README.md
@@ -151,7 +151,7 @@ $ pip install "uvicorn[standard]"
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -164,7 +164,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -174,7 +174,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -187,7 +187,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -266,7 +266,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -277,7 +277,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -286,7 +286,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md
index ce13bcc4a..929754462 100644
--- a/docs/de/docs/index.md
+++ b/docs/de/docs/index.md
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -162,7 +162,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -185,7 +185,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -284,7 +284,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md
index 37ec283ff..b61f88b93 100644
--- a/docs/en/docs/advanced/additional-status-codes.md
+++ b/docs/en/docs/advanced/additional-status-codes.md
@@ -14,7 +14,7 @@ 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 23"
+```Python hl_lines="4 25"
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md
index 79208e8dc..7bba82fb7 100644
--- a/docs/en/docs/advanced/testing-dependencies.md
+++ b/docs/en/docs/advanced/testing-dependencies.md
@@ -28,7 +28,7 @@ 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="26-27 30"
+```Python hl_lines="28-29 32"
{!../../../docs_src/dependency_testing/tutorial001.py!}
```
diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md
index 651b0e840..8a542622e 100644
--- a/docs/en/docs/deployment/docker.md
+++ b/docs/en/docs/deployment/docker.md
@@ -142,7 +142,7 @@ Successfully installed fastapi pydantic uvicorn
* Create a `main.py` file with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -155,7 +155,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md
index 7de1e50df..17163ba01 100644
--- a/docs/en/docs/index.md
+++ b/docs/en/docs/index.md
@@ -148,7 +148,7 @@ $ pip install "uvicorn[standard]"
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -161,7 +161,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -171,7 +171,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -184,7 +184,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -263,7 +263,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -274,7 +274,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -283,7 +283,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md
index 8486ed849..963fcaf1c 100644
--- a/docs/en/docs/python-types.md
+++ b/docs/en/docs/python-types.md
@@ -317,6 +317,45 @@ This also means that in Python 3.10, you can use `Something | None`:
{!> ../../../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:
+
+* 🚨 Avoid using `Optional[SomeType]`
+* Instead ✨ **use `Union[SomeType, None]`** ✨.
+
+Both are equivalent and underneath they are the same, but I would recommend `Union` instead of `Optional` because the word "**optional**" would seem to imply that the value is optional, and it actually means "it can be `None`", even if it's not optional and is still required.
+
+I think `Union[str, SomeType]` is more explicit about what it means.
+
+It's just about the words and names. But those words can affect how you and your teammates think about the code.
+
+As an example, let's take this function:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial009c.py!}
+```
+
+The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:
+
+```Python
+say_hi() # Oh, no, this throws an error! 😱
+```
+
+The `name` parameter is **still required** (not *optional*) because it doesn't have a default value. Still, `name` accepts `None` as the value:
+
+```Python
+say_hi(name=None) # This works, None is valid 🎉
+```
+
+The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types:
+
+```Python hl_lines="1 4"
+{!../../../docs_src/python_types/tutorial009c_py310.py!}
+```
+
+And then you won't have to worry about names like `Optional` and `Union`. 😎
+
#### Generic types
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
@@ -422,6 +461,9 @@ An example from the official Pydantic docs:
You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+!!! 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 Required Optional fields.
+
## Type hints in **FastAPI**
**FastAPI** takes advantage of these type hints to do several things.
diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md
index 13de4c8ea..31dd27fed 100644
--- a/docs/en/docs/tutorial/body-multiple-params.md
+++ b/docs/en/docs/tutorial/body-multiple-params.md
@@ -89,13 +89,13 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`:
=== "Python 3.6 and above"
- ```Python hl_lines="23"
+ ```Python hl_lines="22"
{!> ../../../docs_src/body_multiple_params/tutorial003.py!}
```
=== "Python 3.10 and above"
- ```Python hl_lines="21"
+ ```Python hl_lines="20"
{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
```
@@ -126,7 +126,7 @@ Of course, you can also declare additional query parameters whenever you need, a
As, by default, singular values are interpreted as query parameters, you don't have to explicitly add a `Query`, you can just do:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
Or in Python 3.10 and above:
@@ -139,7 +139,7 @@ For example:
=== "Python 3.6 and above"
- ```Python hl_lines="28"
+ ```Python hl_lines="27"
{!> ../../../docs_src/body_multiple_params/tutorial004.py!}
```
@@ -152,7 +152,6 @@ For example:
!!! info
`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
-
## Embed a single body parameter
Let's say you only have a single `item` body parameter from a Pydantic model `Item`.
@@ -162,7 +161,7 @@ By default, **FastAPI** will then expect its body directly.
But if you want it to expect a JSON with a key `item` and inside of it the model contents, as it does when you declare extra body parameters, you can use the special `Body` parameter `embed`:
```Python
-item: Item = Body(..., embed=True)
+item: Item = Body(embed=True)
```
as in:
diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md
index eb21f29a8..509005936 100644
--- a/docs/en/docs/tutorial/body.md
+++ b/docs/en/docs/tutorial/body.md
@@ -206,7 +206,7 @@ The function parameters will be recognized as follows:
!!! note
FastAPI will know that the value of `q` is not required because of the default value `= None`.
- The `Optional` in `Optional[str]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
+ The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
## Without Pydantic
diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
index 663fff15b..fb41ba1f6 100644
--- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -109,7 +109,7 @@ Pay attention to the `__init__` method used to create the instance of the class:
=== "Python 3.6 and above"
- ```Python hl_lines="8"
+ ```Python hl_lines="9"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md
index fe10facfb..5078c0096 100644
--- a/docs/en/docs/tutorial/dependencies/index.md
+++ b/docs/en/docs/tutorial/dependencies/index.md
@@ -33,7 +33,7 @@ It is just a function that can take all the same parameters that a *path operati
=== "Python 3.6 and above"
- ```Python hl_lines="8-9"
+ ```Python hl_lines="8-11"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
@@ -81,7 +81,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p
=== "Python 3.6 and above"
- ```Python hl_lines="13 18"
+ ```Python hl_lines="15 20"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
index 51531228d..a5b40c9ad 100644
--- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
@@ -55,7 +55,7 @@ Then we can use the dependency with:
=== "Python 3.6 and above"
- ```Python hl_lines="21"
+ ```Python hl_lines="22"
{!> ../../../docs_src/dependencies/tutorial005.py!}
```
diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md
index 31bf91a0e..29235c6e2 100644
--- a/docs/en/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/en/docs/tutorial/path-params-numeric-validations.md
@@ -59,7 +59,7 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
So, you can declare your function as:
-```Python hl_lines="8"
+```Python hl_lines="7"
{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
@@ -71,7 +71,7 @@ Pass `*`, as the first parameter of the function.
Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs
. Even if they don't have a default value.
-```Python hl_lines="8"
+```Python hl_lines="7"
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index c751a9256..e371e86e4 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -162,7 +162,7 @@ Your response model could have default values, like:
{!> ../../../docs_src/response_model/tutorial004_py310.py!}
```
-* `description: Optional[str] = None` has a default of `None`.
+* `description: Union[str, None] = None` has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
* `tags: List[str] = []` as a default of an empty list: `[]`.
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index c69df51dc..94347018d 100644
--- a/docs/en/docs/tutorial/schema-extra-example.md
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -68,13 +68,13 @@ Here we pass an `example` of the data expected in `Body()`:
=== "Python 3.6 and above"
- ```Python hl_lines="21-26"
+ ```Python hl_lines="20-25"
{!> ../../../docs_src/schema_extra_example/tutorial003.py!}
```
=== "Python 3.10 and above"
- ```Python hl_lines="19-24"
+ ```Python hl_lines="18-23"
{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
```
@@ -99,13 +99,13 @@ Each specific example `dict` in the `examples` can contain:
=== "Python 3.6 and above"
- ```Python hl_lines="22-48"
+ ```Python hl_lines="21-47"
{!> ../../../docs_src/schema_extra_example/tutorial004.py!}
```
=== "Python 3.10 and above"
- ```Python hl_lines="20-46"
+ ```Python hl_lines="19-45"
{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
```
diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md
index 67224fb36..1f28ea85b 100644
--- a/docs/es/docs/advanced/additional-status-codes.md
+++ b/docs/es/docs/advanced/additional-status-codes.md
@@ -14,7 +14,7 @@ Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan ant
Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras:
-```Python hl_lines="2 19"
+```Python hl_lines="4 25"
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md
index 1fa79fdde..ef4850b56 100644
--- a/docs/es/docs/index.md
+++ b/docs/es/docs/index.md
@@ -145,7 +145,7 @@ $ pip install uvicorn[standard]
```Python
from fastapi import FastAPI
-from typing import Optional
+from typing import Union
app = FastAPI()
@@ -156,7 +156,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -167,7 +167,7 @@ Si tu código usa `async` / `await`, usa `async def`:
```Python hl_lines="7 12"
from fastapi import FastAPI
-from typing import Optional
+from typing import Union
app = FastAPI()
@@ -178,7 +178,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -259,7 +259,7 @@ Declara el body usando las declaraciones de tipo estándares de Python gracias a
```Python hl_lines="2 7-10 23-25"
from fastapi import FastAPI
from pydantic import BaseModel
-from typing import Optional
+from typing import Union
app = FastAPI()
@@ -267,7 +267,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -276,7 +276,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md
index 69caee6e8..482af8dc0 100644
--- a/docs/es/docs/tutorial/query-params.md
+++ b/docs/es/docs/tutorial/query-params.md
@@ -75,7 +75,7 @@ En este caso el parámetro de la función `q` será opcional y será `None` por
!!! note "Nota"
FastAPI sabrá que `q` es opcional por el `= None`.
- El `Optional` en `Optional[str]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Optional[str]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
+ El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
## Conversión de tipos de parámetros de query
diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md
index 0070de179..fd52f994c 100644
--- a/docs/fa/docs/index.md
+++ b/docs/fa/docs/index.md
@@ -152,7 +152,7 @@ $ pip install "uvicorn[standard]"
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -165,7 +165,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -175,7 +175,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -188,7 +188,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -267,7 +267,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -278,7 +278,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -287,7 +287,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md
index 0b537054e..f713ee96b 100644
--- a/docs/fr/docs/index.md
+++ b/docs/fr/docs/index.md
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -162,7 +162,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -185,7 +185,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9 10 11 12 25 26 27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -284,7 +284,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md
index 6c03cd92b..d1f8e6451 100644
--- a/docs/ja/docs/advanced/additional-status-codes.md
+++ b/docs/ja/docs/advanced/additional-status-codes.md
@@ -14,7 +14,7 @@
これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
-```Python hl_lines="4 23"
+```Python hl_lines="4 25"
{!../../../docs_src/additional_status_codes/tutorial001.py!}
```
diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md
index ff0af725f..8d375d7ce 100644
--- a/docs/ja/docs/tutorial/query-params-str-validations.md
+++ b/docs/ja/docs/tutorial/query-params-str-validations.md
@@ -34,12 +34,12 @@
{!../../../docs_src/query_params_str_validations/tutorial002.py!}
```
-デフォルト値`None`を`Query(None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。
+デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。
なので:
```Python
-q: Optional[str] = Query(None)
+q: Optional[str] = Query(default=None)
```
...を以下と同じようにパラメータをオプションにします:
@@ -60,7 +60,7 @@ q: Optional[str] = None
もしくは:
```Python
- = Query(None)
+ = Query(default=None)
```
そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
@@ -70,7 +70,7 @@ q: Optional[str] = None
そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。
```Python
-q: str = Query(None, max_length=50)
+q: Union[str, None] = Query(default=None, max_length=50)
```
これにより、データを検証し、データが有効でない場合は明確なエラーを表示し、OpenAPIスキーマの *path operation* にパラメータを記載します。
@@ -79,7 +79,7 @@ q: str = Query(None, max_length=50)
パラメータ`min_length`も追加することができます:
-```Python hl_lines="9"
+```Python hl_lines="10"
{!../../../docs_src/query_params_str_validations/tutorial003.py!}
```
@@ -87,7 +87,7 @@ q: str = Query(None, max_length=50)
パラメータが一致するべき正規表現を定義することができます:
-```Python hl_lines="10"
+```Python hl_lines="11"
{!../../../docs_src/query_params_str_validations/tutorial004.py!}
```
@@ -125,13 +125,13 @@ q: str
以下の代わりに:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
現在は以下の例のように`Query`で宣言しています:
```Python
-q: Optional[str] = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
```
そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます:
diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md
index 284628955..ec4422994 100644
--- a/docs/ko/docs/index.md
+++ b/docs/ko/docs/index.md
@@ -145,7 +145,7 @@ $ pip install uvicorn[standard]
* `main.py` 파일을 만드십시오:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -158,7 +158,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -168,7 +168,7 @@ def read_item(item_id: int, q: Optional[str] = None):
여러분의 코드가 `async` / `await`을 사용한다면, `async def`를 사용하십시오.
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -181,7 +181,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -260,7 +260,7 @@ INFO: Application startup complete.
Pydantic을 이용해 파이썬 표준 타입으로 본문을 선언합니다.
```Python hl_lines="4 9 10 11 12 25 26 27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -271,7 +271,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -280,7 +280,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md
index abb9d03db..cadf543fc 100644
--- a/docs/ko/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md
@@ -43,7 +43,7 @@
따라서 함수를 다음과 같이 선언 할 수 있습니다:
-```Python hl_lines="8"
+```Python hl_lines="7"
{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
@@ -55,7 +55,7 @@
파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs
로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다.
-```Python hl_lines="8"
+```Python hl_lines="7"
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md
index 05f2ff9c9..bb631e6ff 100644
--- a/docs/ko/docs/tutorial/query-params.md
+++ b/docs/ko/docs/tutorial/query-params.md
@@ -75,7 +75,7 @@ http://127.0.0.1:8000/items/?skip=20
!!! note "참고"
FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다.
- `Optional[str]`에 있는 `Optional`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Optional[str]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
+ `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
## 쿼리 매개변수 형변환
diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md
index 0070de179..fd52f994c 100644
--- a/docs/nl/docs/index.md
+++ b/docs/nl/docs/index.md
@@ -152,7 +152,7 @@ $ pip install "uvicorn[standard]"
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -165,7 +165,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -175,7 +175,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -188,7 +188,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -267,7 +267,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -278,7 +278,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -287,7 +287,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md
index 4a300ae63..bbe1b1ad1 100644
--- a/docs/pl/docs/index.md
+++ b/docs/pl/docs/index.md
@@ -144,7 +144,7 @@ $ pip install uvicorn[standard]
* Utwórz plik o nazwie `main.py` z:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -157,7 +157,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -167,7 +167,7 @@ def read_item(item_id: int, q: Optional[str] = None):
Jeżeli twój kod korzysta z `async` / `await`, użyj `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -180,7 +180,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -258,7 +258,7 @@ Zmodyfikuj teraz plik `main.py`, aby otrzmywał treść (body) żądania `PUT`.
Zadeklaruj treść żądania, używając standardowych typów w Pythonie dzięki Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -269,7 +269,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -278,7 +278,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md
index c1a0dbf0d..b1d0c89f2 100644
--- a/docs/pt/docs/index.md
+++ b/docs/pt/docs/index.md
@@ -138,7 +138,7 @@ $ pip install uvicorn[standard]
* Crie um arquivo `main.py` com:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -151,7 +151,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -161,7 +161,7 @@ def read_item(item_id: int, q: Optional[str] = None):
Se seu código utiliza `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -174,7 +174,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -253,6 +253,8 @@ Agora modifique o arquivo `main.py` para receber um corpo para uma requisição
Declare o corpo utilizando tipos padrão Python, graças ao Pydantic.
```Python hl_lines="4 9-12 25-27"
+from typing import Union
+
from fastapi import FastAPI
from pydantic import BaseModel
@@ -262,7 +264,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool] = None
@app.get("/")
@@ -271,7 +273,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md
index 5abc91177..99e05ab77 100644
--- a/docs/pt/docs/tutorial/body.md
+++ b/docs/pt/docs/tutorial/body.md
@@ -158,7 +158,7 @@ Os parâmetros da função serão reconhecidos conforme abaixo:
!!! note "Observação"
O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
- O `Optional` em `Optional[str]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
+ O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
## Sem o Pydantic
diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md
index baac5f493..9a9e071db 100644
--- a/docs/pt/docs/tutorial/query-params-str-validations.md
+++ b/docs/pt/docs/tutorial/query-params-str-validations.md
@@ -8,12 +8,12 @@ Vamos utilizar essa aplicação como exemplo:
{!../../../docs_src/query_params_str_validations/tutorial001.py!}
```
-O parâmetro de consulta `q` é do tipo `Optional[str]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório.
+O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório.
!!! note "Observação"
O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
- O `Optional` em `Optional[str]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
+ O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
## Validação adicional
@@ -35,18 +35,18 @@ Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `ma
{!../../../docs_src/query_params_str_validations/tutorial002.py!}
```
-Note que substituímos o valor padrão de `None` para `Query(None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro.
+Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro.
Então:
```Python
-q: Optional[str] = Query(None)
+q: Union[str, None] = Query(default=None)
```
...Torna o parâmetro opcional, da mesma maneira que:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
Mas o declara explicitamente como um parâmetro de consulta.
@@ -61,17 +61,17 @@ Mas o declara explicitamente como um parâmetro de consulta.
Ou com:
```Python
- = Query(None)
+ = Query(default=None)
```
E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório.
- O `Optional` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
+ O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos:
```Python
-q: str = Query(None, max_length=50)
+q: str = Query(default=None, max_length=50)
```
Isso irá validar os dados, mostrar um erro claro quando os dados forem inválidos, e documentar o parâmetro na *operação de rota* do esquema OpenAPI..
@@ -80,7 +80,7 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid
Você também pode incluir um parâmetro `min_length`:
-```Python hl_lines="9"
+```Python hl_lines="10"
{!../../../docs_src/query_params_str_validations/tutorial003.py!}
```
@@ -88,7 +88,7 @@ Você também pode incluir um parâmetro `min_length`:
Você pode definir uma expressão regular que combine com um padrão esperado pelo parâmetro:
-```Python hl_lines="10"
+```Python hl_lines="11"
{!../../../docs_src/query_params_str_validations/tutorial004.py!}
```
@@ -126,13 +126,13 @@ q: str
em vez desta:
```Python
-q: Optional[str] = None
+q: Union[str, None] = None
```
Mas agora nós o estamos declarando como `Query`, conforme abaixo:
```Python
-q: Optional[str] = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
```
Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento:
diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md
index a1d302276..9a3957d5f 100644
--- a/docs/ru/docs/index.md
+++ b/docs/ru/docs/index.md
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -162,7 +162,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -185,7 +185,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -284,7 +284,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/sq/docs/index.md b/docs/sq/docs/index.md
index 0bb7b55e3..29f92e020 100644
--- a/docs/sq/docs/index.md
+++ b/docs/sq/docs/index.md
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
* Create a file `main.py` with:
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -162,7 +162,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
If your code uses `async` / `await`, use `async def`:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -185,7 +185,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
Declare the body using standard Python types, thanks to Pydantic.
```Python hl_lines="4 9-12 25-27"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
- is_offer: Optional[bool] = None
+ is_offer: Union[bool, None] = None
@app.get("/")
@@ -284,7 +284,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md
index 3195cd440..5693029b5 100644
--- a/docs/tr/docs/index.md
+++ b/docs/tr/docs/index.md
@@ -157,7 +157,7 @@ $ pip install uvicorn[standard]
* `main.py` adında bir dosya oluştur :
```Python
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -170,7 +170,7 @@ def read_root():
@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -180,7 +180,7 @@ def read_item(item_id: int, q: Optional[str] = None):
Eğer kodunda `async` / `await` var ise, `async def` kullan:
```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -193,7 +193,7 @@ async def read_root():
@app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
```
@@ -272,7 +272,7 @@ Senin için alternatif olarak (kwargs
,来调用。即使它们没有默认值。
-```Python hl_lines="8"
+```Python hl_lines="7"
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md
index 1d1d383d4..0b2b9446a 100644
--- a/docs/zh/docs/tutorial/query-params-str-validations.md
+++ b/docs/zh/docs/tutorial/query-params-str-validations.md
@@ -30,12 +30,12 @@
{!../../../docs_src/query_params_str_validations/tutorial002.py!}
```
-由于我们必须用 `Query(None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。
+由于我们必须用 `Query(default=None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。
所以:
```Python
-q: str = Query(None)
+q: Union[str, None] = Query(default=None)
```
...使得参数可选,等同于:
@@ -49,7 +49,7 @@ q: str = None
然后,我们可以将更多的参数传递给 `Query`。在本例中,适用于字符串的 `max_length` 参数:
```Python
-q: str = Query(None, max_length=50)
+q: Union[str, None] = Query(default=None, max_length=50)
```
将会校验数据,在数据无效时展示清晰的错误信息,并在 OpenAPI 模式的*路径操作*中记录该参数。
@@ -58,7 +58,7 @@ q: str = Query(None, max_length=50)
你还可以添加 `min_length` 参数:
-```Python hl_lines="9"
+```Python hl_lines="10"
{!../../../docs_src/query_params_str_validations/tutorial003.py!}
```
@@ -66,7 +66,7 @@ q: str = Query(None, max_length=50)
你可以定义一个参数值必须匹配的正则表达式:
-```Python hl_lines="10"
+```Python hl_lines="11"
{!../../../docs_src/query_params_str_validations/tutorial004.py!}
```
@@ -110,7 +110,7 @@ q: str = None
但是现在我们正在用 `Query` 声明它,例如:
```Python
-q: str = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
```
因此,当你在使用 `Query` 且需要声明一个值是必需的时,可以将 `...` 用作第一个参数值:
diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md
index 59a7c17d5..ea3d0666d 100644
--- a/docs/zh/docs/tutorial/response-model.md
+++ b/docs/zh/docs/tutorial/response-model.md
@@ -94,7 +94,7 @@ FastAPI 将使用此 `response_model` 来:
{!../../../docs_src/response_model/tutorial004.py!}
```
-* `description: Optional[str] = None` 具有默认值 `None`。
+* `description: Union[str, None] = None` 具有默认值 `None`。
* `tax: float = 10.5` 具有默认值 `10.5`.
* `tags: List[str] = []` 具有一个空列表作为默认值: `[]`.
diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md
index 6482366b0..8f5fbfe70 100644
--- a/docs/zh/docs/tutorial/schema-extra-example.md
+++ b/docs/zh/docs/tutorial/schema-extra-example.md
@@ -33,7 +33,7 @@
比如,你可以将请求体的一个 `example` 传递给 `Body`:
-```Python hl_lines="21-26"
+```Python hl_lines="20-25"
{!../../../docs_src/schema_extra_example/tutorial003.py!}
```
diff --git a/docs_src/additional_responses/tutorial002.py b/docs_src/additional_responses/tutorial002.py
index a46e95959..bd0c95704 100644
--- a/docs_src/additional_responses/tutorial002.py
+++ b/docs_src/additional_responses/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
@@ -23,7 +23,7 @@ app = FastAPI()
}
},
)
-async def read_item(item_id: str, img: Optional[bool] = None):
+async def read_item(item_id: str, img: Union[bool, None] = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
diff --git a/docs_src/additional_responses/tutorial004.py b/docs_src/additional_responses/tutorial004.py
index 361aecb8e..978bc18c1 100644
--- a/docs_src/additional_responses/tutorial004.py
+++ b/docs_src/additional_responses/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
@@ -25,7 +25,7 @@ app = FastAPI()
response_model=Item,
responses={**responses, 200: {"content": {"image/png": {}}}},
)
-async def read_item(item_id: str, img: Optional[bool] = None):
+async def read_item(item_id: str, img: Union[bool, None] = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
diff --git a/docs_src/background_tasks/tutorial002.py b/docs_src/background_tasks/tutorial002.py
index e7517e8cd..2e1b2f6c6 100644
--- a/docs_src/background_tasks/tutorial002.py
+++ b/docs_src/background_tasks/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import BackgroundTasks, Depends, FastAPI
@@ -10,7 +10,7 @@ def write_log(message: str):
log.write(message)
-def get_query(background_tasks: BackgroundTasks, q: Optional[str] = None):
+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)
diff --git a/docs_src/body/tutorial001.py b/docs_src/body/tutorial001.py
index 52144bd2b..f93317274 100644
--- a/docs_src/body/tutorial001.py
+++ b/docs_src/body/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -6,9 +6,9 @@ from pydantic import BaseModel
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
app = FastAPI()
diff --git a/docs_src/body/tutorial002.py b/docs_src/body/tutorial002.py
index 644fabae9..7f5183908 100644
--- a/docs_src/body/tutorial002.py
+++ b/docs_src/body/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -6,9 +6,9 @@ from pydantic import BaseModel
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
app = FastAPI()
diff --git a/docs_src/body/tutorial003.py b/docs_src/body/tutorial003.py
index c99ea694b..89a6b833c 100644
--- a/docs_src/body/tutorial003.py
+++ b/docs_src/body/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -6,9 +6,9 @@ from pydantic import BaseModel
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
app = FastAPI()
diff --git a/docs_src/body/tutorial004.py b/docs_src/body/tutorial004.py
index 7a222a390..e2df0df2b 100644
--- a/docs_src/body/tutorial004.py
+++ b/docs_src/body/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -6,16 +6,16 @@ from pydantic import BaseModel
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
app = FastAPI()
@app.put("/items/{item_id}")
-async def create_item(item_id: int, item: Item, q: Optional[str] = None):
+async def create_item(item_id: int, item: Item, q: Union[str, None] = None):
result = {"item_id": item_id, **item.dict()}
if q:
result.update({"q": q})
diff --git a/docs_src/body_multiple_params/tutorial002.py b/docs_src/body_multiple_params/tutorial002.py
index 6b8748420..2d7160ae8 100644
--- a/docs_src/body_multiple_params/tutorial002.py
+++ b/docs_src/body_multiple_params/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,14 +8,14 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
class User(BaseModel):
username: str
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/body_nested_models/tutorial001.py b/docs_src/body_nested_models/tutorial001.py
index fe14fdf93..37ef6dda5 100644
--- a/docs_src/body_nested_models/tutorial001.py
+++ b/docs_src/body_nested_models/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: list = []
diff --git a/docs_src/body_nested_models/tutorial002.py b/docs_src/body_nested_models/tutorial002.py
index 1770516a4..155cff788 100644
--- a/docs_src/body_nested_models/tutorial002.py
+++ b/docs_src/body_nested_models/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: List[str] = []
diff --git a/docs_src/body_nested_models/tutorial002_py39.py b/docs_src/body_nested_models/tutorial002_py39.py
index af523a74e..8a93a7233 100644
--- a/docs_src/body_nested_models/tutorial002_py39.py
+++ b/docs_src/body_nested_models/tutorial002_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: list[str] = []
diff --git a/docs_src/body_nested_models/tutorial003.py b/docs_src/body_nested_models/tutorial003.py
index 33dbbe3a9..84ed18bf4 100644
--- a/docs_src/body_nested_models/tutorial003.py
+++ b/docs_src/body_nested_models/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
diff --git a/docs_src/body_nested_models/tutorial003_py39.py b/docs_src/body_nested_models/tutorial003_py39.py
index 931d92f88..b590ece36 100644
--- a/docs_src/body_nested_models/tutorial003_py39.py
+++ b/docs_src/body_nested_models/tutorial003_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
diff --git a/docs_src/body_nested_models/tutorial004.py b/docs_src/body_nested_models/tutorial004.py
index 311a4e73f..a07bfacac 100644
--- a/docs_src/body_nested_models/tutorial004.py
+++ b/docs_src/body_nested_models/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -13,11 +13,11 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
- image: Optional[Image] = None
+ image: Union[Image, None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/body_nested_models/tutorial004_py39.py b/docs_src/body_nested_models/tutorial004_py39.py
index ab05da023..dc2b175fb 100644
--- a/docs_src/body_nested_models/tutorial004_py39.py
+++ b/docs_src/body_nested_models/tutorial004_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -13,11 +13,11 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
- image: Optional[Image] = None
+ image: Union[Image, None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/body_nested_models/tutorial005.py b/docs_src/body_nested_models/tutorial005.py
index e76498c3b..5a01264ed 100644
--- a/docs_src/body_nested_models/tutorial005.py
+++ b/docs_src/body_nested_models/tutorial005.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
- image: Optional[Image] = None
+ image: Union[Image, None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/body_nested_models/tutorial005_py39.py b/docs_src/body_nested_models/tutorial005_py39.py
index 504551883..47db90008 100644
--- a/docs_src/body_nested_models/tutorial005_py39.py
+++ b/docs_src/body_nested_models/tutorial005_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
- image: Optional[Image] = None
+ image: Union[Image, None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/body_nested_models/tutorial006.py b/docs_src/body_nested_models/tutorial006.py
index da7836715..75f1f30e3 100644
--- a/docs_src/body_nested_models/tutorial006.py
+++ b/docs_src/body_nested_models/tutorial006.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Set
+from typing import List, Set, Union
from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
- images: Optional[List[Image]] = None
+ images: Union[List[Image], None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/body_nested_models/tutorial006_py39.py b/docs_src/body_nested_models/tutorial006_py39.py
index 61898178e..b14409703 100644
--- a/docs_src/body_nested_models/tutorial006_py39.py
+++ b/docs_src/body_nested_models/tutorial006_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
- images: Optional[list[Image]] = None
+ images: Union[list[Image], None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/body_nested_models/tutorial007.py b/docs_src/body_nested_models/tutorial007.py
index dfbbeaab1..641f09dce 100644
--- a/docs_src/body_nested_models/tutorial007.py
+++ b/docs_src/body_nested_models/tutorial007.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Set
+from typing import List, Set, Union
from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl
@@ -13,16 +13,16 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
- images: Optional[List[Image]] = None
+ images: Union[List[Image], None] = None
class Offer(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
items: List[Item]
diff --git a/docs_src/body_nested_models/tutorial007_py39.py b/docs_src/body_nested_models/tutorial007_py39.py
index 0c7d32fbb..59cf01e23 100644
--- a/docs_src/body_nested_models/tutorial007_py39.py
+++ b/docs_src/body_nested_models/tutorial007_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, HttpUrl
@@ -13,16 +13,16 @@ class Image(BaseModel):
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
- images: Optional[list[Image]] = None
+ images: Union[list[Image], None] = None
class Offer(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
items: list[Item]
diff --git a/docs_src/body_updates/tutorial001.py b/docs_src/body_updates/tutorial001.py
index 9b8f3ccf1..4e65d77e2 100644
--- a/docs_src/body_updates/tutorial001.py
+++ b/docs_src/body_updates/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
- name: Optional[str] = None
- description: Optional[str] = None
- price: Optional[float] = None
+ name: Union[str, None] = None
+ description: Union[str, None] = None
+ price: Union[float, None] = None
tax: float = 10.5
tags: List[str] = []
diff --git a/docs_src/body_updates/tutorial001_py39.py b/docs_src/body_updates/tutorial001_py39.py
index 5d5388b56..999bcdb82 100644
--- a/docs_src/body_updates/tutorial001_py39.py
+++ b/docs_src/body_updates/tutorial001_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
- name: Optional[str] = None
- description: Optional[str] = None
- price: Optional[float] = None
+ name: Union[str, None] = None
+ description: Union[str, None] = None
+ price: Union[float, None] = None
tax: float = 10.5
tags: list[str] = []
diff --git a/docs_src/body_updates/tutorial002.py b/docs_src/body_updates/tutorial002.py
index 46d27e67e..c3a0fe79e 100644
--- a/docs_src/body_updates/tutorial002.py
+++ b/docs_src/body_updates/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
- name: Optional[str] = None
- description: Optional[str] = None
- price: Optional[float] = None
+ name: Union[str, None] = None
+ description: Union[str, None] = None
+ price: Union[float, None] = None
tax: float = 10.5
tags: List[str] = []
diff --git a/docs_src/body_updates/tutorial002_py39.py b/docs_src/body_updates/tutorial002_py39.py
index ab85bd5ae..eb35b3521 100644
--- a/docs_src/body_updates/tutorial002_py39.py
+++ b/docs_src/body_updates/tutorial002_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
- name: Optional[str] = None
- description: Optional[str] = None
- price: Optional[float] = None
+ name: Union[str, None] = None
+ description: Union[str, None] = None
+ price: Union[float, None] = None
tax: float = 10.5
tags: list[str] = []
diff --git a/docs_src/dataclasses/tutorial001.py b/docs_src/dataclasses/tutorial001.py
index 43015eb27..2954c391f 100644
--- a/docs_src/dataclasses/tutorial001.py
+++ b/docs_src/dataclasses/tutorial001.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -8,8 +8,8 @@ from fastapi import FastAPI
class Item:
name: str
price: float
- description: Optional[str] = None
- tax: Optional[float] = None
+ description: Union[str, None] = None
+ tax: Union[float, None] = None
app = FastAPI()
diff --git a/docs_src/dataclasses/tutorial002.py b/docs_src/dataclasses/tutorial002.py
index aaa7b8799..08a238080 100644
--- a/docs_src/dataclasses/tutorial002.py
+++ b/docs_src/dataclasses/tutorial002.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI
@@ -9,8 +9,8 @@ class Item:
name: str
price: float
tags: List[str] = field(default_factory=list)
- description: Optional[str] = None
- tax: Optional[float] = None
+ description: Union[str, None] = None
+ tax: Union[float, None] = None
app = FastAPI()
diff --git a/docs_src/dataclasses/tutorial003.py b/docs_src/dataclasses/tutorial003.py
index 2c1fccdd7..34ce1199e 100644
--- a/docs_src/dataclasses/tutorial003.py
+++ b/docs_src/dataclasses/tutorial003.py
@@ -1,5 +1,5 @@
from dataclasses import field # (1)
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI
from pydantic.dataclasses import dataclass # (2)
@@ -8,7 +8,7 @@ from pydantic.dataclasses import dataclass # (2)
@dataclass
class Item:
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
@dataclass
diff --git a/docs_src/dependencies/tutorial001.py b/docs_src/dependencies/tutorial001.py
index a9da971dc..b1275103a 100644
--- a/docs_src/dependencies/tutorial001.py
+++ b/docs_src/dependencies/tutorial001.py
@@ -1,11 +1,13 @@
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI
app = FastAPI()
-async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
+async def common_parameters(
+ q: Union[str, None] = None, skip: int = 0, limit: int = 100
+):
return {"q": q, "skip": skip, "limit": limit}
diff --git a/docs_src/dependencies/tutorial002.py b/docs_src/dependencies/tutorial002.py
index 458f6b5bb..8e863e4fa 100644
--- a/docs_src/dependencies/tutorial002.py
+++ b/docs_src/dependencies/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI
@@ -9,7 +9,7 @@ fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"
class CommonQueryParams:
- def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
+ def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
diff --git a/docs_src/dependencies/tutorial003.py b/docs_src/dependencies/tutorial003.py
index 3f3e940f8..34614e539 100644
--- a/docs_src/dependencies/tutorial003.py
+++ b/docs_src/dependencies/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI
@@ -9,7 +9,7 @@ fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"
class CommonQueryParams:
- def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
+ def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
diff --git a/docs_src/dependencies/tutorial004.py b/docs_src/dependencies/tutorial004.py
index daa7b4670..d9fe88148 100644
--- a/docs_src/dependencies/tutorial004.py
+++ b/docs_src/dependencies/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI
@@ -9,7 +9,7 @@ fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"
class CommonQueryParams:
- def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
+ def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
diff --git a/docs_src/dependencies/tutorial005.py b/docs_src/dependencies/tutorial005.py
index 24f73c617..697332b5b 100644
--- a/docs_src/dependencies/tutorial005.py
+++ b/docs_src/dependencies/tutorial005.py
@@ -1,16 +1,17 @@
-from typing import Optional
+from typing import Union
from fastapi import Cookie, Depends, FastAPI
app = FastAPI()
-def query_extractor(q: Optional[str] = None):
+def query_extractor(q: Union[str, None] = None):
return q
def query_or_cookie_extractor(
- q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(default=None)
+ q: str = Depends(query_extractor),
+ last_query: Union[str, None] = Cookie(default=None),
):
if not q:
return last_query
diff --git a/docs_src/dependency_testing/tutorial001.py b/docs_src/dependency_testing/tutorial001.py
index 237d3b231..a5fe1d9bf 100644
--- a/docs_src/dependency_testing/tutorial001.py
+++ b/docs_src/dependency_testing/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
@@ -6,7 +6,9 @@ from fastapi.testclient import TestClient
app = FastAPI()
-async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
+async def common_parameters(
+ q: Union[str, None] = None, skip: int = 0, limit: int = 100
+):
return {"q": q, "skip": skip, "limit": limit}
@@ -23,7 +25,7 @@ async def read_users(commons: dict = Depends(common_parameters)):
client = TestClient(app)
-async def override_dependency(q: Optional[str] = None):
+async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
diff --git a/docs_src/encoder/tutorial001.py b/docs_src/encoder/tutorial001.py
index a918fdd64..5f7e7061e 100644
--- a/docs_src/encoder/tutorial001.py
+++ b/docs_src/encoder/tutorial001.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
@@ -11,7 +11,7 @@ fake_db = {}
class Item(BaseModel):
title: str
timestamp: datetime
- description: Optional[str] = None
+ description: Union[str, None] = None
app = FastAPI()
diff --git a/docs_src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001.py
index 9f5e911bf..8ae8472a7 100644
--- a/docs_src/extra_data_types/tutorial001.py
+++ b/docs_src/extra_data_types/tutorial001.py
@@ -1,5 +1,5 @@
from datetime import datetime, time, timedelta
-from typing import Optional
+from typing import Union
from uuid import UUID
from fastapi import Body, FastAPI
@@ -10,10 +10,10 @@ app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
- start_datetime: Optional[datetime] = Body(default=None),
- end_datetime: Optional[datetime] = Body(default=None),
- repeat_at: Optional[time] = Body(default=None),
- process_after: Optional[timedelta] = Body(default=None),
+ start_datetime: Union[datetime, None] = Body(default=None),
+ end_datetime: Union[datetime, None] = Body(default=None),
+ repeat_at: Union[time, None] = Body(default=None),
+ process_after: Union[timedelta, None] = Body(default=None),
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
diff --git a/docs_src/extra_models/tutorial001.py b/docs_src/extra_models/tutorial001.py
index e95844f60..4be56cd2a 100644
--- a/docs_src/extra_models/tutorial001.py
+++ b/docs_src/extra_models/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
@@ -10,20 +10,20 @@ class UserIn(BaseModel):
username: str
password: str
email: EmailStr
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
class UserOut(BaseModel):
username: str
email: EmailStr
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
class UserInDB(BaseModel):
username: str
hashed_password: str
email: EmailStr
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
def fake_password_hasher(raw_password: str):
diff --git a/docs_src/extra_models/tutorial002.py b/docs_src/extra_models/tutorial002.py
index 5bc6e707f..70fa16441 100644
--- a/docs_src/extra_models/tutorial002.py
+++ b/docs_src/extra_models/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
@@ -9,7 +9,7 @@ app = FastAPI()
class UserBase(BaseModel):
username: str
email: EmailStr
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
class UserIn(UserBase):
diff --git a/docs_src/header_params/tutorial001.py b/docs_src/header_params/tutorial001.py
index 1df561a12..74429c8e2 100644
--- a/docs_src/header_params/tutorial001.py
+++ b/docs_src/header_params/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI, Header
@@ -6,5 +6,5 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(user_agent: Optional[str] = Header(default=None)):
+async def read_items(user_agent: Union[str, None] = Header(default=None)):
return {"User-Agent": user_agent}
diff --git a/docs_src/header_params/tutorial002.py b/docs_src/header_params/tutorial002.py
index 2250727f6..639ab1735 100644
--- a/docs_src/header_params/tutorial002.py
+++ b/docs_src/header_params/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI, Header
@@ -7,6 +7,6 @@ app = FastAPI()
@app.get("/items/")
async def read_items(
- strange_header: Optional[str] = Header(default=None, convert_underscores=False)
+ strange_header: Union[str, None] = Header(default=None, convert_underscores=False)
):
return {"strange_header": strange_header}
diff --git a/docs_src/header_params/tutorial003.py b/docs_src/header_params/tutorial003.py
index 1ef131cee..a61314aed 100644
--- a/docs_src/header_params/tutorial003.py
+++ b/docs_src/header_params/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI, Header
@@ -6,5 +6,5 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(x_token: Optional[List[str]] = Header(default=None)):
+async def read_items(x_token: Union[List[str], None] = Header(default=None)):
return {"X-Token values": x_token}
diff --git a/docs_src/header_params/tutorial003_py39.py b/docs_src/header_params/tutorial003_py39.py
index 78dda58da..34437db16 100644
--- a/docs_src/header_params/tutorial003_py39.py
+++ b/docs_src/header_params/tutorial003_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI, Header
@@ -6,5 +6,5 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(x_token: Optional[list[str]] = Header(default=None)):
+async def read_items(x_token: Union[list[str], None] = Header(default=None)):
return {"X-Token values": x_token}
diff --git a/docs_src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py
index 39548d862..91893e528 100644
--- a/docs_src/nosql_databases/tutorial001.py
+++ b/docs_src/nosql_databases/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from couchbase import LOCKMODE_WAIT
from couchbase.bucket import Bucket
@@ -23,9 +23,9 @@ def get_bucket():
class User(BaseModel):
username: str
- email: Optional[str] = None
- full_name: Optional[str] = None
- disabled: Optional[bool] = None
+ email: Union[str, None] = None
+ full_name: Union[str, None] = None
+ disabled: Union[bool, None] = None
class UserInDB(User):
diff --git a/docs_src/openapi_callbacks/tutorial001.py b/docs_src/openapi_callbacks/tutorial001.py
index 2fb836751..3f1bac6e2 100644
--- a/docs_src/openapi_callbacks/tutorial001.py
+++ b/docs_src/openapi_callbacks/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import APIRouter, FastAPI
from pydantic import BaseModel, HttpUrl
@@ -8,7 +8,7 @@ app = FastAPI()
class Invoice(BaseModel):
id: str
- title: Optional[str] = None
+ title: Union[str, None] = None
customer: str
total: float
@@ -33,7 +33,7 @@ def invoice_notification(body: InvoiceEvent):
@app.post("/invoices/", callbacks=invoices_callback_router.routes)
-def create_invoice(invoice: Invoice, callback_url: Optional[HttpUrl] = None):
+def create_invoice(invoice: Invoice, callback_url: Union[HttpUrl, None] = None):
"""
Create an invoice.
diff --git a/docs_src/path_operation_advanced_configuration/tutorial004.py b/docs_src/path_operation_advanced_configuration/tutorial004.py
index da678aed3..a3aad4ac4 100644
--- a/docs_src/path_operation_advanced_configuration/tutorial004.py
+++ b/docs_src/path_operation_advanced_configuration/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial001.py b/docs_src/path_operation_configuration/tutorial001.py
index 1316d9237..83fd8377a 100644
--- a/docs_src/path_operation_configuration/tutorial001.py
+++ b/docs_src/path_operation_configuration/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI, status
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial001_py39.py b/docs_src/path_operation_configuration/tutorial001_py39.py
index 5c04d8bac..a9dcbf389 100644
--- a/docs_src/path_operation_configuration/tutorial001_py39.py
+++ b/docs_src/path_operation_configuration/tutorial001_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI, status
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial002.py b/docs_src/path_operation_configuration/tutorial002.py
index 2df537d86..798b0c231 100644
--- a/docs_src/path_operation_configuration/tutorial002.py
+++ b/docs_src/path_operation_configuration/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial002_py39.py b/docs_src/path_operation_configuration/tutorial002_py39.py
index 766d9fb0b..e7ced7de7 100644
--- a/docs_src/path_operation_configuration/tutorial002_py39.py
+++ b/docs_src/path_operation_configuration/tutorial002_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial003.py b/docs_src/path_operation_configuration/tutorial003.py
index 269a1a253..26bf7daba 100644
--- a/docs_src/path_operation_configuration/tutorial003.py
+++ b/docs_src/path_operation_configuration/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial003_py39.py b/docs_src/path_operation_configuration/tutorial003_py39.py
index 446198b5c..607c5707e 100644
--- a/docs_src/path_operation_configuration/tutorial003_py39.py
+++ b/docs_src/path_operation_configuration/tutorial003_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial004.py b/docs_src/path_operation_configuration/tutorial004.py
index de83be836..8f865c58a 100644
--- a/docs_src/path_operation_configuration/tutorial004.py
+++ b/docs_src/path_operation_configuration/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial004_py39.py b/docs_src/path_operation_configuration/tutorial004_py39.py
index bf6005b95..fc25680c5 100644
--- a/docs_src/path_operation_configuration/tutorial004_py39.py
+++ b/docs_src/path_operation_configuration/tutorial004_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial005.py b/docs_src/path_operation_configuration/tutorial005.py
index 0f62c3814..2c1be4a34 100644
--- a/docs_src/path_operation_configuration/tutorial005.py
+++ b/docs_src/path_operation_configuration/tutorial005.py
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: Set[str] = set()
diff --git a/docs_src/path_operation_configuration/tutorial005_py39.py b/docs_src/path_operation_configuration/tutorial005_py39.py
index 5ef320405..ddf29b733 100644
--- a/docs_src/path_operation_configuration/tutorial005_py39.py
+++ b/docs_src/path_operation_configuration/tutorial005_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: set[str] = set()
diff --git a/docs_src/python_types/tutorial009c.py b/docs_src/python_types/tutorial009c.py
new file mode 100644
index 000000000..2f539a34b
--- /dev/null
+++ b/docs_src/python_types/tutorial009c.py
@@ -0,0 +1,5 @@
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
diff --git a/docs_src/python_types/tutorial009c_py310.py b/docs_src/python_types/tutorial009c_py310.py
new file mode 100644
index 000000000..96b1220fc
--- /dev/null
+++ b/docs_src/python_types/tutorial009c_py310.py
@@ -0,0 +1,2 @@
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
diff --git a/docs_src/python_types/tutorial011.py b/docs_src/python_types/tutorial011.py
index 047b633b5..c8634cbff 100644
--- a/docs_src/python_types/tutorial011.py
+++ b/docs_src/python_types/tutorial011.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import List, Optional
+from typing import List, Union
from pydantic import BaseModel
@@ -7,7 +7,7 @@ from pydantic import BaseModel
class User(BaseModel):
id: int
name = "John Doe"
- signup_ts: Optional[datetime] = None
+ signup_ts: Union[datetime, None] = None
friends: List[int] = []
diff --git a/docs_src/python_types/tutorial011_py39.py b/docs_src/python_types/tutorial011_py39.py
index af79e2df0..468496f51 100644
--- a/docs_src/python_types/tutorial011_py39.py
+++ b/docs_src/python_types/tutorial011_py39.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Optional
+from typing import Union
from pydantic import BaseModel
@@ -7,7 +7,7 @@ from pydantic import BaseModel
class User(BaseModel):
id: int
name = "John Doe"
- signup_ts: Optional[datetime] = None
+ signup_ts: Union[datetime, None] = None
friends: list[int] = []
diff --git a/docs_src/python_types/tutorial012.py b/docs_src/python_types/tutorial012.py
new file mode 100644
index 000000000..74fa94c43
--- /dev/null
+++ b/docs_src/python_types/tutorial012.py
@@ -0,0 +1,8 @@
+from typing import Optional
+
+from pydantic import BaseModel
+
+
+class User(BaseModel):
+ name: str
+ age: Optional[int]
diff --git a/docs_src/query_params/tutorial002.py b/docs_src/query_params/tutorial002.py
index 32918465e..8465f45ee 100644
--- a/docs_src/query_params/tutorial002.py
+++ b/docs_src/query_params/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -6,7 +6,7 @@ app = FastAPI()
@app.get("/items/{item_id}")
-async def read_item(item_id: str, q: Optional[str] = None):
+async def read_item(item_id: str, q: Union[str, None] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
diff --git a/docs_src/query_params/tutorial003.py b/docs_src/query_params/tutorial003.py
index c81a96785..3362715b3 100644
--- a/docs_src/query_params/tutorial003.py
+++ b/docs_src/query_params/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -6,7 +6,7 @@ app = FastAPI()
@app.get("/items/{item_id}")
-async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
+async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False):
item = {"item_id": item_id}
if q:
item.update({"q": q})
diff --git a/docs_src/query_params/tutorial004.py b/docs_src/query_params/tutorial004.py
index 37f97fa2a..049c3ae93 100644
--- a/docs_src/query_params/tutorial004.py
+++ b/docs_src/query_params/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -7,7 +7,7 @@ app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
- user_id: int, item_id: str, q: Optional[str] = None, short: bool = False
+ user_id: int, item_id: str, q: Union[str, None] = None, short: bool = False
):
item = {"item_id": item_id, "owner_id": user_id}
if q:
diff --git a/docs_src/query_params/tutorial006.py b/docs_src/query_params/tutorial006.py
index ffe328340..f0dbfe08f 100644
--- a/docs_src/query_params/tutorial006.py
+++ b/docs_src/query_params/tutorial006.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -7,7 +7,7 @@ app = FastAPI()
@app.get("/items/{item_id}")
async def read_user_item(
- item_id: str, needy: str, skip: int = 0, limit: Optional[int] = None
+ item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None
):
item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
return item
diff --git a/docs_src/query_params_str_validations/tutorial001.py b/docs_src/query_params_str_validations/tutorial001.py
index 5d7bfb0ee..e38326b18 100644
--- a/docs_src/query_params_str_validations/tutorial001.py
+++ b/docs_src/query_params_str_validations/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
@@ -6,7 +6,7 @@ app = FastAPI()
@app.get("/items/")
-async def read_items(q: Optional[str] = None):
+async def read_items(q: Union[str, None] = None):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
diff --git a/docs_src/request_files/tutorial001_02.py b/docs_src/request_files/tutorial001_02.py
index 3f311c4b8..ac30be2d3 100644
--- a/docs_src/request_files/tutorial001_02.py
+++ b/docs_src/request_files/tutorial001_02.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI, File, UploadFile
@@ -6,7 +6,7 @@ app = FastAPI()
@app.post("/files/")
-async def create_file(file: Optional[bytes] = File(default=None)):
+async def create_file(file: Union[bytes, None] = File(default=None)):
if not file:
return {"message": "No file sent"}
else:
@@ -14,7 +14,7 @@ async def create_file(file: Optional[bytes] = File(default=None)):
@app.post("/uploadfile/")
-async def create_upload_file(file: Optional[UploadFile] = None):
+async def create_upload_file(file: Union[UploadFile, None] = None):
if not file:
return {"message": "No upload file sent"}
else:
diff --git a/docs_src/response_directly/tutorial001.py b/docs_src/response_directly/tutorial001.py
index 6acdc0fc8..5ab655a8a 100644
--- a/docs_src/response_directly/tutorial001.py
+++ b/docs_src/response_directly/tutorial001.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
@@ -10,7 +10,7 @@ from pydantic import BaseModel
class Item(BaseModel):
title: str
timestamp: datetime
- description: Optional[str] = None
+ description: Union[str, None] = None
app = FastAPI()
diff --git a/docs_src/response_model/tutorial001.py b/docs_src/response_model/tutorial001.py
index 57992ecfc..0f6e03e5b 100644
--- a/docs_src/response_model/tutorial001.py
+++ b/docs_src/response_model/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: List[str] = []
diff --git a/docs_src/response_model/tutorial001_py39.py b/docs_src/response_model/tutorial001_py39.py
index 37b866864..cdcca39d2 100644
--- a/docs_src/response_model/tutorial001_py39.py
+++ b/docs_src/response_model/tutorial001_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
tags: list[str] = []
diff --git a/docs_src/response_model/tutorial002.py b/docs_src/response_model/tutorial002.py
index 373317eb9..c68e8b138 100644
--- a/docs_src/response_model/tutorial002.py
+++ b/docs_src/response_model/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
@@ -10,7 +10,7 @@ class UserIn(BaseModel):
username: str
password: str
email: EmailStr
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
# Don't do this in production!
diff --git a/docs_src/response_model/tutorial003.py b/docs_src/response_model/tutorial003.py
index e14026dd8..37e493dcb 100644
--- a/docs_src/response_model/tutorial003.py
+++ b/docs_src/response_model/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
@@ -10,13 +10,13 @@ class UserIn(BaseModel):
username: str
password: str
email: EmailStr
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
class UserOut(BaseModel):
username: str
email: EmailStr
- full_name: Optional[str] = None
+ full_name: Union[str, None] = None
@app.post("/user/", response_model=UserOut)
diff --git a/docs_src/response_model/tutorial004.py b/docs_src/response_model/tutorial004.py
index 1e18f989d..10b48039a 100644
--- a/docs_src/response_model/tutorial004.py
+++ b/docs_src/response_model/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
tax: float = 10.5
tags: List[str] = []
diff --git a/docs_src/response_model/tutorial004_py39.py b/docs_src/response_model/tutorial004_py39.py
index 07ccbbf41..9463b45ec 100644
--- a/docs_src/response_model/tutorial004_py39.py
+++ b/docs_src/response_model/tutorial004_py39.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
tax: float = 10.5
tags: list[str] = []
diff --git a/docs_src/response_model/tutorial005.py b/docs_src/response_model/tutorial005.py
index 03933d1f7..30eb9f8e3 100644
--- a/docs_src/response_model/tutorial005.py
+++ b/docs_src/response_model/tutorial005.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
tax: float = 10.5
diff --git a/docs_src/response_model/tutorial006.py b/docs_src/response_model/tutorial006.py
index 629ab8a3a..3ffdb512b 100644
--- a/docs_src/response_model/tutorial006.py
+++ b/docs_src/response_model/tutorial006.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
tax: float = 10.5
diff --git a/docs_src/schema_extra_example/tutorial001.py b/docs_src/schema_extra_example/tutorial001.py
index fab4d7a44..a5ae28127 100644
--- a/docs_src/schema_extra_example/tutorial001.py
+++ b/docs_src/schema_extra_example/tutorial001.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
class Config:
schema_extra = {
diff --git a/docs_src/schema_extra_example/tutorial002.py b/docs_src/schema_extra_example/tutorial002.py
index a2aec46f5..6de434f81 100644
--- a/docs_src/schema_extra_example/tutorial002.py
+++ b/docs_src/schema_extra_example/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, Field
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str = Field(example="Foo")
- description: Optional[str] = Field(default=None, example="A very nice Item")
+ description: Union[str, None] = Field(default=None, example="A very nice Item")
price: float = Field(example=35.4)
- tax: Optional[float] = Field(default=None, example=3.2)
+ tax: Union[float, None] = Field(default=None, example=3.2)
@app.put("/items/{item_id}")
diff --git a/docs_src/schema_extra_example/tutorial003.py b/docs_src/schema_extra_example/tutorial003.py
index 43d46b81b..ce1736bba 100644
--- a/docs_src/schema_extra_example/tutorial003.py
+++ b/docs_src/schema_extra_example/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Body, FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/schema_extra_example/tutorial004.py b/docs_src/schema_extra_example/tutorial004.py
index 42d7a04a3..b67edf30c 100644
--- a/docs_src/schema_extra_example/tutorial004.py
+++ b/docs_src/schema_extra_example/tutorial004.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Body, FastAPI
from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
class Item(BaseModel):
name: str
- description: Optional[str] = None
+ description: Union[str, None] = None
price: float
- tax: Optional[float] = None
+ tax: Union[float, None] = None
@app.put("/items/{item_id}")
diff --git a/docs_src/security/tutorial002.py b/docs_src/security/tutorial002.py
index 03e0cd5fc..bfd035221 100644
--- a/docs_src/security/tutorial002.py
+++ b/docs_src/security/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
@@ -11,9 +11,9 @@ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class User(BaseModel):
username: str
- email: Optional[str] = None
- full_name: Optional[str] = None
- disabled: Optional[bool] = None
+ email: Union[str, None] = None
+ full_name: Union[str, None] = None
+ disabled: Union[bool, None] = None
def fake_decode_token(token):
diff --git a/docs_src/security/tutorial003.py b/docs_src/security/tutorial003.py
index a6bb176e4..4b324866f 100644
--- a/docs_src/security/tutorial003.py
+++ b/docs_src/security/tutorial003.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
@@ -33,9 +33,9 @@ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class User(BaseModel):
username: str
- email: Optional[str] = None
- full_name: Optional[str] = None
- disabled: Optional[bool] = None
+ email: Union[str, None] = None
+ full_name: Union[str, None] = None
+ disabled: Union[bool, None] = None
class UserInDB(User):
diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py
index 18e2c428f..64099abe9 100644
--- a/docs_src/security/tutorial004.py
+++ b/docs_src/security/tutorial004.py
@@ -1,5 +1,5 @@
from datetime import datetime, timedelta
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
@@ -31,14 +31,14 @@ class Token(BaseModel):
class TokenData(BaseModel):
- username: Optional[str] = None
+ username: Union[str, None] = None
class User(BaseModel):
username: str
- email: Optional[str] = None
- full_name: Optional[str] = None
- disabled: Optional[bool] = None
+ email: Union[str, None] = None
+ full_name: Union[str, None] = None
+ disabled: Union[bool, None] = None
class UserInDB(User):
@@ -75,7 +75,7 @@ def authenticate_user(fake_db, username: str, password: str):
return user
-def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
+def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py
index 5b34a09f1..ab3af9a6a 100644
--- a/docs_src/security/tutorial005.py
+++ b/docs_src/security/tutorial005.py
@@ -1,5 +1,5 @@
from datetime import datetime, timedelta
-from typing import List, Optional
+from typing import List, Union
from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
@@ -42,15 +42,15 @@ class Token(BaseModel):
class TokenData(BaseModel):
- username: Optional[str] = None
+ username: Union[str, None] = None
scopes: List[str] = []
class User(BaseModel):
username: str
- email: Optional[str] = None
- full_name: Optional[str] = None
- disabled: Optional[bool] = None
+ email: Union[str, None] = None
+ full_name: Union[str, None] = None
+ disabled: Union[bool, None] = None
class UserInDB(User):
@@ -90,7 +90,7 @@ def authenticate_user(fake_db, username: str, password: str):
return user
-def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
+def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py
index d45c08ce6..38391308a 100644
--- a/docs_src/security/tutorial005_py39.py
+++ b/docs_src/security/tutorial005_py39.py
@@ -1,5 +1,5 @@
from datetime import datetime, timedelta
-from typing import Optional
+from typing import Union
from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import (
@@ -42,15 +42,15 @@ class Token(BaseModel):
class TokenData(BaseModel):
- username: Optional[str] = None
+ username: Union[str, None] = None
scopes: list[str] = []
class User(BaseModel):
username: str
- email: Optional[str] = None
- full_name: Optional[str] = None
- disabled: Optional[bool] = None
+ email: Union[str, None] = None
+ full_name: Union[str, None] = None
+ disabled: Union[bool, None] = None
class UserInDB(User):
@@ -90,7 +90,7 @@ def authenticate_user(fake_db, username: str, password: str):
return user
-def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
+def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
diff --git a/docs_src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py
index 51655663a..c49beba88 100644
--- a/docs_src/sql_databases/sql_app/schemas.py
+++ b/docs_src/sql_databases/sql_app/schemas.py
@@ -1,11 +1,11 @@
-from typing import List, Optional
+from typing import List, Union
from pydantic import BaseModel
class ItemBase(BaseModel):
title: str
- description: Optional[str] = None
+ description: Union[str, None] = None
class ItemCreate(ItemBase):
diff --git a/docs_src/sql_databases/sql_app_py39/schemas.py b/docs_src/sql_databases/sql_app_py39/schemas.py
index a19f1cdfe..dadc403d9 100644
--- a/docs_src/sql_databases/sql_app_py39/schemas.py
+++ b/docs_src/sql_databases/sql_app_py39/schemas.py
@@ -1,11 +1,11 @@
-from typing import Optional
+from typing import Union
from pydantic import BaseModel
class ItemBase(BaseModel):
title: str
- description: Optional[str] = None
+ description: Union[str, None] = None
class ItemCreate(ItemBase):
diff --git a/docs_src/sql_databases_peewee/sql_app/schemas.py b/docs_src/sql_databases_peewee/sql_app/schemas.py
index b715604ee..d8775cb30 100644
--- a/docs_src/sql_databases_peewee/sql_app/schemas.py
+++ b/docs_src/sql_databases_peewee/sql_app/schemas.py
@@ -1,4 +1,4 @@
-from typing import Any, List, Optional
+from typing import Any, List, Union
import peewee
from pydantic import BaseModel
@@ -15,7 +15,7 @@ class PeeweeGetterDict(GetterDict):
class ItemBase(BaseModel):
title: str
- description: Optional[str] = None
+ description: Union[str, None] = None
class ItemCreate(ItemBase):
diff --git a/docs_src/websockets/tutorial002.py b/docs_src/websockets/tutorial002.py
index b01008530..cf5c7e805 100644
--- a/docs_src/websockets/tutorial002.py
+++ b/docs_src/websockets/tutorial002.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status
from fastapi.responses import HTMLResponse
@@ -57,8 +57,8 @@ async def get():
async def get_cookie_or_token(
websocket: WebSocket,
- session: Optional[str] = Cookie(default=None),
- token: Optional[str] = Query(default=None),
+ session: Union[str, None] = Cookie(default=None),
+ token: Union[str, None] = Query(default=None),
):
if session is None and token is None:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
@@ -69,7 +69,7 @@ async def get_cookie_or_token(
async def websocket_endpoint(
websocket: WebSocket,
item_id: str,
- q: Optional[int] = None,
+ q: Union[int, None] = None,
cookie_or_token: str = Depends(get_cookie_or_token),
):
await websocket.accept()