-
First Check
Commit to Help
Example Codeimport pytest
from fastapi import FastAPI
from starlette.testclient import TestClient
@pytest.fixture(name="client")
def get_client():
app = FastAPI()
from pydantic import BaseModel, computed_field
class Rectangle(BaseModel):
width: int
length: int
@computed_field
@property
def area(self) -> int:
return self.width * self.length
# A usual endpoint, works as expected.
@app.get("/normal")
def normal() -> Rectangle:
return Rectangle(width=3, length=4)
# An endpoint with response model specified.
@app.get("/response_model", response_model=Rectangle)
def response_model() -> Rectangle:
return Rectangle(width=3, length=4)
# An endpoint with responses specified.
@app.get("/responses", responses={200: {"model": Rectangle}})
def responses() -> Rectangle:
return Rectangle(width=3, length=4)
client = TestClient(app)
return client
def test_get(client: TestClient):
response = client.get("/openapi.json")
data = response.json()
# print(data) # Uncomment this to see the full openapi.json
assert data["paths"]["/normal"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/Rectangle-Output"
# succeeds
assert data["paths"]["/response_model"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/Rectangle-Output"
# succeeds
assert data["paths"]["/responses"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/Rectangle-Output"
# failsDescriptionWhen adding the For example, in the code above a Rectangle has a width and length, and a computed field area. The input model therefore only contains width and length, the output model also contains area. The first end point returns a Is this expected behaviour? Or am I supposed to pass the model in another way? You can run the example code using pytest. It is based on the code from this related question. (This issue may also be related this solved issue.) Operating SystemLinux Operating System DetailsNo response FastAPI Version0.104.1 Pydantic Version2.4.2 Python Version3.11.5 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
I think I was able to fix this problem, at least for me. I changed line 517 in routing.py from: response_field = create_response_field(name=response_name, type_=model)to: response_field = create_response_field(name=response_name, type_=model, mode="serialization")I don't know what other implications this has, but it seems to work for me. I was helped by this suggestion in issue #9856. |
Beta Was this translation helpful? Give feedback.
-
|
A temporary workaround for this issue: #10697 (comment) |
Beta Was this translation helpful? Give feedback.
Stumbled across this too a while ago and finally had the time to prepare a small PR for that: #10895