In FastAPI, defining multiple API endpoints with the same path parameter but different paths is not straightforward. As the order of endpoint evaluation matters, the endpoint defined first will always be triggered, regardless of the request's specific path.
Consider the following router file where three endpoints are defined, each with a different path but sharing the "project_id" path parameter:
</p> <h1>GET API Endpoint 1</h1> <p>@router.get("/project/{project_id}/{employee_id}")<br>async def method_one(project_id: str, organization_id: str, session: AsyncSession = Depends(get_db)):</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"># ...
@router.get("/project/details/{project_id}")
async def method_two(project_id: str, session: AsyncSession = Depends(get_db)):
# ...
@router.get("/project/metadata/{project_id}")
async def method_three(project_id: str, session: AsyncSession = Depends(get_db)):
# ...
This code exhibits unexpected behavior where API Endpoints 2 and 3 invoke the controller method defined in Endpoint 1 (method_one()).
In FastAPI, endpoint evaluation occurs sequentially. Therefore, Endpoint 1 ("/project/{project_id}/{employee_id}") is evaluated first. When a subsequent request is made to Endpoint 2 or Endpoint 3, FastAPI interprets the "/project/{project_id}" portion of the path as the project_id parameter for Endpoint 1. This results in the controller method for Endpoint 1 being invoked.
To resolve this issue, the order of endpoint definition should be reversed so that the endpoints with the same path parameter are defined before the endpoint that includes additional path parameters:
</p> <h1>GET API Endpoint 2</h1> <p>@router.get("/project/details/{project_id}")</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"># ...
@router.get("/project/metadata/{project_id}")
# ...
@router.get("/project/{project_id}/{employee_id}")
# ...
By making this modification, FastAPI will evaluate Endpoints 2 and 3 first, ensuring that the appropriate controller methods are executed when requests are made to those endpoints.
The above is the detailed content of How to Define Multiple API Endpoints with the Same Path Parameter in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!