I'm getting this error while trying to accept a pedantic model. After debugging for quite some time I believe the problem is with accepting CodeCreate
Pydantic model
class BaseCode(BaseModel):
index: Optional[int] = Field(None)
email: EmailStr
gen_time: datetime
expire_time: datetime
class CodeCreate(BaseCode):
code: int
used_time: Optional[datetime] = Field(None)
class Config:
orm_mode = True
class Message(BaseModel):
message: str
Handler
@app.post('/verify-code', response_model=schemas.Message, responses={404: {"model": schemas.Message}, 406: {"model": schemas.Message}})
async def verify_code(code: schemas.CodeCreate, response: Response, device_name: str = Body(..., embed=True), db=Depends(get_db)):
result = crud.verify_and_insert_code(db=db, code=code)
if result == 'matched':
response.status_code = status.HTTP_202_ACCEPTED
return crud.start_new_session(db=db, session=schemas.Session(session_id='1234', start_time=datetime.now(), email=code.email, device_name=device_name))
elif result == 'not-matched':
response.status_code = status.HTTP_200_OK
elif result == 'expire':
response.status_code = status.HTTP_406_NOT_ACCEPTABLE
elif result == 'invalid':
response.status_code = status.HTTP_404_NOT_FOUND
return schemas.Message(message="Item not found")
CodePudding user response:
According to MDN
here,
a 422 Unprocessable Entity means that the information of the request could not be processed.
In this case, the most likely problem is that the data of the POST request that is sent does not match with the Pydantic model.
Make sure the data that is sent is in the correct format.
CodePudding user response:
The error clearly has to do with the data (or type of data) the client sends in the POST request. The client (and specifically the "payload") should look like something like this:
import requests
from datetime import datetime
url = 'http://127.0.0.1:8000/verify-code'
payload = {"code": {"code": 1, "email": "[email protected]", "gen_time": datetime.isoformat(datetime.now()), "expire_time": datetime.isoformat(datetime.now())}, "device_name": "my device's name"}
resp = requests.post(url=url, json=payload)
print(resp.json())
