fastapi / full-stack-fastapi-template

Full stack, modern web application template. Using FastAPI, React, SQLModel, PostgreSQL, Docker, GitHub Actions, automatic HTTPS and more.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[BUG] The GET path /user/{user_id} is being confused by FastAPI with the /user/me endpoint.

guilhermeyoshida opened this issue · comments

commented

Note the endpoints below.

@router.get("/user/{user_id}")
def get_user(
        user_id: int,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    if not current_user:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )
    try:
        user = CRUDUser.read_user(db, current_user, user_id)
    except ValueError as e:
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=str(e))
    return user


@router.get("/user/me")
def read_me(current_user: User = Depends(get_current_user)):
    if not current_user:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )
    try:
        user = CRUDUser.read_me(current_user)
    except ValueError as e:
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=str(e))
    return user

When there is a request for user/me it accuses

Error: response status is 422

response body
download
{
  "detail": [
    {
      "location": [
        "path",
        "user_id"
      ],
      "msg": "value is not a valid integer",
      "type": "type_error.integer"
    }
  ]
}

No reason. How to fix this issue? When erase @router.get("/user/{user_id}") the @router.get("/user/me") works properly.

fastapi = "^0.100.0"

When you get "/user/me", the "me" was post as user_id,string "me" is not a int,so got status 422. Put the “/user/me" before "/user/{user_id}" .

This is working properly as described in the documentation: https://fastapi.tiangolo.com/tutorial/path-params/#order-matters
Order of defined paths matters.

commented

This is working properly as described in the documentation: https://fastapi.tiangolo.com/tutorial/path-params/#order-matters Order of defined paths matters.