diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index ee62b97181028..c5fc35b88aeff 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -16,12 +16,12 @@ Let's take this application as example: {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` -The query parameter `q` is of type `Optional[str]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. +The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. !!! note 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]` will allow your editor to give you better support and detect errors. ## Additional validation @@ -59,24 +59,24 @@ And now use it as the default value of your parameter, setting the parameter `ma {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` -As we have to replace the default value `None` with `Query(None)`, the first parameter to `Query` serves the same purpose of defining that default value. +As we have to replace the default value `None` in the function with `Query()`, we can now set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value. So: ```Python -q: Optional[str] = Query(None) +q: Union[str, None] = Query(default=None) ``` ...makes the parameter optional, the same as: ```Python -q: Optional[str] = None +q: Union[str, None] = None ``` And in Python 3.10 and above: ```Python -q: str | None = Query(None) +q: str | None = Query(default=None) ``` ...makes the parameter optional, the same as: @@ -97,17 +97,17 @@ But it declares it explicitly as being a query parameter. or the: ```Python - = Query(None) + = Query(default=None) ``` as it will use that `None` as the default value, and that way make the parameter **not required**. - The `Optional` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. + The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings: ```Python -q: str = Query(None, max_length=50) +q: Union[str, None] = Query(default=None, max_length=50) ``` This will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema *path operation*. @@ -118,7 +118,7 @@ You can also add a parameter `min_length`: === "Python 3.6 and above" - ```Python hl_lines="9" + ```Python hl_lines="10" {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} ``` @@ -134,13 +134,13 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004.py!} ``` === "Python 3.10 and above" - ```Python hl_lines="8" + ```Python hl_lines="9" {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` @@ -156,7 +156,7 @@ But whenever you need them and go and learn them, know that you can already use ## Default values -The same way that you can pass `None` as the first argument to be used as the default value, you can pass other values. +The same way that you can pass `None` as the value for the `default` parameter, you can pass other values. Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`: @@ -178,26 +178,68 @@ q: str instead of: ```Python -q: Optional[str] = None +q: Union[str, None] = None ``` But we are now declaring it with `Query`, for example like: ```Python -q: Optional[str] = Query(None, min_length=3) +q: Union[str, None] = Query(default=None, min_length=3) ``` -So, when you need to declare a value as required while using `Query`, you can use `...` as the first argument: +So, when you need to declare a value as required while using `Query`, you can simply not declare a default value: ```Python hl_lines="7" {!../../../docs_src/query_params_str_validations/tutorial006.py!} ``` +### Required with Ellipsis (`...`) + +There's an alternative way to explicitly declare that a value is required. You can set the `default` parameter to the literal value `...`: + +```Python hl_lines="7" +{!../../../docs_src/query_params_str_validations/tutorial006b.py!} +``` + !!! info If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis". + It is used by Pydantic and FastAPI to explicitly declare that a value is required. + This will let **FastAPI** know that this parameter is required. +### Required with `None` + +You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`. + +To do that, you can declare that `None` is a valid type but still use `default=...`: + +=== "Python 3.6 and above" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} + ``` + +!!! tip + Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields. + +### Use Pydantic's `Required` instead of Ellipsis (`...`) + +If you feel uncomfortable using `...`, you can also import and use `Required` from Pydantic: + +```Python hl_lines="2 8" +{!../../../docs_src/query_params_str_validations/tutorial006d.py!} +``` + +!!! tip + Remember that in most of the cases, when something is required, you can simply omit the `default` parameter, so you normally don't have to use `...` nor `Required`. + ## Query parameter list / multiple values When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in other way, to receive multiple values. @@ -315,7 +357,7 @@ You can add a `title`: === "Python 3.10 and above" - ```Python hl_lines="7" + ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` @@ -399,7 +441,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t === "Python 3.10 and above" - ```Python hl_lines="7" + ```Python hl_lines="8" {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` diff --git a/docs_src/additional_status_codes/tutorial001.py b/docs_src/additional_status_codes/tutorial001.py index ae101e0a090cd..74a986a6a9bff 100644 --- a/docs_src/additional_status_codes/tutorial001.py +++ b/docs_src/additional_status_codes/tutorial001.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import Body, FastAPI, status from fastapi.responses import JSONResponse @@ -10,7 +10,9 @@ @app.put("/items/{item_id}") async def upsert_item( - item_id: str, name: Optional[str] = Body(None), size: Optional[int] = Body(None) + item_id: str, + name: Union[str, None] = Body(default=None), + size: Union[int, None] = Body(default=None), ): if item_id in items: item = items[item_id] diff --git a/docs_src/app_testing/app_b/main.py b/docs_src/app_testing/app_b/main.py index df43db8060515..11558b8e813f4 100644 --- a/docs_src/app_testing/app_b/main.py +++ b/docs_src/app_testing/app_b/main.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel @@ -16,11 +16,11 @@ class Item(BaseModel): id: str title: str - description: Optional[str] = None + description: Union[str, None] = None @app.get("/items/{item_id}", response_model=Item) -async def read_main(item_id: str, x_token: str = Header(...)): +async def read_main(item_id: str, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: @@ -29,7 +29,7 @@ async def read_main(item_id: str, x_token: str = Header(...)): @app.post("/items/", response_model=Item) -async def create_item(item: Item, x_token: str = Header(...)): +async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: diff --git a/docs_src/app_testing/app_b_py310/main.py b/docs_src/app_testing/app_b_py310/main.py index d44ab9e7c442a..b4c72de5c9431 100644 --- a/docs_src/app_testing/app_b_py310/main.py +++ b/docs_src/app_testing/app_b_py310/main.py @@ -18,7 +18,7 @@ class Item(BaseModel): @app.get("/items/{item_id}", response_model=Item) -async def read_main(item_id: str, x_token: str = Header(...)): +async def read_main(item_id: str, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item_id not in fake_db: @@ -27,7 +27,7 @@ async def read_main(item_id: str, x_token: str = Header(...)): @app.post("/items/", response_model=Item) -async def create_item(item: Item, x_token: str = Header(...)): +async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: diff --git a/docs_src/bigger_applications/app/dependencies.py b/docs_src/bigger_applications/app/dependencies.py index 267b0d3a8ee20..8e45f004b42e4 100644 --- a/docs_src/bigger_applications/app/dependencies.py +++ b/docs_src/bigger_applications/app/dependencies.py @@ -1,7 +1,7 @@ from fastapi import Header, HTTPException -async def get_token_header(x_token: str = Header(...)): +async def get_token_header(x_token: str = Header()): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") diff --git a/docs_src/body_fields/tutorial001.py b/docs_src/body_fields/tutorial001.py index dabc48a0f5a64..cbeebd614ad53 100644 --- a/docs_src/body_fields/tutorial001.py +++ b/docs_src/body_fields/tutorial001.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import Body, FastAPI from pydantic import BaseModel, Field @@ -8,14 +8,14 @@ class Item(BaseModel): name: str - description: Optional[str] = Field( - None, title="The description of the item", max_length=300 + description: Union[str, None] = Field( + default=None, title="The description of the item", max_length=300 ) - price: float = Field(..., gt=0, description="The price must be greater than zero") - tax: Optional[float] = None + price: float = Field(gt=0, description="The price must be greater than zero") + tax: Union[float, None] = None @app.put("/items/{item_id}") -async def update_item(item_id: int, item: Item = Body(..., embed=True)): +async def update_item(item_id: int, item: Item = Body(embed=True)): results = {"item_id": item_id, "item": item} return results diff --git a/docs_src/body_fields/tutorial001_py310.py b/docs_src/body_fields/tutorial001_py310.py index 01e02a050d820..4437327f3bf82 100644 --- a/docs_src/body_fields/tutorial001_py310.py +++ b/docs_src/body_fields/tutorial001_py310.py @@ -7,13 +7,13 @@ class Item(BaseModel): name: str description: str | None = Field( - None, title="The description of the item", max_length=300 + default=None, title="The description of the item", max_length=300 ) - price: float = Field(..., gt=0, description="The price must be greater than zero") + price: float = Field(gt=0, description="The price must be greater than zero") tax: float | None = None @app.put("/items/{item_id}") -async def update_item(item_id: int, item: Item = Body(..., embed=True)): +async def update_item(item_id: int, item: Item = Body(embed=True)): results = {"item_id": item_id, "item": item} return results diff --git a/docs_src/body_multiple_params/tutorial001.py b/docs_src/body_multiple_params/tutorial001.py index 7ce0ae6f28483..a73975b3a2b3b 100644 --- a/docs_src/body_multiple_params/tutorial001.py +++ b/docs_src/body_multiple_params/tutorial001.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Path from pydantic import BaseModel @@ -8,17 +8,17 @@ 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}") async def update_item( *, - item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000), - q: Optional[str] = None, - item: Optional[Item] = None, + item_id: int = Path(title="The ID of the item to get", ge=0, le=1000), + q: Union[str, None] = None, + item: Union[Item, None] = None, ): results = {"item_id": item_id} if q: diff --git a/docs_src/body_multiple_params/tutorial001_py310.py b/docs_src/body_multiple_params/tutorial001_py310.py index b08d397b3a4db..be0eba2aee846 100644 --- a/docs_src/body_multiple_params/tutorial001_py310.py +++ b/docs_src/body_multiple_params/tutorial001_py310.py @@ -14,7 +14,7 @@ class Item(BaseModel): @app.put("/items/{item_id}") async def update_item( *, - item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000), + item_id: int = Path(title="The ID of the item to get", ge=0, le=1000), q: str | None = None, item: Item | None = None, ): diff --git a/docs_src/body_multiple_params/tutorial003.py b/docs_src/body_multiple_params/tutorial003.py index 7e9e243748125..cf344e6c5d010 100644 --- a/docs_src/body_multiple_params/tutorial003.py +++ b/docs_src/body_multiple_params/tutorial003.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import Body, FastAPI from pydantic import BaseModel @@ -8,19 +8,17 @@ 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}") -async def update_item( - item_id: int, item: Item, user: User, importance: int = Body(...) -): +async def update_item(item_id: int, item: Item, user: User, importance: int = Body()): results = {"item_id": item_id, "item": item, "user": user, "importance": importance} return results diff --git a/docs_src/body_multiple_params/tutorial003_py310.py b/docs_src/body_multiple_params/tutorial003_py310.py index 9ddbda3f7b2ed..a1a75fe8e40e9 100644 --- a/docs_src/body_multiple_params/tutorial003_py310.py +++ b/docs_src/body_multiple_params/tutorial003_py310.py @@ -17,8 +17,6 @@ class User(BaseModel): @app.put("/items/{item_id}") -async def update_item( - item_id: int, item: Item, user: User, importance: int = Body(...) -): +async def update_item(item_id: int, item: Item, user: User, importance: int = Body()): results = {"item_id": item_id, "item": item, "user": user, "importance": importance} return results diff --git a/docs_src/body_multiple_params/tutorial004.py b/docs_src/body_multiple_params/tutorial004.py index 8dc0d374deddd..beea7d1e38ff8 100644 --- a/docs_src/body_multiple_params/tutorial004.py +++ b/docs_src/body_multiple_params/tutorial004.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import Body, FastAPI from pydantic import BaseModel @@ -8,14 +8,14 @@ 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}") @@ -24,8 +24,8 @@ async def update_item( item_id: int, item: Item, user: User, - importance: int = Body(..., gt=0), - q: Optional[str] = None + importance: int = Body(gt=0), + q: Union[str, None] = None ): results = {"item_id": item_id, "item": item, "user": user, "importance": importance} if q: diff --git a/docs_src/body_multiple_params/tutorial004_py310.py b/docs_src/body_multiple_params/tutorial004_py310.py index 77321300e68f2..6d495d4082352 100644 --- a/docs_src/body_multiple_params/tutorial004_py310.py +++ b/docs_src/body_multiple_params/tutorial004_py310.py @@ -22,7 +22,7 @@ async def update_item( item_id: int, item: Item, user: User, - importance: int = Body(..., gt=0), + importance: int = Body(gt=0), q: str | None = None ): results = {"item_id": item_id, "item": item, "user": user, "importance": importance} diff --git a/docs_src/body_multiple_params/tutorial005.py b/docs_src/body_multiple_params/tutorial005.py index 4657b4144e4c6..29e6e14b7e306 100644 --- a/docs_src/body_multiple_params/tutorial005.py +++ b/docs_src/body_multiple_params/tutorial005.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import Body, FastAPI from pydantic import BaseModel @@ -8,12 +8,12 @@ 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}") -async def update_item(item_id: int, item: Item = Body(..., embed=True)): +async def update_item(item_id: int, item: Item = Body(embed=True)): results = {"item_id": item_id, "item": item} return results diff --git a/docs_src/body_multiple_params/tutorial005_py310.py b/docs_src/body_multiple_params/tutorial005_py310.py index 97b213b16375d..06744507b8e28 100644 --- a/docs_src/body_multiple_params/tutorial005_py310.py +++ b/docs_src/body_multiple_params/tutorial005_py310.py @@ -12,6 +12,6 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def update_item(item_id: int, item: Item = Body(..., embed=True)): +async def update_item(item_id: int, item: Item = Body(embed=True)): results = {"item_id": item_id, "item": item} return results diff --git a/docs_src/cookie_params/tutorial001.py b/docs_src/cookie_params/tutorial001.py index 67d03b13366a2..c4a497fda5989 100644 --- a/docs_src/cookie_params/tutorial001.py +++ b/docs_src/cookie_params/tutorial001.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import Cookie, FastAPI @@ -6,5 +6,5 @@ @app.get("/items/") -async def read_items(ads_id: Optional[str] = Cookie(None)): +async def read_items(ads_id: Union[str, None] = Cookie(default=None)): return {"ads_id": ads_id} diff --git a/docs_src/cookie_params/tutorial001_py310.py b/docs_src/cookie_params/tutorial001_py310.py index d0b0046318160..6c9d5f9a1ebcb 100644 --- a/docs_src/cookie_params/tutorial001_py310.py +++ b/docs_src/cookie_params/tutorial001_py310.py @@ -4,5 +4,5 @@ @app.get("/items/") -async def read_items(ads_id: str | None = Cookie(None)): +async def read_items(ads_id: str | None = Cookie(default=None)): return {"ads_id": ads_id} diff --git a/docs_src/custom_request_and_route/tutorial001.py b/docs_src/custom_request_and_route/tutorial001.py index 2e64ad45d8b56..268ce9019e9e8 100644 --- a/docs_src/custom_request_and_route/tutorial001.py +++ b/docs_src/custom_request_and_route/tutorial001.py @@ -31,5 +31,5 @@ async def custom_route_handler(request: Request) -> Response: @app.post("/sum") -async def sum_numbers(numbers: List[int] = Body(...)): +async def sum_numbers(numbers: List[int] = Body()): return {"sum": sum(numbers)} diff --git a/docs_src/custom_request_and_route/tutorial002.py b/docs_src/custom_request_and_route/tutorial002.py index f4c093ac9c6e5..cee4a95f088c7 100644 --- a/docs_src/custom_request_and_route/tutorial002.py +++ b/docs_src/custom_request_and_route/tutorial002.py @@ -25,5 +25,5 @@ async def custom_route_handler(request: Request) -> Response: @app.post("/") -async def sum_numbers(numbers: List[int] = Body(...)): +async def sum_numbers(numbers: List[int] = Body()): return sum(numbers) diff --git a/docs_src/dependencies/tutorial005.py b/docs_src/dependencies/tutorial005.py index c8923d143dcdb..24f73c6178032 100644 --- a/docs_src/dependencies/tutorial005.py +++ b/docs_src/dependencies/tutorial005.py @@ -10,7 +10,7 @@ def query_extractor(q: Optional[str] = None): def query_or_cookie_extractor( - q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(None) + q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(default=None) ): if not q: return last_query diff --git a/docs_src/dependencies/tutorial005_py310.py b/docs_src/dependencies/tutorial005_py310.py index 5e1d7e0ef0423..247cdabe213a8 100644 --- a/docs_src/dependencies/tutorial005_py310.py +++ b/docs_src/dependencies/tutorial005_py310.py @@ -8,7 +8,7 @@ def query_extractor(q: str | None = None): def query_or_cookie_extractor( - q: str = Depends(query_extractor), last_query: str | None = Cookie(None) + q: str = Depends(query_extractor), last_query: str | None = Cookie(default=None) ): if not q: return last_query diff --git a/docs_src/dependencies/tutorial006.py b/docs_src/dependencies/tutorial006.py index a71d7cce6ea5d..9aff4154f4436 100644 --- a/docs_src/dependencies/tutorial006.py +++ b/docs_src/dependencies/tutorial006.py @@ -3,12 +3,12 @@ app = FastAPI() -async def verify_token(x_token: str = Header(...)): +async def verify_token(x_token: str = Header()): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") -async def verify_key(x_key: str = Header(...)): +async def verify_key(x_key: str = Header()): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key diff --git a/docs_src/dependencies/tutorial012.py b/docs_src/dependencies/tutorial012.py index 8f8868a559e3f..36ce6c7111e67 100644 --- a/docs_src/dependencies/tutorial012.py +++ b/docs_src/dependencies/tutorial012.py @@ -1,12 +1,12 @@ from fastapi import Depends, FastAPI, Header, HTTPException -async def verify_token(x_token: str = Header(...)): +async def verify_token(x_token: str = Header()): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") -async def verify_key(x_key: str = Header(...)): +async def verify_key(x_key: str = Header()): if x_key != "fake-super-secret-key": raise HTTPException(status_code=400, detail="X-Key header invalid") return x_key diff --git a/docs_src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001.py index e8d7e1ea32475..9f5e911bfab02 100644 --- a/docs_src/extra_data_types/tutorial001.py +++ b/docs_src/extra_data_types/tutorial001.py @@ -10,10 +10,10 @@ @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Optional[datetime] = Body(None), - end_datetime: Optional[datetime] = Body(None), - repeat_at: Optional[time] = Body(None), - process_after: Optional[timedelta] = Body(None), + 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_process = start_datetime + process_after duration = end_datetime - start_process diff --git a/docs_src/extra_data_types/tutorial001_py310.py b/docs_src/extra_data_types/tutorial001_py310.py index 4a33481b77d47..d22f818886d9d 100644 --- a/docs_src/extra_data_types/tutorial001_py310.py +++ b/docs_src/extra_data_types/tutorial001_py310.py @@ -9,10 +9,10 @@ @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: datetime | None = Body(None), - end_datetime: datetime | None = Body(None), - repeat_at: time | None = Body(None), - process_after: timedelta | None = Body(None), + start_datetime: datetime | None = Body(default=None), + end_datetime: datetime | None = Body(default=None), + repeat_at: time | None = Body(default=None), + process_after: timedelta | None = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process diff --git a/docs_src/header_params/tutorial001.py b/docs_src/header_params/tutorial001.py index 7d69b027eec5b..1df561a12fb30 100644 --- a/docs_src/header_params/tutorial001.py +++ b/docs_src/header_params/tutorial001.py @@ -6,5 +6,5 @@ @app.get("/items/") -async def read_items(user_agent: Optional[str] = Header(None)): +async def read_items(user_agent: Optional[str] = Header(default=None)): return {"User-Agent": user_agent} diff --git a/docs_src/header_params/tutorial001_py310.py b/docs_src/header_params/tutorial001_py310.py index b2846334659fb..2203ed1b8b62b 100644 --- a/docs_src/header_params/tutorial001_py310.py +++ b/docs_src/header_params/tutorial001_py310.py @@ -4,5 +4,5 @@ @app.get("/items/") -async def read_items(user_agent: str | None = Header(None)): +async def read_items(user_agent: 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 2de3dddd70ac6..2250727f6d598 100644 --- a/docs_src/header_params/tutorial002.py +++ b/docs_src/header_params/tutorial002.py @@ -7,6 +7,6 @@ @app.get("/items/") async def read_items( - strange_header: Optional[str] = Header(None, convert_underscores=False) + strange_header: Optional[str] = Header(default=None, convert_underscores=False) ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_py310.py b/docs_src/header_params/tutorial002_py310.py index 98ab5a807d6a5..b7979b542a143 100644 --- a/docs_src/header_params/tutorial002_py310.py +++ b/docs_src/header_params/tutorial002_py310.py @@ -5,6 +5,6 @@ @app.get("/items/") async def read_items( - strange_header: str | None = Header(None, convert_underscores=False) + strange_header: 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 6d0eefdd2141a..1ef131cee3c14 100644 --- a/docs_src/header_params/tutorial003.py +++ b/docs_src/header_params/tutorial003.py @@ -6,5 +6,5 @@ @app.get("/items/") -async def read_items(x_token: Optional[List[str]] = Header(None)): +async def read_items(x_token: Optional[List[str]] = Header(default=None)): return {"X-Token values": x_token} diff --git a/docs_src/header_params/tutorial003_py310.py b/docs_src/header_params/tutorial003_py310.py index 2dac2c13cf186..435c67574b0cd 100644 --- a/docs_src/header_params/tutorial003_py310.py +++ b/docs_src/header_params/tutorial003_py310.py @@ -4,5 +4,5 @@ @app.get("/items/") -async def read_items(x_token: list[str] | None = Header(None)): +async def read_items(x_token: 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 359766527eb87..78dda58da49f9 100644 --- a/docs_src/header_params/tutorial003_py39.py +++ b/docs_src/header_params/tutorial003_py39.py @@ -6,5 +6,5 @@ @app.get("/items/") -async def read_items(x_token: Optional[list[str]] = Header(None)): +async def read_items(x_token: Optional[list[str]] = Header(default=None)): return {"X-Token values": x_token} diff --git a/docs_src/path_params_numeric_validations/tutorial001.py b/docs_src/path_params_numeric_validations/tutorial001.py index 11777bba77b99..53014702826e3 100644 --- a/docs_src/path_params_numeric_validations/tutorial001.py +++ b/docs_src/path_params_numeric_validations/tutorial001.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Path, Query @@ -7,8 +7,8 @@ @app.get("/items/{item_id}") async def read_items( - item_id: int = Path(..., title="The ID of the item to get"), - q: Optional[str] = Query(None, alias="item-query"), + item_id: int = Path(title="The ID of the item to get"), + q: Union[str, None] = Query(default=None, alias="item-query"), ): results = {"item_id": item_id} if q: diff --git a/docs_src/path_params_numeric_validations/tutorial001_py310.py b/docs_src/path_params_numeric_validations/tutorial001_py310.py index b940a0949f6de..b1a77cc9dd1df 100644 --- a/docs_src/path_params_numeric_validations/tutorial001_py310.py +++ b/docs_src/path_params_numeric_validations/tutorial001_py310.py @@ -5,8 +5,8 @@ @app.get("/items/{item_id}") async def read_items( - item_id: int = Path(..., title="The ID of the item to get"), - q: str | None = Query(None, alias="item-query"), + item_id: int = Path(title="The ID of the item to get"), + q: str | None = Query(default=None, alias="item-query"), ): results = {"item_id": item_id} if q: diff --git a/docs_src/path_params_numeric_validations/tutorial002.py b/docs_src/path_params_numeric_validations/tutorial002.py index 57ca50ece0179..63ac691a8347e 100644 --- a/docs_src/path_params_numeric_validations/tutorial002.py +++ b/docs_src/path_params_numeric_validations/tutorial002.py @@ -4,9 +4,7 @@ @app.get("/items/{item_id}") -async def read_items( - q: str, item_id: int = Path(..., title="The ID of the item to get") -): +async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")): results = {"item_id": item_id} if q: results.update({"q": q}) diff --git a/docs_src/path_params_numeric_validations/tutorial003.py b/docs_src/path_params_numeric_validations/tutorial003.py index b6b5a19869b0d..8df0ffc6202bd 100644 --- a/docs_src/path_params_numeric_validations/tutorial003.py +++ b/docs_src/path_params_numeric_validations/tutorial003.py @@ -4,9 +4,7 @@ @app.get("/items/{item_id}") -async def read_items( - *, item_id: int = Path(..., title="The ID of the item to get"), q: str -): +async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str): results = {"item_id": item_id} if q: results.update({"q": q}) diff --git a/docs_src/path_params_numeric_validations/tutorial004.py b/docs_src/path_params_numeric_validations/tutorial004.py index 2ec70828013e5..86651d47cfee2 100644 --- a/docs_src/path_params_numeric_validations/tutorial004.py +++ b/docs_src/path_params_numeric_validations/tutorial004.py @@ -5,7 +5,7 @@ @app.get("/items/{item_id}") async def read_items( - *, item_id: int = Path(..., title="The ID of the item to get", ge=1), q: str + *, item_id: int = Path(title="The ID of the item to get", ge=1), q: str ): results = {"item_id": item_id} if q: diff --git a/docs_src/path_params_numeric_validations/tutorial005.py b/docs_src/path_params_numeric_validations/tutorial005.py index 2809f37b27ed3..8f12f2da02659 100644 --- a/docs_src/path_params_numeric_validations/tutorial005.py +++ b/docs_src/path_params_numeric_validations/tutorial005.py @@ -6,7 +6,7 @@ @app.get("/items/{item_id}") async def read_items( *, - item_id: int = Path(..., title="The ID of the item to get", gt=0, le=1000), + item_id: int = Path(title="The ID of the item to get", gt=0, le=1000), q: str, ): results = {"item_id": item_id} diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py index 0c19579f5e3b2..85bd6e8b4d258 100644 --- a/docs_src/path_params_numeric_validations/tutorial006.py +++ b/docs_src/path_params_numeric_validations/tutorial006.py @@ -6,9 +6,9 @@ @app.get("/items/{item_id}") async def read_items( *, - item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000), + item_id: int = Path(title="The ID of the item to get", ge=0, le=1000), q: str, - size: float = Query(..., gt=0, lt=10.5) + size: float = Query(gt=0, lt=10.5) ): results = {"item_id": item_id} if q: diff --git a/docs_src/query_params_str_validations/tutorial002.py b/docs_src/query_params_str_validations/tutorial002.py index 68ea582061a00..17e017b7e7142 100644 --- a/docs_src/query_params_str_validations/tutorial002.py +++ b/docs_src/query_params_str_validations/tutorial002.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -6,7 +6,7 @@ @app.get("/items/") -async def read_items(q: Optional[str] = Query(None, max_length=50)): +async def read_items(q: Union[str, None] = Query(default=None, max_length=50)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial002_py310.py b/docs_src/query_params_str_validations/tutorial002_py310.py index fa3139d5aadf7..f15351d290ee9 100644 --- a/docs_src/query_params_str_validations/tutorial002_py310.py +++ b/docs_src/query_params_str_validations/tutorial002_py310.py @@ -4,7 +4,7 @@ @app.get("/items/") -async def read_items(q: str | None = Query(None, max_length=50)): +async def read_items(q: str | None = Query(default=None, max_length=50)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial003.py b/docs_src/query_params_str_validations/tutorial003.py index e52acc72f0fea..73d2e08c8ef0d 100644 --- a/docs_src/query_params_str_validations/tutorial003.py +++ b/docs_src/query_params_str_validations/tutorial003.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -6,7 +6,9 @@ @app.get("/items/") -async def read_items(q: Optional[str] = Query(None, min_length=3, max_length=50)): +async def read_items( + q: Union[str, None] = Query(default=None, min_length=3, max_length=50) +): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial003_py310.py b/docs_src/query_params_str_validations/tutorial003_py310.py index 335858a404c92..dc60ecb39da7b 100644 --- a/docs_src/query_params_str_validations/tutorial003_py310.py +++ b/docs_src/query_params_str_validations/tutorial003_py310.py @@ -4,7 +4,7 @@ @app.get("/items/") -async def read_items(q: str | None = Query(None, min_length=3, max_length=50)): +async def read_items(q: str | None = Query(default=None, min_length=3, max_length=50)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial004.py b/docs_src/query_params_str_validations/tutorial004.py index d2c30331f63a0..5a7129816c4a6 100644 --- a/docs_src/query_params_str_validations/tutorial004.py +++ b/docs_src/query_params_str_validations/tutorial004.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -7,7 +7,9 @@ @app.get("/items/") async def read_items( - q: Optional[str] = Query(None, min_length=3, max_length=50, regex="^fixedquery$") + q: Union[str, None] = Query( + default=None, min_length=3, max_length=50, regex="^fixedquery$" + ) ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004_py310.py b/docs_src/query_params_str_validations/tutorial004_py310.py index 518b779f70ff6..180a2e5112a0b 100644 --- a/docs_src/query_params_str_validations/tutorial004_py310.py +++ b/docs_src/query_params_str_validations/tutorial004_py310.py @@ -5,7 +5,8 @@ @app.get("/items/") async def read_items( - q: str | None = Query(None, min_length=3, max_length=50, regex="^fixedquery$") + q: str + | None = Query(default=None, min_length=3, max_length=50, regex="^fixedquery$") ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial005.py b/docs_src/query_params_str_validations/tutorial005.py index 22eb3acba16c9..8ab42869e6140 100644 --- a/docs_src/query_params_str_validations/tutorial005.py +++ b/docs_src/query_params_str_validations/tutorial005.py @@ -4,7 +4,7 @@ @app.get("/items/") -async def read_items(q: str = Query("fixedquery", min_length=3)): +async def read_items(q: str = Query(default="fixedquery", min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006.py b/docs_src/query_params_str_validations/tutorial006.py index 720bf07f1a9df..9a90eb64efafa 100644 --- a/docs_src/query_params_str_validations/tutorial006.py +++ b/docs_src/query_params_str_validations/tutorial006.py @@ -4,7 +4,7 @@ @app.get("/items/") -async def read_items(q: str = Query(..., min_length=3)): +async def read_items(q: str = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006b.py b/docs_src/query_params_str_validations/tutorial006b.py new file mode 100644 index 0000000000000..a8d69c8899cf0 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial006b.py @@ -0,0 +1,11 @@ +from fastapi import FastAPI, Query + +app = FastAPI() + + +@app.get("/items/") +async def read_items(q: str = Query(default=..., min_length=3)): + results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + if q: + results.update({"q": q}) + return results diff --git a/docs_src/query_params_str_validations/tutorial006c.py b/docs_src/query_params_str_validations/tutorial006c.py new file mode 100644 index 0000000000000..2ac148c94f623 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial006c.py @@ -0,0 +1,13 @@ +from typing import Union + +from fastapi import FastAPI, Query + +app = FastAPI() + + +@app.get("/items/") +async def read_items(q: Union[str, None] = Query(default=..., min_length=3)): + results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + if q: + results.update({"q": q}) + return results diff --git a/docs_src/query_params_str_validations/tutorial006c_py310.py b/docs_src/query_params_str_validations/tutorial006c_py310.py new file mode 100644 index 0000000000000..82dd9e5d7c30c --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial006c_py310.py @@ -0,0 +1,11 @@ +from fastapi import FastAPI, Query + +app = FastAPI() + + +@app.get("/items/") +async def read_items(q: str | None = Query(default=..., min_length=3)): + results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + if q: + results.update({"q": q}) + return results diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py new file mode 100644 index 0000000000000..42c5bf4ebb57f --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial006d.py @@ -0,0 +1,12 @@ +from fastapi import FastAPI, Query +from pydantic import Required + +app = FastAPI() + + +@app.get("/items/") +async def read_items(q: str = Query(default=Required, min_length=3)): + results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} + if q: + results.update({"q": q}) + return results diff --git a/docs_src/query_params_str_validations/tutorial007.py b/docs_src/query_params_str_validations/tutorial007.py index e360feda9f07a..cb836569e980e 100644 --- a/docs_src/query_params_str_validations/tutorial007.py +++ b/docs_src/query_params_str_validations/tutorial007.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Optional[str] = Query(None, title="Query string", min_length=3) + q: Union[str, None] = Query(default=None, title="Query string", min_length=3) ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_py310.py b/docs_src/query_params_str_validations/tutorial007_py310.py index 14ef4cb69fc33..e3e1ef2e08711 100644 --- a/docs_src/query_params_str_validations/tutorial007_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_py310.py @@ -4,7 +4,9 @@ @app.get("/items/") -async def read_items(q: str | None = Query(None, title="Query string", min_length=3)): +async def read_items( + q: str | None = Query(default=None, title="Query string", min_length=3) +): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial008.py b/docs_src/query_params_str_validations/tutorial008.py index 238add4710425..d112a9ab8aa5a 100644 --- a/docs_src/query_params_str_validations/tutorial008.py +++ b/docs_src/query_params_str_validations/tutorial008.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -7,8 +7,8 @@ @app.get("/items/") async def read_items( - q: Optional[str] = Query( - None, + q: Union[str, None] = Query( + default=None, title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, diff --git a/docs_src/query_params_str_validations/tutorial008_py310.py b/docs_src/query_params_str_validations/tutorial008_py310.py index 06bb02442bde8..489f631d5e908 100644 --- a/docs_src/query_params_str_validations/tutorial008_py310.py +++ b/docs_src/query_params_str_validations/tutorial008_py310.py @@ -7,7 +7,7 @@ async def read_items( q: str | None = Query( - None, + default=None, title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, diff --git a/docs_src/query_params_str_validations/tutorial009.py b/docs_src/query_params_str_validations/tutorial009.py index 7e5c0b81a8a84..8a6bfe2d93fb3 100644 --- a/docs_src/query_params_str_validations/tutorial009.py +++ b/docs_src/query_params_str_validations/tutorial009.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -6,7 +6,7 @@ @app.get("/items/") -async def read_items(q: Optional[str] = Query(None, alias="item-query")): +async def read_items(q: Union[str, None] = Query(default=None, alias="item-query")): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial009_py310.py b/docs_src/query_params_str_validations/tutorial009_py310.py index e84c116f12760..a38d32cbbd2b6 100644 --- a/docs_src/query_params_str_validations/tutorial009_py310.py +++ b/docs_src/query_params_str_validations/tutorial009_py310.py @@ -4,7 +4,7 @@ @app.get("/items/") -async def read_items(q: str | None = Query(None, alias="item-query")): +async def read_items(q: str | None = Query(default=None, alias="item-query")): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial010.py b/docs_src/query_params_str_validations/tutorial010.py index 7921506b653d4..35443d1947061 100644 --- a/docs_src/query_params_str_validations/tutorial010.py +++ b/docs_src/query_params_str_validations/tutorial010.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -7,8 +7,8 @@ @app.get("/items/") async def read_items( - q: Optional[str] = Query( - None, + q: Union[str, None] = Query( + default=None, alias="item-query", title="Query string", description="Query string for the items to search in the database that have a good match", diff --git a/docs_src/query_params_str_validations/tutorial010_py310.py b/docs_src/query_params_str_validations/tutorial010_py310.py index c35800858d122..f2839516e6446 100644 --- a/docs_src/query_params_str_validations/tutorial010_py310.py +++ b/docs_src/query_params_str_validations/tutorial010_py310.py @@ -7,7 +7,7 @@ async def read_items( q: str | None = Query( - None, + default=None, alias="item-query", title="Query string", description="Query string for the items to search in the database that have a good match", diff --git a/docs_src/query_params_str_validations/tutorial011.py b/docs_src/query_params_str_validations/tutorial011.py index 7fda267edd59d..65bbce781ac41 100644 --- a/docs_src/query_params_str_validations/tutorial011.py +++ b/docs_src/query_params_str_validations/tutorial011.py @@ -1,4 +1,4 @@ -from typing import List, Optional +from typing import List, Union from fastapi import FastAPI, Query @@ -6,6 +6,6 @@ @app.get("/items/") -async def read_items(q: Optional[List[str]] = Query(None)): +async def read_items(q: Union[List[str], None] = Query(default=None)): query_items = {"q": q} return query_items diff --git a/docs_src/query_params_str_validations/tutorial011_py310.py b/docs_src/query_params_str_validations/tutorial011_py310.py index c3d992e625b6d..70155de7c9a28 100644 --- a/docs_src/query_params_str_validations/tutorial011_py310.py +++ b/docs_src/query_params_str_validations/tutorial011_py310.py @@ -4,6 +4,6 @@ @app.get("/items/") -async def read_items(q: list[str] | None = Query(None)): +async def read_items(q: list[str] | None = Query(default=None)): query_items = {"q": q} return query_items diff --git a/docs_src/query_params_str_validations/tutorial011_py39.py b/docs_src/query_params_str_validations/tutorial011_py39.py index 38ba764d6fcf2..878f95c7984cf 100644 --- a/docs_src/query_params_str_validations/tutorial011_py39.py +++ b/docs_src/query_params_str_validations/tutorial011_py39.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -6,6 +6,6 @@ @app.get("/items/") -async def read_items(q: Optional[list[str]] = Query(None)): +async def read_items(q: Union[list[str], None] = Query(default=None)): query_items = {"q": q} return query_items diff --git a/docs_src/query_params_str_validations/tutorial012.py b/docs_src/query_params_str_validations/tutorial012.py index 7ea9f017dfa6e..e77d56974de91 100644 --- a/docs_src/query_params_str_validations/tutorial012.py +++ b/docs_src/query_params_str_validations/tutorial012.py @@ -6,6 +6,6 @@ @app.get("/items/") -async def read_items(q: List[str] = Query(["foo", "bar"])): +async def read_items(q: List[str] = Query(default=["foo", "bar"])): query_items = {"q": q} return query_items diff --git a/docs_src/query_params_str_validations/tutorial012_py39.py b/docs_src/query_params_str_validations/tutorial012_py39.py index 1900133d9f768..070d0b04bfd03 100644 --- a/docs_src/query_params_str_validations/tutorial012_py39.py +++ b/docs_src/query_params_str_validations/tutorial012_py39.py @@ -4,6 +4,6 @@ @app.get("/items/") -async def read_items(q: list[str] = Query(["foo", "bar"])): +async def read_items(q: list[str] = Query(default=["foo", "bar"])): query_items = {"q": q} return query_items diff --git a/docs_src/query_params_str_validations/tutorial013.py b/docs_src/query_params_str_validations/tutorial013.py index 95dd6999dd0f4..0b0f44869fd5f 100644 --- a/docs_src/query_params_str_validations/tutorial013.py +++ b/docs_src/query_params_str_validations/tutorial013.py @@ -4,6 +4,6 @@ @app.get("/items/") -async def read_items(q: list = Query([])): +async def read_items(q: list = Query(default=[])): query_items = {"q": q} return query_items diff --git a/docs_src/query_params_str_validations/tutorial014.py b/docs_src/query_params_str_validations/tutorial014.py index fb50bc27b5639..50e0a6c2b18ce 100644 --- a/docs_src/query_params_str_validations/tutorial014.py +++ b/docs_src/query_params_str_validations/tutorial014.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Union from fastapi import FastAPI, Query @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - hidden_query: Optional[str] = Query(None, include_in_schema=False) + hidden_query: Union[str, None] = Query(default=None, include_in_schema=False) ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_py310.py b/docs_src/query_params_str_validations/tutorial014_py310.py index 7ae39c7f97e16..1b617efdd128a 100644 --- a/docs_src/query_params_str_validations/tutorial014_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_py310.py @@ -4,7 +4,9 @@ @app.get("/items/") -async def read_items(hidden_query: str | None = Query(None, include_in_schema=False)): +async def read_items( + hidden_query: str | None = Query(default=None, include_in_schema=False) +): if hidden_query: return {"hidden_query": hidden_query} else: diff --git a/docs_src/request_files/tutorial001.py b/docs_src/request_files/tutorial001.py index 0fb1dd571b1b0..2e0ea6391278d 100644 --- a/docs_src/request_files/tutorial001.py +++ b/docs_src/request_files/tutorial001.py @@ -4,7 +4,7 @@ @app.post("/files/") -async def create_file(file: bytes = File(...)): +async def create_file(file: bytes = File()): return {"file_size": len(file)} diff --git a/docs_src/request_files/tutorial001_02.py b/docs_src/request_files/tutorial001_02.py index 26a4c9cbf069d..3f311c4b853f1 100644 --- a/docs_src/request_files/tutorial001_02.py +++ b/docs_src/request_files/tutorial001_02.py @@ -6,7 +6,7 @@ @app.post("/files/") -async def create_file(file: Optional[bytes] = File(None)): +async def create_file(file: Optional[bytes] = File(default=None)): if not file: return {"message": "No file sent"} else: diff --git a/docs_src/request_files/tutorial001_02_py310.py b/docs_src/request_files/tutorial001_02_py310.py index 0e576251b57b3..298c9974f2fe9 100644 --- a/docs_src/request_files/tutorial001_02_py310.py +++ b/docs_src/request_files/tutorial001_02_py310.py @@ -4,7 +4,7 @@ @app.post("/files/") -async def create_file(file: bytes | None = File(None)): +async def create_file(file: bytes | None = File(default=None)): if not file: return {"message": "No file sent"} else: diff --git a/docs_src/request_files/tutorial001_03.py b/docs_src/request_files/tutorial001_03.py index abcac9e4c1cb2..d8005cc7d2822 100644 --- a/docs_src/request_files/tutorial001_03.py +++ b/docs_src/request_files/tutorial001_03.py @@ -4,12 +4,12 @@ @app.post("/files/") -async def create_file(file: bytes = File(..., description="A file read as bytes")): +async def create_file(file: bytes = File(description="A file read as bytes")): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file( - file: UploadFile = File(..., description="A file read as UploadFile") + file: UploadFile = File(description="A file read as UploadFile"), ): return {"filename": file.filename} diff --git a/docs_src/request_files/tutorial002.py b/docs_src/request_files/tutorial002.py index 94abb7c6c0492..b4d0acc68f1ad 100644 --- a/docs_src/request_files/tutorial002.py +++ b/docs_src/request_files/tutorial002.py @@ -7,7 +7,7 @@ @app.post("/files/") -async def create_files(files: List[bytes] = File(...)): +async def create_files(files: List[bytes] = File()): return {"file_sizes": [len(file) for file in files]} diff --git a/docs_src/request_files/tutorial002_py39.py b/docs_src/request_files/tutorial002_py39.py index 2779618bde83f..b64cf55987898 100644 --- a/docs_src/request_files/tutorial002_py39.py +++ b/docs_src/request_files/tutorial002_py39.py @@ -5,7 +5,7 @@ @app.post("/files/") -async def create_files(files: list[bytes] = File(...)): +async def create_files(files: list[bytes] = File()): return {"file_sizes": [len(file) for file in files]} diff --git a/docs_src/request_files/tutorial003.py b/docs_src/request_files/tutorial003.py index 4a91b7a8bc611..e3f805f605262 100644 --- a/docs_src/request_files/tutorial003.py +++ b/docs_src/request_files/tutorial003.py @@ -8,14 +8,14 @@ @app.post("/files/") async def create_files( - files: List[bytes] = File(..., description="Multiple files as bytes") + files: List[bytes] = File(description="Multiple files as bytes"), ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files( - files: List[UploadFile] = File(..., description="Multiple files as UploadFile") + files: List[UploadFile] = File(description="Multiple files as UploadFile"), ): return {"filenames": [file.filename for file in files]} diff --git a/docs_src/request_files/tutorial003_py39.py b/docs_src/request_files/tutorial003_py39.py index d853f48d11357..96f5e8742dcfc 100644 --- a/docs_src/request_files/tutorial003_py39.py +++ b/docs_src/request_files/tutorial003_py39.py @@ -6,14 +6,14 @@ @app.post("/files/") async def create_files( - files: list[bytes] = File(..., description="Multiple files as bytes") + files: list[bytes] = File(description="Multiple files as bytes"), ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files( - files: list[UploadFile] = File(..., description="Multiple files as UploadFile") + files: list[UploadFile] = File(description="Multiple files as UploadFile"), ): return {"filenames": [file.filename for file in files]} diff --git a/docs_src/request_forms/tutorial001.py b/docs_src/request_forms/tutorial001.py index c07e2294585eb..a537700019d17 100644 --- a/docs_src/request_forms/tutorial001.py +++ b/docs_src/request_forms/tutorial001.py @@ -4,5 +4,5 @@ @app.post("/login/") -async def login(username: str = Form(...), password: str = Form(...)): +async def login(username: str = Form(), password: str = Form()): return {"username": username} diff --git a/docs_src/request_forms_and_files/tutorial001.py b/docs_src/request_forms_and_files/tutorial001.py index 5bf3a5bc0530e..7b5224ce53583 100644 --- a/docs_src/request_forms_and_files/tutorial001.py +++ b/docs_src/request_forms_and_files/tutorial001.py @@ -5,7 +5,7 @@ @app.post("/files/") async def create_file( - file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...) + file: bytes = File(), fileb: UploadFile = File(), token: str = Form() ): return { "file_size": len(file), diff --git a/docs_src/schema_extra_example/tutorial002.py b/docs_src/schema_extra_example/tutorial002.py index df3df8854719a..a2aec46f54fe4 100644 --- a/docs_src/schema_extra_example/tutorial002.py +++ b/docs_src/schema_extra_example/tutorial002.py @@ -7,10 +7,10 @@ class Item(BaseModel): - name: str = Field(..., example="Foo") - description: Optional[str] = Field(None, example="A very nice Item") - price: float = Field(..., example=35.4) - tax: Optional[float] = Field(None, example=3.2) + name: str = Field(example="Foo") + description: Optional[str] = Field(default=None, example="A very nice Item") + price: float = Field(example=35.4) + tax: Optional[float] = Field(default=None, example=3.2) @app.put("/items/{item_id}") diff --git a/docs_src/schema_extra_example/tutorial002_py310.py b/docs_src/schema_extra_example/tutorial002_py310.py index 4f8f8304ec82d..e84928bb11980 100644 --- a/docs_src/schema_extra_example/tutorial002_py310.py +++ b/docs_src/schema_extra_example/tutorial002_py310.py @@ -5,10 +5,10 @@ class Item(BaseModel): - name: str = Field(..., example="Foo") - description: str | None = Field(None, example="A very nice Item") - price: float = Field(..., example=35.4) - tax: float | None = Field(None, example=3.2) + name: str = Field(example="Foo") + description: str | None = Field(default=None, example="A very nice Item") + price: float = Field(example=35.4) + tax: 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 58c79f55439f2..43d46b81ba953 100644 --- a/docs_src/schema_extra_example/tutorial003.py +++ b/docs_src/schema_extra_example/tutorial003.py @@ -17,7 +17,6 @@ class Item(BaseModel): async def update_item( item_id: int, item: Item = Body( - ..., example={ "name": "Foo", "description": "A very nice Item", diff --git a/docs_src/schema_extra_example/tutorial003_py310.py b/docs_src/schema_extra_example/tutorial003_py310.py index cf4c99dc033f6..1e137101d9e46 100644 --- a/docs_src/schema_extra_example/tutorial003_py310.py +++ b/docs_src/schema_extra_example/tutorial003_py310.py @@ -15,7 +15,6 @@ class Item(BaseModel): async def update_item( item_id: int, item: Item = Body( - ..., example={ "name": "Foo", "description": "A very nice Item", diff --git a/docs_src/schema_extra_example/tutorial004.py b/docs_src/schema_extra_example/tutorial004.py index 9f0e8b43787a1..42d7a04a3c1d3 100644 --- a/docs_src/schema_extra_example/tutorial004.py +++ b/docs_src/schema_extra_example/tutorial004.py @@ -18,7 +18,6 @@ async def update_item( *, item_id: int, item: Item = Body( - ..., examples={ "normal": { "summary": "A normal example", diff --git a/docs_src/schema_extra_example/tutorial004_py310.py b/docs_src/schema_extra_example/tutorial004_py310.py index 6f29c1a5c67d3..100a30860b01a 100644 --- a/docs_src/schema_extra_example/tutorial004_py310.py +++ b/docs_src/schema_extra_example/tutorial004_py310.py @@ -16,7 +16,6 @@ async def update_item( *, item_id: int, item: Item = Body( - ..., examples={ "normal": { "summary": "A normal example", diff --git a/docs_src/websockets/tutorial002.py b/docs_src/websockets/tutorial002.py index 53cdb41ff1b54..b010085303b2b 100644 --- a/docs_src/websockets/tutorial002.py +++ b/docs_src/websockets/tutorial002.py @@ -57,8 +57,8 @@ async def get(): async def get_cookie_or_token( websocket: WebSocket, - session: Optional[str] = Cookie(None), - token: Optional[str] = Query(None), + session: Optional[str] = Cookie(default=None), + token: Optional[str] = Query(default=None), ): if session is None and token is None: await websocket.close(code=status.WS_1008_POLICY_VIOLATION) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 9dccd354efe7e..f397e333c0928 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -43,6 +43,7 @@ FieldInfo, ModelField, Required, + Undefined, ) from pydantic.schema import get_annotation_from_field_info from pydantic.typing import ForwardRef, evaluate_forwardref @@ -316,7 +317,7 @@ def get_dependant( field_info = param_field.field_info assert isinstance( field_info, params.Body - ), f"Param: {param_field.name} can only be a request body, using Body(...)" + ), f"Param: {param_field.name} can only be a request body, using Body()" dependant.body_params.append(param_field) return dependant @@ -353,7 +354,7 @@ def get_param_field( force_type: Optional[params.ParamTypes] = None, ignore_default: bool = False, ) -> ModelField: - default_value = Required + default_value: Any = Undefined had_schema = False if not param.default == param.empty and ignore_default is False: default_value = param.default @@ -369,8 +370,13 @@ def get_param_field( if force_type: field_info.in_ = force_type # type: ignore else: - field_info = default_field_info(default_value) - required = default_value == Required + field_info = default_field_info(default=default_value) + required = True + if default_value is Required or ignore_default: + required = True + default_value = None + elif default_value is not Undefined: + required = False annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation @@ -382,12 +388,11 @@ def get_param_field( field = create_response_field( name=param.name, type_=annotation, - default=None if required else default_value, + default=default_value, alias=alias, required=required, field_info=field_info, ) - field.required = required if not had_schema and not is_scalar_field(field=field): field.field_info = params.Body(field_info.default) if not had_schema and lenient_issubclass(field.type_, UploadFile): diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py index 9c6598d2d1a7b..35aa1672b3cc0 100644 --- a/fastapi/openapi/models.py +++ b/fastapi/openapi/models.py @@ -73,7 +73,7 @@ class Config: class Reference(BaseModel): - ref: str = Field(..., alias="$ref") + ref: str = Field(alias="$ref") class Discriminator(BaseModel): @@ -101,28 +101,28 @@ class Config: class Schema(BaseModel): - ref: Optional[str] = Field(None, alias="$ref") + ref: Optional[str] = Field(default=None, alias="$ref") title: Optional[str] = None multipleOf: Optional[float] = None maximum: Optional[float] = None exclusiveMaximum: Optional[float] = None minimum: Optional[float] = None exclusiveMinimum: Optional[float] = None - maxLength: Optional[int] = Field(None, gte=0) - minLength: Optional[int] = Field(None, gte=0) + maxLength: Optional[int] = Field(default=None, gte=0) + minLength: Optional[int] = Field(default=None, gte=0) pattern: Optional[str] = None - maxItems: Optional[int] = Field(None, gte=0) - minItems: Optional[int] = Field(None, gte=0) + maxItems: Optional[int] = Field(default=None, gte=0) + minItems: Optional[int] = Field(default=None, gte=0) uniqueItems: Optional[bool] = None - maxProperties: Optional[int] = Field(None, gte=0) - minProperties: Optional[int] = Field(None, gte=0) + maxProperties: Optional[int] = Field(default=None, gte=0) + minProperties: Optional[int] = Field(default=None, gte=0) required: Optional[List[str]] = None enum: Optional[List[Any]] = None type: Optional[str] = None allOf: Optional[List["Schema"]] = None oneOf: Optional[List["Schema"]] = None anyOf: Optional[List["Schema"]] = None - not_: Optional["Schema"] = Field(None, alias="not") + not_: Optional["Schema"] = Field(default=None, alias="not") items: Optional[Union["Schema", List["Schema"]]] = None properties: Optional[Dict[str, "Schema"]] = None additionalProperties: Optional[Union["Schema", Reference, bool]] = None @@ -171,7 +171,7 @@ class Config: class MediaType(BaseModel): - schema_: Optional[Union[Schema, Reference]] = Field(None, alias="schema") + schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None encoding: Optional[Dict[str, Encoding]] = None @@ -188,7 +188,7 @@ class ParameterBase(BaseModel): style: Optional[str] = None explode: Optional[bool] = None allowReserved: Optional[bool] = None - schema_: Optional[Union[Schema, Reference]] = Field(None, alias="schema") + schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None # Serialization rules for more complex scenarios @@ -200,7 +200,7 @@ class Config: class Parameter(ParameterBase): name: str - in_: ParameterInType = Field(..., alias="in") + in_: ParameterInType = Field(alias="in") class Header(ParameterBase): @@ -258,7 +258,7 @@ class Config: class PathItem(BaseModel): - ref: Optional[str] = Field(None, alias="$ref") + ref: Optional[str] = Field(default=None, alias="$ref") summary: Optional[str] = None description: Optional[str] = None get: Optional[Operation] = None @@ -284,7 +284,7 @@ class SecuritySchemeType(Enum): class SecurityBase(BaseModel): - type_: SecuritySchemeType = Field(..., alias="type") + type_: SecuritySchemeType = Field(alias="type") description: Optional[str] = None class Config: @@ -299,7 +299,7 @@ class APIKeyIn(Enum): class APIKey(SecurityBase): type_ = Field(SecuritySchemeType.apiKey, alias="type") - in_: APIKeyIn = Field(..., alias="in") + in_: APIKeyIn = Field(alias="in") name: str diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index a553a1461f8d7..1932ef0657d66 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -5,7 +5,7 @@ def Path( # noqa: N802 - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, title: Optional[str] = None, @@ -44,7 +44,7 @@ def Path( # noqa: N802 def Query( # noqa: N802 - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, title: Optional[str] = None, @@ -63,7 +63,7 @@ def Query( # noqa: N802 **extra: Any, ) -> Any: return params.Query( - default, + default=default, alias=alias, title=title, description=description, @@ -83,7 +83,7 @@ def Query( # noqa: N802 def Header( # noqa: N802 - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, convert_underscores: bool = True, @@ -103,7 +103,7 @@ def Header( # noqa: N802 **extra: Any, ) -> Any: return params.Header( - default, + default=default, alias=alias, convert_underscores=convert_underscores, title=title, @@ -124,7 +124,7 @@ def Header( # noqa: N802 def Cookie( # noqa: N802 - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, title: Optional[str] = None, @@ -143,7 +143,7 @@ def Cookie( # noqa: N802 **extra: Any, ) -> Any: return params.Cookie( - default, + default=default, alias=alias, title=title, description=description, @@ -163,7 +163,7 @@ def Cookie( # noqa: N802 def Body( # noqa: N802 - default: Any, + default: Any = Undefined, *, embed: bool = False, media_type: str = "application/json", @@ -182,7 +182,7 @@ def Body( # noqa: N802 **extra: Any, ) -> Any: return params.Body( - default, + default=default, embed=embed, media_type=media_type, alias=alias, @@ -202,7 +202,7 @@ def Body( # noqa: N802 def Form( # noqa: N802 - default: Any, + default: Any = Undefined, *, media_type: str = "application/x-www-form-urlencoded", alias: Optional[str] = None, @@ -220,7 +220,7 @@ def Form( # noqa: N802 **extra: Any, ) -> Any: return params.Form( - default, + default=default, media_type=media_type, alias=alias, title=title, @@ -239,7 +239,7 @@ def Form( # noqa: N802 def File( # noqa: N802 - default: Any, + default: Any = Undefined, *, media_type: str = "multipart/form-data", alias: Optional[str] = None, @@ -257,7 +257,7 @@ def File( # noqa: N802 **extra: Any, ) -> Any: return params.File( - default, + default=default, media_type=media_type, alias=alias, title=title, diff --git a/fastapi/params.py b/fastapi/params.py index 042bbd42ff8b0..5395b98a39ab1 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -16,7 +16,7 @@ class Param(FieldInfo): def __init__( self, - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, title: Optional[str] = None, @@ -39,7 +39,7 @@ def __init__( self.examples = examples self.include_in_schema = include_in_schema super().__init__( - default, + default=default, alias=alias, title=title, description=description, @@ -62,7 +62,7 @@ class Path(Param): def __init__( self, - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, title: Optional[str] = None, @@ -82,7 +82,7 @@ def __init__( ): self.in_ = self.in_ super().__init__( - ..., + default=..., alias=alias, title=title, description=description, @@ -106,7 +106,7 @@ class Query(Param): def __init__( self, - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, title: Optional[str] = None, @@ -125,7 +125,7 @@ def __init__( **extra: Any, ): super().__init__( - default, + default=default, alias=alias, title=title, description=description, @@ -149,7 +149,7 @@ class Header(Param): def __init__( self, - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, convert_underscores: bool = True, @@ -170,7 +170,7 @@ def __init__( ): self.convert_underscores = convert_underscores super().__init__( - default, + default=default, alias=alias, title=title, description=description, @@ -194,7 +194,7 @@ class Cookie(Param): def __init__( self, - default: Any, + default: Any = Undefined, *, alias: Optional[str] = None, title: Optional[str] = None, @@ -213,7 +213,7 @@ def __init__( **extra: Any, ): super().__init__( - default, + default=default, alias=alias, title=title, description=description, @@ -235,7 +235,7 @@ def __init__( class Body(FieldInfo): def __init__( self, - default: Any, + default: Any = Undefined, *, embed: bool = False, media_type: str = "application/json", @@ -258,7 +258,7 @@ def __init__( self.example = example self.examples = examples super().__init__( - default, + default=default, alias=alias, title=title, description=description, @@ -297,7 +297,7 @@ def __init__( **extra: Any, ): super().__init__( - default, + default=default, embed=True, media_type=media_type, alias=alias, @@ -337,7 +337,7 @@ def __init__( **extra: Any, ): super().__init__( - default, + default=default, media_type=media_type, alias=alias, title=title, diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index bdc6e2ea9beee..888208c1501fc 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -45,12 +45,12 @@ def login(form_data: OAuth2PasswordRequestForm = Depends()): def __init__( self, - grant_type: str = Form(None, regex="password"), - username: str = Form(...), - password: str = Form(...), - scope: str = Form(""), - client_id: Optional[str] = Form(None), - client_secret: Optional[str] = Form(None), + grant_type: str = Form(default=None, regex="password"), + username: str = Form(), + password: str = Form(), + scope: str = Form(default=""), + client_id: Optional[str] = Form(default=None), + client_secret: Optional[str] = Form(default=None), ): self.grant_type = grant_type self.username = username @@ -95,12 +95,12 @@ def login(form_data: OAuth2PasswordRequestFormStrict = Depends()): def __init__( self, - grant_type: str = Form(..., regex="password"), - username: str = Form(...), - password: str = Form(...), - scope: str = Form(""), - client_id: Optional[str] = Form(None), - client_secret: Optional[str] = Form(None), + grant_type: str = Form(regex="password"), + username: str = Form(), + password: str = Form(), + scope: str = Form(default=""), + client_id: Optional[str] = Form(default=None), + client_secret: Optional[str] = Form(default=None), ): super().__init__( grant_type=grant_type, diff --git a/fastapi/utils.py b/fastapi/utils.py index 9d720feb3758a..a7e135bcab598 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -52,7 +52,7 @@ def create_response_field( Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} - field_info = field_info or FieldInfo(None) + field_info = field_info or FieldInfo() response_field = functools.partial( ModelField, diff --git a/tests/main.py b/tests/main.py index d5603d0e617e1..f70496db8e111 100644 --- a/tests/main.py +++ b/tests/main.py @@ -49,97 +49,97 @@ def get_bool_id(item_id: bool): @app.get("/path/param/{item_id}") -def get_path_param_id(item_id: Optional[str] = Path(None)): +def get_path_param_id(item_id: str = Path()): return item_id @app.get("/path/param-required/{item_id}") -def get_path_param_required_id(item_id: str = Path(...)): +def get_path_param_required_id(item_id: str = Path()): return item_id @app.get("/path/param-minlength/{item_id}") -def get_path_param_min_length(item_id: str = Path(..., min_length=3)): +def get_path_param_min_length(item_id: str = Path(min_length=3)): return item_id @app.get("/path/param-maxlength/{item_id}") -def get_path_param_max_length(item_id: str = Path(..., max_length=3)): +def get_path_param_max_length(item_id: str = Path(max_length=3)): return item_id @app.get("/path/param-min_maxlength/{item_id}") -def get_path_param_min_max_length(item_id: str = Path(..., max_length=3, min_length=2)): +def get_path_param_min_max_length(item_id: str = Path(max_length=3, min_length=2)): return item_id @app.get("/path/param-gt/{item_id}") -def get_path_param_gt(item_id: float = Path(..., gt=3)): +def get_path_param_gt(item_id: float = Path(gt=3)): return item_id @app.get("/path/param-gt0/{item_id}") -def get_path_param_gt0(item_id: float = Path(..., gt=0)): +def get_path_param_gt0(item_id: float = Path(gt=0)): return item_id @app.get("/path/param-ge/{item_id}") -def get_path_param_ge(item_id: float = Path(..., ge=3)): +def get_path_param_ge(item_id: float = Path(ge=3)): return item_id @app.get("/path/param-lt/{item_id}") -def get_path_param_lt(item_id: float = Path(..., lt=3)): +def get_path_param_lt(item_id: float = Path(lt=3)): return item_id @app.get("/path/param-lt0/{item_id}") -def get_path_param_lt0(item_id: float = Path(..., lt=0)): +def get_path_param_lt0(item_id: float = Path(lt=0)): return item_id @app.get("/path/param-le/{item_id}") -def get_path_param_le(item_id: float = Path(..., le=3)): +def get_path_param_le(item_id: float = Path(le=3)): return item_id @app.get("/path/param-lt-gt/{item_id}") -def get_path_param_lt_gt(item_id: float = Path(..., lt=3, gt=1)): +def get_path_param_lt_gt(item_id: float = Path(lt=3, gt=1)): return item_id @app.get("/path/param-le-ge/{item_id}") -def get_path_param_le_ge(item_id: float = Path(..., le=3, ge=1)): +def get_path_param_le_ge(item_id: float = Path(le=3, ge=1)): return item_id @app.get("/path/param-lt-int/{item_id}") -def get_path_param_lt_int(item_id: int = Path(..., lt=3)): +def get_path_param_lt_int(item_id: int = Path(lt=3)): return item_id @app.get("/path/param-gt-int/{item_id}") -def get_path_param_gt_int(item_id: int = Path(..., gt=3)): +def get_path_param_gt_int(item_id: int = Path(gt=3)): return item_id @app.get("/path/param-le-int/{item_id}") -def get_path_param_le_int(item_id: int = Path(..., le=3)): +def get_path_param_le_int(item_id: int = Path(le=3)): return item_id @app.get("/path/param-ge-int/{item_id}") -def get_path_param_ge_int(item_id: int = Path(..., ge=3)): +def get_path_param_ge_int(item_id: int = Path(ge=3)): return item_id @app.get("/path/param-lt-gt-int/{item_id}") -def get_path_param_lt_gt_int(item_id: int = Path(..., lt=3, gt=1)): +def get_path_param_lt_gt_int(item_id: int = Path(lt=3, gt=1)): return item_id @app.get("/path/param-le-ge-int/{item_id}") -def get_path_param_le_ge_int(item_id: int = Path(..., le=3, ge=1)): +def get_path_param_le_ge_int(item_id: int = Path(le=3, ge=1)): return item_id @@ -173,19 +173,19 @@ def get_query_type_int_default(query: int = 10): @app.get("/query/param") -def get_query_param(query=Query(None)): +def get_query_param(query=Query(default=None)): if query is None: return "foo bar" return f"foo bar {query}" @app.get("/query/param-required") -def get_query_param_required(query=Query(...)): +def get_query_param_required(query=Query()): return f"foo bar {query}" @app.get("/query/param-required/int") -def get_query_param_required_type(query: int = Query(...)): +def get_query_param_required_type(query: int = Query()): return f"foo bar {query}" diff --git a/tests/test_dependency_normal_exceptions.py b/tests/test_dependency_normal_exceptions.py index 49a19f460cc04..23c366d5d7a6f 100644 --- a/tests/test_dependency_normal_exceptions.py +++ b/tests/test_dependency_normal_exceptions.py @@ -26,14 +26,14 @@ async def get_database(): @app.put("/invalid-user/{user_id}") def put_invalid_user( - user_id: str, name: str = Body(...), db: dict = Depends(get_database) + user_id: str, name: str = Body(), db: dict = Depends(get_database) ): db[user_id] = name raise HTTPException(status_code=400, detail="Invalid user") @app.put("/user/{user_id}") -def put_user(user_id: str, name: str = Body(...), db: dict = Depends(get_database)): +def put_user(user_id: str, name: str = Body(), db: dict = Depends(get_database)): db[user_id] = name return {"message": "OK"} diff --git a/tests/test_forms_from_non_typing_sequences.py b/tests/test_forms_from_non_typing_sequences.py index be917eab7e2e0..52ce247533eb1 100644 --- a/tests/test_forms_from_non_typing_sequences.py +++ b/tests/test_forms_from_non_typing_sequences.py @@ -5,17 +5,17 @@ @app.post("/form/python-list") -def post_form_param_list(items: list = Form(...)): +def post_form_param_list(items: list = Form()): return items @app.post("/form/python-set") -def post_form_param_set(items: set = Form(...)): +def post_form_param_set(items: set = Form()): return items @app.post("/form/python-tuple") -def post_form_param_tuple(items: tuple = Form(...)): +def post_form_param_tuple(items: tuple = Form()): return items diff --git a/tests/test_invalid_sequence_param.py b/tests/test_invalid_sequence_param.py index f00dd7b9343c1..475786adbf80d 100644 --- a/tests/test_invalid_sequence_param.py +++ b/tests/test_invalid_sequence_param.py @@ -13,7 +13,7 @@ class Item(BaseModel): title: str @app.get("/items/") - def read_items(q: List[Item] = Query(None)): + def read_items(q: List[Item] = Query(default=None)): pass # pragma: no cover @@ -25,7 +25,7 @@ class Item(BaseModel): title: str @app.get("/items/") - def read_items(q: Tuple[Item, Item] = Query(None)): + def read_items(q: Tuple[Item, Item] = Query(default=None)): pass # pragma: no cover @@ -37,7 +37,7 @@ class Item(BaseModel): title: str @app.get("/items/") - def read_items(q: Dict[str, Item] = Query(None)): + def read_items(q: Dict[str, Item] = Query(default=None)): pass # pragma: no cover @@ -49,5 +49,5 @@ class Item(BaseModel): title: str @app.get("/items/") - def read_items(q: Optional[dict] = Query(None)): + def read_items(q: Optional[dict] = Query(default=None)): pass # pragma: no cover diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index fa82b5ea83585..ed35fd32e43f0 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -67,7 +67,7 @@ class Config: class ModelWithAlias(BaseModel): - foo: str = Field(..., alias="Foo") + foo: str = Field(alias="Foo") class ModelWithDefault(BaseModel): diff --git a/tests/test_modules_same_name_body/app/a.py b/tests/test_modules_same_name_body/app/a.py index 3c86c1865e74f..37723689062cf 100644 --- a/tests/test_modules_same_name_body/app/a.py +++ b/tests/test_modules_same_name_body/app/a.py @@ -4,5 +4,5 @@ @router.post("/compute") -def compute(a: int = Body(...), b: str = Body(...)): +def compute(a: int = Body(), b: str = Body()): return {"a": a, "b": b} diff --git a/tests/test_modules_same_name_body/app/b.py b/tests/test_modules_same_name_body/app/b.py index f7c7fdfc690d1..b62118f84142c 100644 --- a/tests/test_modules_same_name_body/app/b.py +++ b/tests/test_modules_same_name_body/app/b.py @@ -4,5 +4,5 @@ @router.post("/compute/") -def compute(a: int = Body(...), b: str = Body(...)): +def compute(a: int = Body(), b: str = Body()): return {"a": a, "b": b} diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py index 0a15833fa0ee9..3da461af5a532 100644 --- a/tests/test_multi_query_errors.py +++ b/tests/test_multi_query_errors.py @@ -7,7 +7,7 @@ @app.get("/items/") -def read_items(q: List[int] = Query(None)): +def read_items(q: List[int] = Query(default=None)): return {"q": q} diff --git a/tests/test_multipart_installation.py b/tests/test_multipart_installation.py index c8a6fd942fa1a..788d9ef5afd30 100644 --- a/tests/test_multipart_installation.py +++ b/tests/test_multipart_installation.py @@ -12,7 +12,7 @@ def test_incorrect_multipart_installed_form(monkeypatch): app = FastAPI() @app.post("/") - async def root(username: str = Form(...)): + async def root(username: str = Form()): return username # pragma: nocover @@ -22,7 +22,7 @@ def test_incorrect_multipart_installed_file_upload(monkeypatch): app = FastAPI() @app.post("/") - async def root(f: UploadFile = File(...)): + async def root(f: UploadFile = File()): return f # pragma: nocover @@ -32,7 +32,7 @@ def test_incorrect_multipart_installed_file_bytes(monkeypatch): app = FastAPI() @app.post("/") - async def root(f: bytes = File(...)): + async def root(f: bytes = File()): return f # pragma: nocover @@ -42,7 +42,7 @@ def test_incorrect_multipart_installed_multi_form(monkeypatch): app = FastAPI() @app.post("/") - async def root(username: str = Form(...), password: str = Form(...)): + async def root(username: str = Form(), password: str = Form()): return username # pragma: nocover @@ -52,7 +52,7 @@ def test_incorrect_multipart_installed_form_file(monkeypatch): app = FastAPI() @app.post("/") - async def root(username: str = Form(...), f: UploadFile = File(...)): + async def root(username: str = Form(), f: UploadFile = File()): return username # pragma: nocover @@ -62,7 +62,7 @@ def test_no_multipart_installed(monkeypatch): app = FastAPI() @app.post("/") - async def root(username: str = Form(...)): + async def root(username: str = Form()): return username # pragma: nocover @@ -72,7 +72,7 @@ def test_no_multipart_installed_file(monkeypatch): app = FastAPI() @app.post("/") - async def root(f: UploadFile = File(...)): + async def root(f: UploadFile = File()): return f # pragma: nocover @@ -82,7 +82,7 @@ def test_no_multipart_installed_file_bytes(monkeypatch): app = FastAPI() @app.post("/") - async def root(f: bytes = File(...)): + async def root(f: bytes = File()): return f # pragma: nocover @@ -92,7 +92,7 @@ def test_no_multipart_installed_multi_form(monkeypatch): app = FastAPI() @app.post("/") - async def root(username: str = Form(...), password: str = Form(...)): + async def root(username: str = Form(), password: str = Form()): return username # pragma: nocover @@ -102,5 +102,5 @@ def test_no_multipart_installed_form_file(monkeypatch): app = FastAPI() @app.post("/") - async def root(username: str = Form(...), f: UploadFile = File(...)): + async def root(username: str = Form(), f: UploadFile = File()): return username # pragma: nocover diff --git a/tests/test_param_class.py b/tests/test_param_class.py index f5767ec96cab8..1fd40dcd218b9 100644 --- a/tests/test_param_class.py +++ b/tests/test_param_class.py @@ -8,7 +8,7 @@ @app.get("/items/") -def read_items(q: Optional[str] = Param(None)): # type: ignore +def read_items(q: Optional[str] = Param(default=None)): # type: ignore return {"q": q} diff --git a/tests/test_param_include_in_schema.py b/tests/test_param_include_in_schema.py index 26aa638971644..214f039b67d3e 100644 --- a/tests/test_param_include_in_schema.py +++ b/tests/test_param_include_in_schema.py @@ -9,26 +9,26 @@ @app.get("/hidden_cookie") async def hidden_cookie( - hidden_cookie: Optional[str] = Cookie(None, include_in_schema=False) + hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False) ): return {"hidden_cookie": hidden_cookie} @app.get("/hidden_header") async def hidden_header( - hidden_header: Optional[str] = Header(None, include_in_schema=False) + hidden_header: Optional[str] = Header(default=None, include_in_schema=False) ): return {"hidden_header": hidden_header} @app.get("/hidden_path/{hidden_path}") -async def hidden_path(hidden_path: str = Path(..., include_in_schema=False)): +async def hidden_path(hidden_path: str = Path(include_in_schema=False)): return {"hidden_path": hidden_path} @app.get("/hidden_query") async def hidden_query( - hidden_query: Optional[str] = Query(None, include_in_schema=False) + hidden_query: Optional[str] = Query(default=None, include_in_schema=False) ): return {"hidden_query": hidden_query} diff --git a/tests/test_repeated_dependency_schema.py b/tests/test_repeated_dependency_schema.py index 00441694ee18a..ca0305184aaff 100644 --- a/tests/test_repeated_dependency_schema.py +++ b/tests/test_repeated_dependency_schema.py @@ -4,7 +4,7 @@ app = FastAPI() -def get_header(*, someheader: str = Header(...)): +def get_header(*, someheader: str = Header()): return someheader diff --git a/tests/test_request_body_parameters_media_type.py b/tests/test_request_body_parameters_media_type.py index ace6bdef76ee6..e9cf4006d9eff 100644 --- a/tests/test_request_body_parameters_media_type.py +++ b/tests/test_request_body_parameters_media_type.py @@ -21,14 +21,14 @@ class Shop(BaseModel): @app.post("/products") -async def create_product(data: Product = Body(..., media_type=media_type, embed=True)): +async def create_product(data: Product = Body(media_type=media_type, embed=True)): pass # pragma: no cover @app.post("/shops") async def create_shop( - data: Shop = Body(..., media_type=media_type), - included: typing.List[Product] = Body([], media_type=media_type), + data: Shop = Body(media_type=media_type), + included: typing.List[Product] = Body(default=[], media_type=media_type), ): pass # pragma: no cover diff --git a/tests/test_schema_extra_examples.py b/tests/test_schema_extra_examples.py index 444e350a86a16..5047aeaa4b02a 100644 --- a/tests/test_schema_extra_examples.py +++ b/tests/test_schema_extra_examples.py @@ -1,3 +1,5 @@ +from typing import Union + from fastapi import Body, Cookie, FastAPI, Header, Path, Query from fastapi.testclient import TestClient from pydantic import BaseModel @@ -18,14 +20,13 @@ def schema_extra(item: Item): @app.post("/example/") -def example(item: Item = Body(..., example={"data": "Data in Body example"})): +def example(item: Item = Body(example={"data": "Data in Body example"})): return item @app.post("/examples/") def examples( item: Item = Body( - ..., examples={ "example1": { "summary": "example1 summary", @@ -41,7 +42,6 @@ def examples( @app.post("/example_examples/") def example_examples( item: Item = Body( - ..., example={"data": "Overriden example"}, examples={ "example1": {"value": {"data": "examples example_examples 1"}}, @@ -55,7 +55,7 @@ def example_examples( # TODO: enable these tests once/if Form(embed=False) is supported # TODO: In that case, define if File() should support example/examples too # @app.post("/form_example") -# def form_example(firstname: str = Form(..., example="John")): +# def form_example(firstname: str = Form(example="John")): # return firstname @@ -89,7 +89,6 @@ def example_examples( @app.get("/path_example/{item_id}") def path_example( item_id: str = Path( - ..., example="item_1", ), ): @@ -99,7 +98,6 @@ def path_example( @app.get("/path_examples/{item_id}") def path_examples( item_id: str = Path( - ..., examples={ "example1": {"summary": "item ID summary", "value": "item_1"}, "example2": {"value": "item_2"}, @@ -112,7 +110,6 @@ def path_examples( @app.get("/path_example_examples/{item_id}") def path_example_examples( item_id: str = Path( - ..., example="item_overriden", examples={ "example1": {"summary": "item ID summary", "value": "item_1"}, @@ -125,8 +122,8 @@ def path_example_examples( @app.get("/query_example/") def query_example( - data: str = Query( - None, + data: Union[str, None] = Query( + default=None, example="query1", ), ): @@ -135,8 +132,8 @@ def query_example( @app.get("/query_examples/") def query_examples( - data: str = Query( - None, + data: Union[str, None] = Query( + default=None, examples={ "example1": {"summary": "Query example 1", "value": "query1"}, "example2": {"value": "query2"}, @@ -148,8 +145,8 @@ def query_examples( @app.get("/query_example_examples/") def query_example_examples( - data: str = Query( - None, + data: Union[str, None] = Query( + default=None, example="query_overriden", examples={ "example1": {"summary": "Qeury example 1", "value": "query1"}, @@ -162,8 +159,8 @@ def query_example_examples( @app.get("/header_example/") def header_example( - data: str = Header( - None, + data: Union[str, None] = Header( + default=None, example="header1", ), ): @@ -172,8 +169,8 @@ def header_example( @app.get("/header_examples/") def header_examples( - data: str = Header( - None, + data: Union[str, None] = Header( + default=None, examples={ "example1": {"summary": "header example 1", "value": "header1"}, "example2": {"value": "header2"}, @@ -185,8 +182,8 @@ def header_examples( @app.get("/header_example_examples/") def header_example_examples( - data: str = Header( - None, + data: Union[str, None] = Header( + default=None, example="header_overriden", examples={ "example1": {"summary": "Qeury example 1", "value": "header1"}, @@ -199,8 +196,8 @@ def header_example_examples( @app.get("/cookie_example/") def cookie_example( - data: str = Cookie( - None, + data: Union[str, None] = Cookie( + default=None, example="cookie1", ), ): @@ -209,8 +206,8 @@ def cookie_example( @app.get("/cookie_examples/") def cookie_examples( - data: str = Cookie( - None, + data: Union[str, None] = Cookie( + default=None, examples={ "example1": {"summary": "cookie example 1", "value": "cookie1"}, "example2": {"value": "cookie2"}, @@ -222,8 +219,8 @@ def cookie_examples( @app.get("/cookie_example_examples/") def cookie_example_examples( - data: str = Cookie( - None, + data: Union[str, None] = Cookie( + default=None, example="cookie_overriden", examples={ "example1": {"summary": "Qeury example 1", "value": "cookie1"}, diff --git a/tests/test_serialize_response_model.py b/tests/test_serialize_response_model.py index 2956674376a58..3bb46b2e9bcd6 100644 --- a/tests/test_serialize_response_model.py +++ b/tests/test_serialize_response_model.py @@ -8,7 +8,7 @@ class Item(BaseModel): - name: str = Field(..., alias="aliased_name") + name: str = Field(alias="aliased_name") price: Optional[float] = None owner_ids: Optional[List[int]] = None diff --git a/tests/test_starlette_urlconvertors.py b/tests/test_starlette_urlconvertors.py index 2320c7005f2cb..5a980cbf6dad7 100644 --- a/tests/test_starlette_urlconvertors.py +++ b/tests/test_starlette_urlconvertors.py @@ -5,17 +5,17 @@ @app.get("/int/{param:int}") -def int_convertor(param: int = Path(...)): +def int_convertor(param: int = Path()): return {"int": param} @app.get("/float/{param:float}") -def float_convertor(param: float = Path(...)): +def float_convertor(param: float = Path()): return {"float": param} @app.get("/path/{param:path}") -def path_convertor(param: str = Path(...)): +def path_convertor(param: str = Path()): return {"path": param} diff --git a/tests/test_tuples.py b/tests/test_tuples.py index 2085dc3670eed..18ec2d0489912 100644 --- a/tests/test_tuples.py +++ b/tests/test_tuples.py @@ -27,7 +27,7 @@ def post_tuple_of_models(square: Tuple[Coordinate, Coordinate]): @app.post("/tuple-form/") -def hello(values: Tuple[int, int] = Form(...)): +def hello(values: Tuple[int, int] = Form()): return values