How to define multiple API endpoints in FastAPI with different paths but the same path parameter?

In FastAPI, as described in this answer, because endpoints are evaluated in order (see FastAPI’s about how order matters), it makes sure that the endpoint you defined first in your app—in this case, that is, /project/{project_id}/...—will be evaluated first. Hence, every time you call one of the other two endpoints, i.e., /project/details/... and /project/metadata/..., the first endpoint is triggered, using details or metadata as the project_id parameter.

Solution

Thus, you need to make sure that the other two endpoints are declared before the one for /project/{project_id}/.... For example:

# GET API Endpoint 1
@router.get("/project/details/{project_id}")
    # ...

# GET API Endpoint 2
@router.get("/project/metadata/{project_id}")
    # ...

# GET API Endpoint 3
@router.get("/project/{project_id}/{employee_id}")
    # ...

Leave a Comment