I want to pass 2 parameters into the handler, to validate it and to proceed work. There are two parameters: id
of string type and the date
of the DateTime in ISO8601 format. FastAPI always returns 400 error instead of at least return simply parameters back in json.
def convert_datetime_to_iso_8601_with_z_suffix(dt: datetime) -> str:
return dt.strftime('%Y-%m-%dT%H:%M:%S.000Z')
class DeleteInModel(BaseModel):
id: int
date: datetime
class Config:
json_encoders = {
datetime: convert_datetime_to_iso_8601_with_z_suffix
}
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content=jsonable_encoder({'code': 400, 'message': 'Validation Failed'})
)
@app.exception_handler(404)
async def existance_exception_handler(request: Request, exc: RequestNotFoundException):
return JSONResponse(
status_code=status.HTTP_404_NOT_FOUND,
content=jsonable_encoder({'code': 404, 'message': 'Item not found'})
)
@app.delete('/delete/{id}', status_code=status.HTTP_200_OK)
async def delete_import(date: DeleteInModel, id: str = Path()):
return {'id': id, 'date': date}
Example of the request string:
localhost:8000/delete/элемент_1_5?date=2022-05-28T21:12:01.516Z
FastApi allows using classes as a basis for query parameters: classes-as-dependencies
In this case, you just need to change the parameter in def delete_import
to:
date: DeleteInModel = Depends(DeleteInModel)
,
or more simply
(see shortcut
)
date: DeleteInModel = Depends()
so it expects '?date='
in the url, otherwise it expects a json body matching the DeleteInModel as part of the request.