I am new in fastapi and please help me!
I got an validation error when I change the default API response comes when I use response_model in fastAPI.
The default API response is simple json like object from response_model.
user.py
JavaScript
x
25
25
1
from fastapi import FastAPI, Response, status, HTTPException, Depends
2
from sqlalchemy.orm.session import Session
3
import models
4
import schemas
5
from database import get_db
6
7
app = FastAPI()
8
@app.post('/', response_model=schemas.UserOut)
9
def UserCreate(users:schemas.UserBase, db:Session = Depends(get_db)):
10
# print(db.query(models.User).filter(models.User.username == users.username).first().username)
11
if db.query(models.User).filter(models.User.email == users.email).first() != None:
12
if users.email == db.query(models.User).filter(models.User.email == users.email).first().email:
13
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="email already exist")
14
15
16
hashed_password = hash(users.password)
17
users.password =hashed_password
18
new_user = models.User(**users.dict())
19
20
db.add(new_user)
21
db.commit()
22
db.refresh(new_user)
23
# return new_user #if i uncomment this code then it will give default response which i don't want
24
return {"status":True,"data":new_user, "message":"User Created Successfully"}
25
schemas.py
JavaScript
1
30
30
1
from pydantic import BaseModel, validator, ValidationError
2
from datetime import datetime
3
4
from typing import Optional, Text
5
6
from pydantic.networks import EmailStr
7
from pydantic.types import constr, conint
8
9
class UserBase(BaseModel):
10
name : str
11
email : EmailStr
12
country: str
13
city: str
14
state : str
15
address: str
16
phone: constr(min_length=10, max_length=10)
17
password: str
18
19
class UserOut(BaseModel):
20
name : str
21
email : EmailStr
22
country: str
23
city: str
24
state : str
25
address: str
26
phone: str
27
28
class Config:
29
orm_mode = True
30
Now, when I run this code it gives me errors like below mentioned.
JavaScript
1
44
44
1
ERROR: Exception in ASGI application
2
Traceback (most recent call last):
3
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
4
result = await app(self.scope, self.receive, self.send)
5
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
6
return await self.app(scope, receive, send)
7
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/applications.py", line 208, in __call__
8
await super().__call__(scope, receive, send)
9
File "/home/amit/.local/lib/python3.6/site-packages/starlette/applications.py", line 112, in __call__
10
await self.middleware_stack(scope, receive, send)
11
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 181, in __call__
12
raise exc
13
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 159, in __call__
14
await self.app(scope, receive, _send)
15
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 82, in __call__
16
raise exc
17
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 71, in __call__
18
await self.app(scope, receive, sender)
19
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 656, in __call__
20
await route.handle(scope, receive, send)
21
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 259, in handle
22
await self.app(scope, receive, send)
23
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 61, in app
24
response = await func(request)
25
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 243, in app
26
is_coroutine=is_coroutine,
27
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 137, in serialize_response
28
raise ValidationError(errors, field.type_)
29
pydantic.error_wrappers.ValidationError: 7 validation errors for UserOut
30
response -> name
31
field required (type=value_error.missing)
32
response -> email
33
field required (type=value_error.missing)
34
response -> country
35
field required (type=value_error.missing)
36
response -> city
37
field required (type=value_error.missing)
38
response -> state
39
field required (type=value_error.missing)
40
response -> address
41
field required (type=value_error.missing)
42
response -> phone
43
field required (type=value_error.missing)
44
Below is the output i want:-
JavaScript
1
14
14
1
{
2
"status": true,
3
"data": {
4
"name": "raj",
5
"email": "rajshah123@gmail.com",
6
"country": "India",
7
"city": "surat",
8
"state": "gujarat",
9
"address": "str5654",
10
"phone": "6666888899"
11
},
12
"message": "User Created Successfully"
13
}
14
Thank you so much.
Advertisement
Answer
The object you are returning doesn’t match your response_model. You have two options:
The last line should be
return new_user
instead ofreturn {"status":True,"data":new_user, "message":"User Created Successfully"}
You response_model should be something like:
JavaScript161class UserOutSchema(BaseModel):
2user: UserOut
3status: str
4message: str
5
6