diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index ab68314e851c9..69c02052d6098 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -1,6 +1,51 @@ -# Response Model +# Response Model - Return Type -You can declare the model used for the response with the parameter `response_model` in any of the *path operations*: +You can declare the type used for the response by annotating the *path operation function* **return type**. + +You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc. + +=== "Python 3.6 and above" + + ```Python hl_lines="18 23" + {!> ../../../docs_src/response_model/tutorial001_01.py!} + ``` + +=== "Python 3.9 and above" + + ```Python hl_lines="18 23" + {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} + ``` + +FastAPI will use this return type to: + +* **Validate** the returned data. + * If the data is invalid (e.g. you are missing a field), it means that *your* app code is broken, not returning what it should, and it will return a server error instead of returning incorrect data. This way you and your clients can be certain that they will receive the data and the data shape expected. +* Add a **JSON Schema** for the response, in the OpenAPI *path operation*. + * This will be used by the **automatic docs**. + * It will also be used by automatic client code generation tools. + +But most importantly: + +* It will **limit and filter** the output data to what is defined in the return type. + * This is particularly important for **security**, we'll see more of that below. + +## `response_model` Parameter + +There are some cases where you need or want to return some data that is not exactly what the type declares. + +For example, you could want to **return a dictionary** or a database object, but **declare it as a Pydantic model**. This way the Pydantic model would do all the data documentation, validation, etc. for the object that you returned (e.g. a dictionary or database object). + +If you added the return type annotation, tools and editors would complain with a (correct) error telling you that your function is returning a type (e.g. a dict) that is different from what you declared (e.g. a Pydantic model). + +In those cases, you can use the *path operation decorator* parameter `response_model` instead of the return type. + +You can use the `response_model` parameter in any of the *path operations*: * `@app.get()` * `@app.post()` @@ -10,40 +55,39 @@ You can declare the model used for the response with the parameter `response_mod === "Python 3.6 and above" - ```Python hl_lines="17" + ```Python hl_lines="17 22 24-27" {!> ../../../docs_src/response_model/tutorial001.py!} ``` === "Python 3.9 and above" - ```Python hl_lines="17" + ```Python hl_lines="17 22 24-27" {!> ../../../docs_src/response_model/tutorial001_py39.py!} ``` === "Python 3.10 and above" - ```Python hl_lines="15" + ```Python hl_lines="17 22 24-27" {!> ../../../docs_src/response_model/tutorial001_py310.py!} ``` !!! note Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body. -It receives the same type you would declare for a Pydantic model attribute, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`. +`response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`. + +FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration. -FastAPI will use this `response_model` to: +!!! tip + If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`. -* Convert the output data to its type declaration. -* Validate the data. -* Add a JSON Schema for the response, in the OpenAPI *path operation*. -* Will be used by the automatic documentation systems. + That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`. -But most importantly: +### `response_model` Priority -* Will limit the output data to that of the model. We'll see how that's important below. +If you declare both a return type and a `response_model`, the `response_model` will take priority and be used by FastAPI. -!!! note "Technical Details" - The response model is declared in this parameter instead of as a function return type annotation, because the path function may not actually return that response model but rather return a `dict`, database object or some other model, and then use the `response_model` to perform the field limiting and serialization. +This way you can add correct type annotations to your functions even when you are returning a type different than the response model, to be used by the editor and tools like mypy. And still you can have FastAPI do the data validation, documentation, etc. using the `response_model`. ## Return the same input data @@ -71,24 +115,24 @@ And we are using this model to declare our input and the same model to declare o === "Python 3.6 and above" - ```Python hl_lines="17-18" + ```Python hl_lines="18" {!> ../../../docs_src/response_model/tutorial002.py!} ``` === "Python 3.10 and above" - ```Python hl_lines="15-16" + ```Python hl_lines="16" {!> ../../../docs_src/response_model/tutorial002_py310.py!} ``` Now, whenever a browser is creating a user with a password, the API will return the same password in the response. -In this case, it might not be a problem, because the user themself is sending the password. +In this case, it might not be a problem, because it's the same user sending the password. But if we use the same model for another *path operation*, we could be sending our user's passwords to every client. !!! danger - Never store the plain password of a user or send it in a response. + Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing. ## Add an output model @@ -102,7 +146,7 @@ We can instead create an input model with the plaintext password and an output m === "Python 3.10 and above" - ```Python hl_lines="7 9 14" + ```Python hl_lines="9 11 16" {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` @@ -116,7 +160,7 @@ Here, even though our *path operation function* is returning the same input user === "Python 3.10 and above" - ```Python hl_lines="22" + ```Python hl_lines="24" {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` @@ -130,12 +174,66 @@ Here, even though our *path operation function* is returning the same input user === "Python 3.10 and above" - ```Python hl_lines="20" + ```Python hl_lines="22" {!> ../../../docs_src/response_model/tutorial003_py310.py!} ``` So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic). +### `response_model` or Return Type + +In this case, because the two models are different, if we annotated the function return type as `UserOut`, the editor and tools would complain that we are returning an invalid type, as those are different classes. + +That's why in this example we have to declare it in the `response_model` parameter. + +...but continue reading below to see how to overcome that. + +## Return Type and Data Filtering + +Let's continue from the previous example. We wanted to **annotate the function with one type** but return something that includes **more data**. + +We want FastAPI to keep **filtering** the data using the response model. + +In the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type. + +But in most of the cases where we need to do something like this, we want the model just to **filter/remove** some of the data as in this example. + +And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**. + +=== "Python 3.6 and above" + + ```Python hl_lines="9-13 15-16 20" + {!> ../../../docs_src/response_model/tutorial003_01.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="7-10 13-14 18" + {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} + ``` + +With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI. + +How does this work? Let's check that out. 🤓 + +### Type Annotations and Tooling + +First let's see how editors, mypy and other tools would see this. + +`BaseUser` has the base fields. Then `UserIn` inherits from `BaseUser` and adds the `password` field, so, it will include all the fields from both models. + +We annotate the function return type as `BaseUser`, but we are actually returning a `UserIn` instance. + +The editor, mypy, and other tools won't complain about this because, in typing terms, `UserIn` is a subclass of `BaseUser`, which means it's a *valid* type when what is expected is anything that is a `BaseUser`. + +### FastAPI Data Filtering + +Now, for FastAPI, it will see the return type and make sure that what you return includes **only** the fields that are declared in the type. + +FastAPI does several things internally with Pydantic to make sure that those same rules of class inheritance are not used for the returned data filtering, otherwise you could end up returning much more data than what you expected. + +This way, you can get the best of both worlds: type annotations with **tooling support** and **data filtering**. + ## See it in the docs When you see the automatic docs, you can check that the input model and output model will both have their own JSON Schema: diff --git a/docs_src/response_model/tutorial001.py b/docs_src/response_model/tutorial001.py index 0f6e03e5b2e58..fd1c902a52fdb 100644 --- a/docs_src/response_model/tutorial001.py +++ b/docs_src/response_model/tutorial001.py @@ -1,4 +1,4 @@ -from typing import List, Union +from typing import Any, List, Union from fastapi import FastAPI from pydantic import BaseModel @@ -15,5 +15,13 @@ class Item(BaseModel): @app.post("/items/", response_model=Item) -async def create_item(item: Item): +async def create_item(item: Item) -> Any: return item + + +@app.get("/items/", response_model=List[Item]) +async def read_items() -> Any: + return [ + {"name": "Portal Gun", "price": 42.0}, + {"name": "Plumbus", "price": 32.0}, + ] diff --git a/docs_src/response_model/tutorial001_01.py b/docs_src/response_model/tutorial001_01.py new file mode 100644 index 0000000000000..98d30d540f793 --- /dev/null +++ b/docs_src/response_model/tutorial001_01.py @@ -0,0 +1,27 @@ +from typing import List, Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + price: float + tax: Union[float, None] = None + tags: List[str] = [] + + +@app.post("/items/") +async def create_item(item: Item) -> Item: + return item + + +@app.get("/items/") +async def read_items() -> List[Item]: + return [ + Item(name="Portal Gun", price=42.0), + Item(name="Plumbus", price=32.0), + ] diff --git a/docs_src/response_model/tutorial001_01_py310.py b/docs_src/response_model/tutorial001_01_py310.py new file mode 100644 index 0000000000000..7951c10761e6c --- /dev/null +++ b/docs_src/response_model/tutorial001_01_py310.py @@ -0,0 +1,25 @@ +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None = None + price: float + tax: float | None = None + tags: list[str] = [] + + +@app.post("/items/") +async def create_item(item: Item) -> Item: + return item + + +@app.get("/items/") +async def read_items() -> list[Item]: + return [ + Item(name="Portal Gun", price=42.0), + Item(name="Plumbus", price=32.0), + ] diff --git a/docs_src/response_model/tutorial001_01_py39.py b/docs_src/response_model/tutorial001_01_py39.py new file mode 100644 index 0000000000000..16c78aa3fdb2f --- /dev/null +++ b/docs_src/response_model/tutorial001_01_py39.py @@ -0,0 +1,27 @@ +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: Union[str, None] = None + price: float + tax: Union[float, None] = None + tags: list[str] = [] + + +@app.post("/items/") +async def create_item(item: Item) -> Item: + return item + + +@app.get("/items/") +async def read_items() -> list[Item]: + return [ + Item(name="Portal Gun", price=42.0), + Item(name="Plumbus", price=32.0), + ] diff --git a/docs_src/response_model/tutorial001_py310.py b/docs_src/response_model/tutorial001_py310.py index 59efecde41366..f8a2aa9fcae53 100644 --- a/docs_src/response_model/tutorial001_py310.py +++ b/docs_src/response_model/tutorial001_py310.py @@ -1,3 +1,5 @@ +from typing import Any + from fastapi import FastAPI from pydantic import BaseModel @@ -13,5 +15,13 @@ class Item(BaseModel): @app.post("/items/", response_model=Item) -async def create_item(item: Item): +async def create_item(item: Item) -> Any: return item + + +@app.get("/items/", response_model=list[Item]) +async def read_items() -> Any: + return [ + {"name": "Portal Gun", "price": 42.0}, + {"name": "Plumbus", "price": 32.0}, + ] diff --git a/docs_src/response_model/tutorial001_py39.py b/docs_src/response_model/tutorial001_py39.py index cdcca39d2a91d..261e252d00009 100644 --- a/docs_src/response_model/tutorial001_py39.py +++ b/docs_src/response_model/tutorial001_py39.py @@ -1,4 +1,4 @@ -from typing import Union +from typing import Any, Union from fastapi import FastAPI from pydantic import BaseModel @@ -15,5 +15,13 @@ class Item(BaseModel): @app.post("/items/", response_model=Item) -async def create_item(item: Item): +async def create_item(item: Item) -> Any: return item + + +@app.get("/items/", response_model=list[Item]) +async def read_items() -> Any: + return [ + {"name": "Portal Gun", "price": 42.0}, + {"name": "Plumbus", "price": 32.0}, + ] diff --git a/docs_src/response_model/tutorial002.py b/docs_src/response_model/tutorial002.py index c68e8b1385712..a58668f9ef962 100644 --- a/docs_src/response_model/tutorial002.py +++ b/docs_src/response_model/tutorial002.py @@ -14,6 +14,6 @@ class UserIn(BaseModel): # Don't do this in production! -@app.post("/user/", response_model=UserIn) -async def create_user(user: UserIn): +@app.post("/user/") +async def create_user(user: UserIn) -> UserIn: return user diff --git a/docs_src/response_model/tutorial002_py310.py b/docs_src/response_model/tutorial002_py310.py index 29ab9c9d2546c..0a91a5967f816 100644 --- a/docs_src/response_model/tutorial002_py310.py +++ b/docs_src/response_model/tutorial002_py310.py @@ -12,6 +12,6 @@ class UserIn(BaseModel): # Don't do this in production! -@app.post("/user/", response_model=UserIn) -async def create_user(user: UserIn): +@app.post("/user/") +async def create_user(user: UserIn) -> UserIn: return user diff --git a/docs_src/response_model/tutorial003.py b/docs_src/response_model/tutorial003.py index 37e493dcbeb10..c42dbc707710d 100644 --- a/docs_src/response_model/tutorial003.py +++ b/docs_src/response_model/tutorial003.py @@ -1,4 +1,4 @@ -from typing import Union +from typing import Any, Union from fastapi import FastAPI from pydantic import BaseModel, EmailStr @@ -20,5 +20,5 @@ class UserOut(BaseModel): @app.post("/user/", response_model=UserOut) -async def create_user(user: UserIn): +async def create_user(user: UserIn) -> Any: return user diff --git a/docs_src/response_model/tutorial003_01.py b/docs_src/response_model/tutorial003_01.py new file mode 100644 index 0000000000000..52694b5510c70 --- /dev/null +++ b/docs_src/response_model/tutorial003_01.py @@ -0,0 +1,21 @@ +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel, EmailStr + +app = FastAPI() + + +class BaseUser(BaseModel): + username: str + email: EmailStr + full_name: Union[str, None] = None + + +class UserIn(BaseUser): + password: str + + +@app.post("/user/") +async def create_user(user: UserIn) -> BaseUser: + return user diff --git a/docs_src/response_model/tutorial003_01_py310.py b/docs_src/response_model/tutorial003_01_py310.py new file mode 100644 index 0000000000000..6ffddfd0af6a0 --- /dev/null +++ b/docs_src/response_model/tutorial003_01_py310.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI +from pydantic import BaseModel, EmailStr + +app = FastAPI() + + +class BaseUser(BaseModel): + username: str + email: EmailStr + full_name: str | None = None + + +class UserIn(BaseUser): + password: str + + +@app.post("/user/") +async def create_user(user: UserIn) -> BaseUser: + return user diff --git a/docs_src/response_model/tutorial003_py310.py b/docs_src/response_model/tutorial003_py310.py index fc9693e3cd75b..3703bf888a605 100644 --- a/docs_src/response_model/tutorial003_py310.py +++ b/docs_src/response_model/tutorial003_py310.py @@ -1,3 +1,5 @@ +from typing import Any + from fastapi import FastAPI from pydantic import BaseModel, EmailStr @@ -18,5 +20,5 @@ class UserOut(BaseModel): @app.post("/user/", response_model=UserOut) -async def create_user(user: UserIn): +async def create_user(user: UserIn) -> Any: return user diff --git a/fastapi/applications.py b/fastapi/applications.py index 61d4582d27020..36dc2605d53c8 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -274,7 +274,7 @@ def add_api_route( path: str, endpoint: Callable[..., Coroutine[Any, Any, Response]], *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -332,7 +332,7 @@ def api_route( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -435,7 +435,7 @@ def get( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -490,7 +490,7 @@ def put( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -545,7 +545,7 @@ def post( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -600,7 +600,7 @@ def delete( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -655,7 +655,7 @@ def options( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -710,7 +710,7 @@ def head( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -765,7 +765,7 @@ def patch( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -820,7 +820,7 @@ def trace( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 4c817d5d0ba89..32e171f188549 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -253,7 +253,7 @@ def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: name=param.name, kind=param.kind, default=param.default, - annotation=get_typed_annotation(param, globalns), + annotation=get_typed_annotation(param.annotation, globalns), ) for param in signature.parameters.values() ] @@ -261,14 +261,24 @@ def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: return typed_signature -def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: - annotation = param.annotation +def get_typed_annotation(annotation: Any, globalns: Dict[str, Any]) -> Any: if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation +def get_typed_return_annotation(call: Callable[..., Any]) -> Any: + signature = inspect.signature(call) + annotation = signature.return_annotation + + if annotation is inspect.Signature.empty: + return None + + globalns = getattr(call, "__globals__", {}) + return get_typed_annotation(annotation, globalns) + + def get_dependant( *, path: str, diff --git a/fastapi/routing.py b/fastapi/routing.py index 9a7d88efc888a..8c73b954f166c 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -26,6 +26,7 @@ get_body_field, get_dependant, get_parameterless_sub_dependant, + get_typed_return_annotation, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder @@ -323,7 +324,7 @@ def __init__( path: str, endpoint: Callable[..., Any], *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -354,6 +355,8 @@ def __init__( ) -> None: self.path = path self.endpoint = endpoint + if isinstance(response_model, DefaultPlaceholder): + response_model = get_typed_return_annotation(endpoint) self.response_model = response_model self.summary = summary self.response_description = response_description @@ -519,7 +522,7 @@ def add_api_route( path: str, endpoint: Callable[..., Any], *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -600,7 +603,7 @@ def api_route( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -795,7 +798,7 @@ def get( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -851,7 +854,7 @@ def put( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -907,7 +910,7 @@ def post( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -963,7 +966,7 @@ def delete( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1019,7 +1022,7 @@ def options( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1075,7 +1078,7 @@ def head( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1131,7 +1134,7 @@ def patch( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1187,7 +1190,7 @@ def trace( self, path: str, *, - response_model: Any = None, + response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, diff --git a/tests/test_reponse_set_reponse_code_empty.py b/tests/test_reponse_set_reponse_code_empty.py index 094d54a84b60c..50ec753a0076e 100644 --- a/tests/test_reponse_set_reponse_code_empty.py +++ b/tests/test_reponse_set_reponse_code_empty.py @@ -9,6 +9,7 @@ @app.delete( "/{id}", status_code=204, + response_model=None, ) async def delete_deployment( id: int, diff --git a/tests/test_response_model_as_return_annotation.py b/tests/test_response_model_as_return_annotation.py new file mode 100644 index 0000000000000..f2056fecddee2 --- /dev/null +++ b/tests/test_response_model_as_return_annotation.py @@ -0,0 +1,1051 @@ +from typing import List, Union + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import BaseModel, ValidationError + + +class BaseUser(BaseModel): + name: str + + +class User(BaseUser): + surname: str + + +class DBUser(User): + password_hash: str + + +class Item(BaseModel): + name: str + price: float + + +app = FastAPI() + + +@app.get("/no_response_model-no_annotation-return_model") +def no_response_model_no_annotation_return_model(): + return User(name="John", surname="Doe") + + +@app.get("/no_response_model-no_annotation-return_dict") +def no_response_model_no_annotation_return_dict(): + return {"name": "John", "surname": "Doe"} + + +@app.get("/response_model-no_annotation-return_same_model", response_model=User) +def response_model_no_annotation_return_same_model(): + return User(name="John", surname="Doe") + + +@app.get("/response_model-no_annotation-return_exact_dict", response_model=User) +def response_model_no_annotation_return_exact_dict(): + return {"name": "John", "surname": "Doe"} + + +@app.get("/response_model-no_annotation-return_invalid_dict", response_model=User) +def response_model_no_annotation_return_invalid_dict(): + return {"name": "John"} + + +@app.get("/response_model-no_annotation-return_invalid_model", response_model=User) +def response_model_no_annotation_return_invalid_model(): + return Item(name="Foo", price=42.0) + + +@app.get( + "/response_model-no_annotation-return_dict_with_extra_data", response_model=User +) +def response_model_no_annotation_return_dict_with_extra_data(): + return {"name": "John", "surname": "Doe", "password_hash": "secret"} + + +@app.get( + "/response_model-no_annotation-return_submodel_with_extra_data", response_model=User +) +def response_model_no_annotation_return_submodel_with_extra_data(): + return DBUser(name="John", surname="Doe", password_hash="secret") + + +@app.get("/no_response_model-annotation-return_same_model") +def no_response_model_annotation_return_same_model() -> User: + return User(name="John", surname="Doe") + + +@app.get("/no_response_model-annotation-return_exact_dict") +def no_response_model_annotation_return_exact_dict() -> User: + return {"name": "John", "surname": "Doe"} + + +@app.get("/no_response_model-annotation-return_invalid_dict") +def no_response_model_annotation_return_invalid_dict() -> User: + return {"name": "John"} + + +@app.get("/no_response_model-annotation-return_invalid_model") +def no_response_model_annotation_return_invalid_model() -> User: + return Item(name="Foo", price=42.0) + + +@app.get("/no_response_model-annotation-return_dict_with_extra_data") +def no_response_model_annotation_return_dict_with_extra_data() -> User: + return {"name": "John", "surname": "Doe", "password_hash": "secret"} + + +@app.get("/no_response_model-annotation-return_submodel_with_extra_data") +def no_response_model_annotation_return_submodel_with_extra_data() -> User: + return DBUser(name="John", surname="Doe", password_hash="secret") + + +@app.get("/response_model_none-annotation-return_same_model", response_model=None) +def response_model_none_annotation_return_same_model() -> User: + return User(name="John", surname="Doe") + + +@app.get("/response_model_none-annotation-return_exact_dict", response_model=None) +def response_model_none_annotation_return_exact_dict() -> User: + return {"name": "John", "surname": "Doe"} + + +@app.get("/response_model_none-annotation-return_invalid_dict", response_model=None) +def response_model_none_annotation_return_invalid_dict() -> User: + return {"name": "John"} + + +@app.get("/response_model_none-annotation-return_invalid_model", response_model=None) +def response_model_none_annotation_return_invalid_model() -> User: + return Item(name="Foo", price=42.0) + + +@app.get( + "/response_model_none-annotation-return_dict_with_extra_data", response_model=None +) +def response_model_none_annotation_return_dict_with_extra_data() -> User: + return {"name": "John", "surname": "Doe", "password_hash": "secret"} + + +@app.get( + "/response_model_none-annotation-return_submodel_with_extra_data", + response_model=None, +) +def response_model_none_annotation_return_submodel_with_extra_data() -> User: + return DBUser(name="John", surname="Doe", password_hash="secret") + + +@app.get( + "/response_model_model1-annotation_model2-return_same_model", response_model=User +) +def response_model_model1_annotation_model2_return_same_model() -> Item: + return User(name="John", surname="Doe") + + +@app.get( + "/response_model_model1-annotation_model2-return_exact_dict", response_model=User +) +def response_model_model1_annotation_model2_return_exact_dict() -> Item: + return {"name": "John", "surname": "Doe"} + + +@app.get( + "/response_model_model1-annotation_model2-return_invalid_dict", response_model=User +) +def response_model_model1_annotation_model2_return_invalid_dict() -> Item: + return {"name": "John"} + + +@app.get( + "/response_model_model1-annotation_model2-return_invalid_model", response_model=User +) +def response_model_model1_annotation_model2_return_invalid_model() -> Item: + return Item(name="Foo", price=42.0) + + +@app.get( + "/response_model_model1-annotation_model2-return_dict_with_extra_data", + response_model=User, +) +def response_model_model1_annotation_model2_return_dict_with_extra_data() -> Item: + return {"name": "John", "surname": "Doe", "password_hash": "secret"} + + +@app.get( + "/response_model_model1-annotation_model2-return_submodel_with_extra_data", + response_model=User, +) +def response_model_model1_annotation_model2_return_submodel_with_extra_data() -> Item: + return DBUser(name="John", surname="Doe", password_hash="secret") + + +@app.get( + "/response_model_filtering_model-annotation_submodel-return_submodel", + response_model=User, +) +def response_model_filtering_model_annotation_submodel_return_submodel() -> DBUser: + return DBUser(name="John", surname="Doe", password_hash="secret") + + +@app.get("/response_model_list_of_model-no_annotation", response_model=List[User]) +def response_model_list_of_model_no_annotation(): + return [ + DBUser(name="John", surname="Doe", password_hash="secret"), + DBUser(name="Jane", surname="Does", password_hash="secret2"), + ] + + +@app.get("/no_response_model-annotation_list_of_model") +def no_response_model_annotation_list_of_model() -> List[User]: + return [ + DBUser(name="John", surname="Doe", password_hash="secret"), + DBUser(name="Jane", surname="Does", password_hash="secret2"), + ] + + +@app.get("/no_response_model-annotation_forward_ref_list_of_model") +def no_response_model_annotation_forward_ref_list_of_model() -> "List[User]": + return [ + DBUser(name="John", surname="Doe", password_hash="secret"), + DBUser(name="Jane", surname="Does", password_hash="secret2"), + ] + + +@app.get( + "/response_model_union-no_annotation-return_model1", + response_model=Union[User, Item], +) +def response_model_union_no_annotation_return_model1(): + return DBUser(name="John", surname="Doe", password_hash="secret") + + +@app.get( + "/response_model_union-no_annotation-return_model2", + response_model=Union[User, Item], +) +def response_model_union_no_annotation_return_model2(): + return Item(name="Foo", price=42.0) + + +@app.get("/no_response_model-annotation_union-return_model1") +def no_response_model_annotation_union_return_model1() -> Union[User, Item]: + return DBUser(name="John", surname="Doe", password_hash="secret") + + +@app.get("/no_response_model-annotation_union-return_model2") +def no_response_model_annotation_union_return_model2() -> Union[User, Item]: + return Item(name="Foo", price=42.0) + + +openapi_schema = { + "openapi": "3.0.2", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/no_response_model-no_annotation-return_model": { + "get": { + "summary": "No Response Model No Annotation Return Model", + "operationId": "no_response_model_no_annotation_return_model_no_response_model_no_annotation_return_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/no_response_model-no_annotation-return_dict": { + "get": { + "summary": "No Response Model No Annotation Return Dict", + "operationId": "no_response_model_no_annotation_return_dict_no_response_model_no_annotation_return_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/response_model-no_annotation-return_same_model": { + "get": { + "summary": "Response Model No Annotation Return Same Model", + "operationId": "response_model_no_annotation_return_same_model_response_model_no_annotation_return_same_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model-no_annotation-return_exact_dict": { + "get": { + "summary": "Response Model No Annotation Return Exact Dict", + "operationId": "response_model_no_annotation_return_exact_dict_response_model_no_annotation_return_exact_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model-no_annotation-return_invalid_dict": { + "get": { + "summary": "Response Model No Annotation Return Invalid Dict", + "operationId": "response_model_no_annotation_return_invalid_dict_response_model_no_annotation_return_invalid_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model-no_annotation-return_invalid_model": { + "get": { + "summary": "Response Model No Annotation Return Invalid Model", + "operationId": "response_model_no_annotation_return_invalid_model_response_model_no_annotation_return_invalid_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model-no_annotation-return_dict_with_extra_data": { + "get": { + "summary": "Response Model No Annotation Return Dict With Extra Data", + "operationId": "response_model_no_annotation_return_dict_with_extra_data_response_model_no_annotation_return_dict_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model-no_annotation-return_submodel_with_extra_data": { + "get": { + "summary": "Response Model No Annotation Return Submodel With Extra Data", + "operationId": "response_model_no_annotation_return_submodel_with_extra_data_response_model_no_annotation_return_submodel_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/no_response_model-annotation-return_same_model": { + "get": { + "summary": "No Response Model Annotation Return Same Model", + "operationId": "no_response_model_annotation_return_same_model_no_response_model_annotation_return_same_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/no_response_model-annotation-return_exact_dict": { + "get": { + "summary": "No Response Model Annotation Return Exact Dict", + "operationId": "no_response_model_annotation_return_exact_dict_no_response_model_annotation_return_exact_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/no_response_model-annotation-return_invalid_dict": { + "get": { + "summary": "No Response Model Annotation Return Invalid Dict", + "operationId": "no_response_model_annotation_return_invalid_dict_no_response_model_annotation_return_invalid_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/no_response_model-annotation-return_invalid_model": { + "get": { + "summary": "No Response Model Annotation Return Invalid Model", + "operationId": "no_response_model_annotation_return_invalid_model_no_response_model_annotation_return_invalid_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/no_response_model-annotation-return_dict_with_extra_data": { + "get": { + "summary": "No Response Model Annotation Return Dict With Extra Data", + "operationId": "no_response_model_annotation_return_dict_with_extra_data_no_response_model_annotation_return_dict_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/no_response_model-annotation-return_submodel_with_extra_data": { + "get": { + "summary": "No Response Model Annotation Return Submodel With Extra Data", + "operationId": "no_response_model_annotation_return_submodel_with_extra_data_no_response_model_annotation_return_submodel_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_none-annotation-return_same_model": { + "get": { + "summary": "Response Model None Annotation Return Same Model", + "operationId": "response_model_none_annotation_return_same_model_response_model_none_annotation_return_same_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/response_model_none-annotation-return_exact_dict": { + "get": { + "summary": "Response Model None Annotation Return Exact Dict", + "operationId": "response_model_none_annotation_return_exact_dict_response_model_none_annotation_return_exact_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/response_model_none-annotation-return_invalid_dict": { + "get": { + "summary": "Response Model None Annotation Return Invalid Dict", + "operationId": "response_model_none_annotation_return_invalid_dict_response_model_none_annotation_return_invalid_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/response_model_none-annotation-return_invalid_model": { + "get": { + "summary": "Response Model None Annotation Return Invalid Model", + "operationId": "response_model_none_annotation_return_invalid_model_response_model_none_annotation_return_invalid_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/response_model_none-annotation-return_dict_with_extra_data": { + "get": { + "summary": "Response Model None Annotation Return Dict With Extra Data", + "operationId": "response_model_none_annotation_return_dict_with_extra_data_response_model_none_annotation_return_dict_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/response_model_none-annotation-return_submodel_with_extra_data": { + "get": { + "summary": "Response Model None Annotation Return Submodel With Extra Data", + "operationId": "response_model_none_annotation_return_submodel_with_extra_data_response_model_none_annotation_return_submodel_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + } + }, + } + }, + "/response_model_model1-annotation_model2-return_same_model": { + "get": { + "summary": "Response Model Model1 Annotation Model2 Return Same Model", + "operationId": "response_model_model1_annotation_model2_return_same_model_response_model_model1_annotation_model2_return_same_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_model1-annotation_model2-return_exact_dict": { + "get": { + "summary": "Response Model Model1 Annotation Model2 Return Exact Dict", + "operationId": "response_model_model1_annotation_model2_return_exact_dict_response_model_model1_annotation_model2_return_exact_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_model1-annotation_model2-return_invalid_dict": { + "get": { + "summary": "Response Model Model1 Annotation Model2 Return Invalid Dict", + "operationId": "response_model_model1_annotation_model2_return_invalid_dict_response_model_model1_annotation_model2_return_invalid_dict_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_model1-annotation_model2-return_invalid_model": { + "get": { + "summary": "Response Model Model1 Annotation Model2 Return Invalid Model", + "operationId": "response_model_model1_annotation_model2_return_invalid_model_response_model_model1_annotation_model2_return_invalid_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_model1-annotation_model2-return_dict_with_extra_data": { + "get": { + "summary": "Response Model Model1 Annotation Model2 Return Dict With Extra Data", + "operationId": "response_model_model1_annotation_model2_return_dict_with_extra_data_response_model_model1_annotation_model2_return_dict_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_model1-annotation_model2-return_submodel_with_extra_data": { + "get": { + "summary": "Response Model Model1 Annotation Model2 Return Submodel With Extra Data", + "operationId": "response_model_model1_annotation_model2_return_submodel_with_extra_data_response_model_model1_annotation_model2_return_submodel_with_extra_data_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_filtering_model-annotation_submodel-return_submodel": { + "get": { + "summary": "Response Model Filtering Model Annotation Submodel Return Submodel", + "operationId": "response_model_filtering_model_annotation_submodel_return_submodel_response_model_filtering_model_annotation_submodel_return_submodel_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/User"} + } + }, + } + }, + } + }, + "/response_model_list_of_model-no_annotation": { + "get": { + "summary": "Response Model List Of Model No Annotation", + "operationId": "response_model_list_of_model_no_annotation_response_model_list_of_model_no_annotation_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Response Model List Of Model No Annotation Response Model List Of Model No Annotation Get", + "type": "array", + "items": {"$ref": "#/components/schemas/User"}, + } + } + }, + } + }, + } + }, + "/no_response_model-annotation_list_of_model": { + "get": { + "summary": "No Response Model Annotation List Of Model", + "operationId": "no_response_model_annotation_list_of_model_no_response_model_annotation_list_of_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response No Response Model Annotation List Of Model No Response Model Annotation List Of Model Get", + "type": "array", + "items": {"$ref": "#/components/schemas/User"}, + } + } + }, + } + }, + } + }, + "/no_response_model-annotation_forward_ref_list_of_model": { + "get": { + "summary": "No Response Model Annotation Forward Ref List Of Model", + "operationId": "no_response_model_annotation_forward_ref_list_of_model_no_response_model_annotation_forward_ref_list_of_model_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response No Response Model Annotation Forward Ref List Of Model No Response Model Annotation Forward Ref List Of Model Get", + "type": "array", + "items": {"$ref": "#/components/schemas/User"}, + } + } + }, + } + }, + } + }, + "/response_model_union-no_annotation-return_model1": { + "get": { + "summary": "Response Model Union No Annotation Return Model1", + "operationId": "response_model_union_no_annotation_return_model1_response_model_union_no_annotation_return_model1_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Response Model Union No Annotation Return Model1 Response Model Union No Annotation Return Model1 Get", + "anyOf": [ + {"$ref": "#/components/schemas/User"}, + {"$ref": "#/components/schemas/Item"}, + ], + } + } + }, + } + }, + } + }, + "/response_model_union-no_annotation-return_model2": { + "get": { + "summary": "Response Model Union No Annotation Return Model2", + "operationId": "response_model_union_no_annotation_return_model2_response_model_union_no_annotation_return_model2_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Response Model Union No Annotation Return Model2 Response Model Union No Annotation Return Model2 Get", + "anyOf": [ + {"$ref": "#/components/schemas/User"}, + {"$ref": "#/components/schemas/Item"}, + ], + } + } + }, + } + }, + } + }, + "/no_response_model-annotation_union-return_model1": { + "get": { + "summary": "No Response Model Annotation Union Return Model1", + "operationId": "no_response_model_annotation_union_return_model1_no_response_model_annotation_union_return_model1_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response No Response Model Annotation Union Return Model1 No Response Model Annotation Union Return Model1 Get", + "anyOf": [ + {"$ref": "#/components/schemas/User"}, + {"$ref": "#/components/schemas/Item"}, + ], + } + } + }, + } + }, + } + }, + "/no_response_model-annotation_union-return_model2": { + "get": { + "summary": "No Response Model Annotation Union Return Model2", + "operationId": "no_response_model_annotation_union_return_model2_no_response_model_annotation_union_return_model2_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response No Response Model Annotation Union Return Model2 No Response Model Annotation Union Return Model2 Get", + "anyOf": [ + {"$ref": "#/components/schemas/User"}, + {"$ref": "#/components/schemas/Item"}, + ], + } + } + }, + } + }, + } + }, + }, + "components": { + "schemas": { + "Item": { + "title": "Item", + "required": ["name", "price"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "price": {"title": "Price", "type": "number"}, + }, + }, + "User": { + "title": "User", + "required": ["name", "surname"], + "type": "object", + "properties": { + "name": {"title": "Name", "type": "string"}, + "surname": {"title": "Surname", "type": "string"}, + }, + }, + } + }, +} + + +client = TestClient(app) + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == openapi_schema + + +def test_no_response_model_no_annotation_return_model(): + response = client.get("/no_response_model-no_annotation-return_model") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_no_response_model_no_annotation_return_dict(): + response = client.get("/no_response_model-no_annotation-return_dict") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_no_annotation_return_same_model(): + response = client.get("/response_model-no_annotation-return_same_model") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_no_annotation_return_exact_dict(): + response = client.get("/response_model-no_annotation-return_exact_dict") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_no_annotation_return_invalid_dict(): + with pytest.raises(ValidationError): + client.get("/response_model-no_annotation-return_invalid_dict") + + +def test_response_model_no_annotation_return_invalid_model(): + with pytest.raises(ValidationError): + client.get("/response_model-no_annotation-return_invalid_model") + + +def test_response_model_no_annotation_return_dict_with_extra_data(): + response = client.get("/response_model-no_annotation-return_dict_with_extra_data") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_no_annotation_return_submodel_with_extra_data(): + response = client.get( + "/response_model-no_annotation-return_submodel_with_extra_data" + ) + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_no_response_model_annotation_return_same_model(): + response = client.get("/no_response_model-annotation-return_same_model") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_no_response_model_annotation_return_exact_dict(): + response = client.get("/no_response_model-annotation-return_exact_dict") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_no_response_model_annotation_return_invalid_dict(): + with pytest.raises(ValidationError): + client.get("/no_response_model-annotation-return_invalid_dict") + + +def test_no_response_model_annotation_return_invalid_model(): + with pytest.raises(ValidationError): + client.get("/no_response_model-annotation-return_invalid_model") + + +def test_no_response_model_annotation_return_dict_with_extra_data(): + response = client.get("/no_response_model-annotation-return_dict_with_extra_data") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_no_response_model_annotation_return_submodel_with_extra_data(): + response = client.get( + "/no_response_model-annotation-return_submodel_with_extra_data" + ) + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_none_annotation_return_same_model(): + response = client.get("/response_model_none-annotation-return_same_model") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_none_annotation_return_exact_dict(): + response = client.get("/response_model_none-annotation-return_exact_dict") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_none_annotation_return_invalid_dict(): + response = client.get("/response_model_none-annotation-return_invalid_dict") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John"} + + +def test_response_model_none_annotation_return_invalid_model(): + response = client.get("/response_model_none-annotation-return_invalid_model") + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "price": 42.0} + + +def test_response_model_none_annotation_return_dict_with_extra_data(): + response = client.get("/response_model_none-annotation-return_dict_with_extra_data") + assert response.status_code == 200, response.text + assert response.json() == { + "name": "John", + "surname": "Doe", + "password_hash": "secret", + } + + +def test_response_model_none_annotation_return_submodel_with_extra_data(): + response = client.get( + "/response_model_none-annotation-return_submodel_with_extra_data" + ) + assert response.status_code == 200, response.text + assert response.json() == { + "name": "John", + "surname": "Doe", + "password_hash": "secret", + } + + +def test_response_model_model1_annotation_model2_return_same_model(): + response = client.get("/response_model_model1-annotation_model2-return_same_model") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_model1_annotation_model2_return_exact_dict(): + response = client.get("/response_model_model1-annotation_model2-return_exact_dict") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_model1_annotation_model2_return_invalid_dict(): + with pytest.raises(ValidationError): + client.get("/response_model_model1-annotation_model2-return_invalid_dict") + + +def test_response_model_model1_annotation_model2_return_invalid_model(): + with pytest.raises(ValidationError): + client.get("/response_model_model1-annotation_model2-return_invalid_model") + + +def test_response_model_model1_annotation_model2_return_dict_with_extra_data(): + response = client.get( + "/response_model_model1-annotation_model2-return_dict_with_extra_data" + ) + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_model1_annotation_model2_return_submodel_with_extra_data(): + response = client.get( + "/response_model_model1-annotation_model2-return_submodel_with_extra_data" + ) + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_filtering_model_annotation_submodel_return_submodel(): + response = client.get( + "/response_model_filtering_model-annotation_submodel-return_submodel" + ) + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_list_of_model_no_annotation(): + response = client.get("/response_model_list_of_model-no_annotation") + assert response.status_code == 200, response.text + assert response.json() == [ + {"name": "John", "surname": "Doe"}, + {"name": "Jane", "surname": "Does"}, + ] + + +def test_no_response_model_annotation_list_of_model(): + response = client.get("/no_response_model-annotation_list_of_model") + assert response.status_code == 200, response.text + assert response.json() == [ + {"name": "John", "surname": "Doe"}, + {"name": "Jane", "surname": "Does"}, + ] + + +def test_no_response_model_annotation_forward_ref_list_of_model(): + response = client.get("/no_response_model-annotation_forward_ref_list_of_model") + assert response.status_code == 200, response.text + assert response.json() == [ + {"name": "John", "surname": "Doe"}, + {"name": "Jane", "surname": "Does"}, + ] + + +def test_response_model_union_no_annotation_return_model1(): + response = client.get("/response_model_union-no_annotation-return_model1") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_response_model_union_no_annotation_return_model2(): + response = client.get("/response_model_union-no_annotation-return_model2") + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "price": 42.0} + + +def test_no_response_model_annotation_union_return_model1(): + response = client.get("/no_response_model-annotation_union-return_model1") + assert response.status_code == 200, response.text + assert response.json() == {"name": "John", "surname": "Doe"} + + +def test_no_response_model_annotation_union_return_model2(): + response = client.get("/no_response_model-annotation_union-return_model2") + assert response.status_code == 200, response.text + assert response.json() == {"name": "Foo", "price": 42.0}