[英]I want to change api response json in fastapi | pydantic
I am new in fastapi and please help me!我是 fastapi 的新手,请帮助我!
I got an validation error when I change the default API response comes when I use response_model in fastAPI.当我在 fastAPI 中使用 response_model 时更改默认 API 响应时出现验证错误。
The default API response is simple json like object from response_model.默认的 API 响应是简单的 json,例如来自 response_model 的 object。
user.py用户.py
from fastapi import FastAPI, Response, status, HTTPException, Depends
from sqlalchemy.orm.session import Session
import models
import schemas
from database import get_db
app = FastAPI()
@app.post('/', response_model=schemas.UserOut)
def UserCreate(users:schemas.UserBase, db:Session = Depends(get_db)):
# print(db.query(models.User).filter(models.User.username == users.username).first().username)
if db.query(models.User).filter(models.User.email == users.email).first() != None:
if users.email == db.query(models.User).filter(models.User.email == users.email).first().email:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="email already exist")
hashed_password = hash(users.password)
users.password =hashed_password
new_user = models.User(**users.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
# return new_user #if i uncomment this code then it will give default response which i don't want
return {"status":True,"data":new_user, "message":"User Created Successfully"}
schemas.py架构.py
from pydantic import BaseModel, validator, ValidationError
from datetime import datetime
from typing import Optional, Text
from pydantic.networks import EmailStr
from pydantic.types import constr, conint
class UserBase(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: constr(min_length=10, max_length=10)
password: str
class UserOut(BaseModel):
name : str
email : EmailStr
country: str
city: str
state : str
address: str
phone: str
class Config:
orm_mode = True
Now, when I run this code it gives me errors like below mentioned.现在,当我运行此代码时,它会出现如下所述的错误。
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/amit/.local/lib/python3.6/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc
File "/home/amit/.local/lib/python3.6/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 259, in handle
await self.app(scope, receive, send)
File "/home/amit/.local/lib/python3.6/site-packages/starlette/routing.py", line 61, in app
response = await func(request)
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 243, in app
is_coroutine=is_coroutine,
File "/home/amit/.local/lib/python3.6/site-packages/fastapi/routing.py", line 137, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 7 validation errors for UserOut
response -> name
field required (type=value_error.missing)
response -> email
field required (type=value_error.missing)
response -> country
field required (type=value_error.missing)
response -> city
field required (type=value_error.missing)
response -> state
field required (type=value_error.missing)
response -> address
field required (type=value_error.missing)
response -> phone
field required (type=value_error.missing)
Below is the output i want:-下面是我想要的 output:-
{
"status": true,
"data": {
"name": "raj",
"email": "rajshah123@gmail.com",
"country": "India",
"city": "surat",
"state": "gujarat",
"address": "str5654",
"phone": "6666888899"
},
"message": "User Created Successfully"
}
Thank you so much.太感谢了。
The json you return must match the model.您返回的 json 必须与 model 匹配。 Which it does not in your case.
在你的情况下它不是。 You model would have to look like
你 model 必须看起来像
class YourModel(BaseModel):
status : bool
data : UserOut
message: str
The object you are returning doesn't match your response_model.您返回的 object 与您的 response_model 不匹配。
The last line should be return_new_user
instead of return {"status":True,"data":new_user, "message":"User Created Successfully"}
最后一行应该是
return_new_user
而不是return {"status":True,"data":new_user, "message":"User Created Successfully"}
You response_model should be something like:你的 response_model 应该是这样的:
class UserOutSchema(BaseModel): user: UserOut status: str message: str
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.