-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
Closed
Labels
Description
First check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn't find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google "How to X in FastAPI" and didn't find any information.
- I already read and followed all the tutorial in the docs and didn't find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
- After submitting this, I commit to one of:
- Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
- I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
- Implement a Pull Request for a confirmed bug.
Example
Here's a self-contained, minimal, reproducible, example with my use case:
from typing import Optional
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, EmailStr
app = FastAPI()
class UserIn(BaseModel):
username: str
@property
def email(self):
return f"{self.username}@foo.com"
class UserOut(BaseModel):
username: str
email: str
@app.get("/users/1", response_model=UserOut)
async def get_user():
return UserIn(username="toaster")
client = TestClient(app)
def test_get():
response = client.get("/users/1")
assert response.status_code == 200
assert response.json() == {"email": "toaster@gdc.com"}Description
- Run with pytest
- Watch the test fail
- But I expected it to pass
Failure:
File "testfastapi/env/lib/python3.9/site-packages/fastapi/routing.py", line 209, in app
response_data = await serialize_response(
File "testfastapi/env/lib/python3.9/site-packages/fastapi/routing.py", line 126, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for UserOut
response -> email
field required (type=value_error.missing)
Environment
- OS: [e.g. Linux / Windows / macOS]: macOS
- FastAPI Version [e.g. 0.3.0]: 0.63.0
- Python version: 3.9.1
Additional context
This is probably related to pydantic/pydantic#935 - but I'm wondering if we shouldn't use something like from_orm when creating response object, because nothing guarantees (I believe?) that the returned object will be a BaseModel?
In any case, thanks a lot for your work on both libraries!
smirzaei