简体   繁体   中英

Why am I getting {"detail":[{"loc":["path","id"],"msg":"field required","type":"value_error.missing"}]} if I made query with params?

This is the endpoint that is not working:

@router.get(
    "/{question_id}",
    tags=["questions"],
    status_code=status.HTTP_200_OK,
    response_model=Question,
    dependencies=[Depends(get_db)],
)
def get_question(id: int = Path(..., gt=0)):
    return get_question_service(id)

This is what the server shows when I run the query from the interactive FastAPI docs:

INFO:     127.0.0.1:45806 - "GET /api/v1/questions/%7Bquestion_id%7D HTTP/1.1" 422 Unprocessable 

I don't know why it is sending {question_id} here instead of the number.

Also when I run a query from curl, this is what the server shows:

INFO:     127.0.0.1:59104 - "GET /api/v1/questions/21 HTTP/1.1" 422 Unprocessable Entity

It makes no sense since I'm sending the only required param: (question_id)

The other endpoint is working fine:

@router.get(
    "/",
    tags=["questions"],
    status_code=status.HTTP_200_OK,
    response_model=List[Question],
    dependencies=[Depends(get_db)],
)
def get_questions():
    return get_questions_service()

There is a mismatch between the path parameter in the path string and the function argument. Rename the function argument to question_id

@router.get(
    "/{question_id}",
    tags=["questions"],
    status_code=status.HTTP_200_OK,
    response_model=Question,
    dependencies=[Depends(get_db)],
)
def get_question(question_id: int = Path(..., gt=0)):
    return get_question_service(question_id)

or the path parameter to id :

@router.get(
    "/{id}",
    tags=["questions"],
    status_code=status.HTTP_200_OK,
    response_model=Question,
    dependencies=[Depends(get_db)],
)
def get_question(id: int = Path(..., gt=0)):
    return get_question_service(id)

Btw, ... in Path can be omitted. id: int = Path(gt=0) is equivalent to id: int = Path(gt=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM