-2

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
aalexren
  • 133
  • 1
  • 11
  • You have `{id}` as a path parameter, but it doesn't appear you are using one in your request. So fastapi can't find it, and returns 404 – crunker99 Sep 14 '22 at 21:21
  • @crunker99 I slightly updated the code. The problem is 400 Validation Error also – aalexren Sep 14 '22 at 21:35
  • 1
    I see. The issue is the endpoint expects DeleteInModel as the body in the request, but you have it as a query parameter. There is a fix for that though: `date: DeleteInModel = Depends()` - see this question https://stackoverflow.com/questions/62468402/query-parameters-from-pydantic-model – crunker99 Sep 14 '22 at 21:50
  • @crunker99 Thanks a lot! It works! Could you make an answer? P.S. I have absolutely no idea how should I figure it out by myself... :( – aalexren Sep 14 '22 at 22:07

1 Answers1

1

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.

crunker99
  • 371
  • 2
  • 7