Update
If what you need is the original route path, i.e., /users/{user_id}
, you could use the below. The way it works is by getting the root_path
first—which would normally be an empty string, unless you have mounted sub-application(s) to the top-level app (e.g., app.mount("/subapi", subapi)
), and hence, you need the result to be prefixed with that specific path /subapi
—and then append to it the route's path , which you can get from the APIRoute object. Example:
from fastapi import Request
@app.get('/users/{user_id}')
def get_user(user_id: str, request: Request):
path = request.scope['root_path'] + request.scope['route'].path
return path
Output:
/users/{user_id}
Original answer
As per FastAPI documentation:
As FastAPI is actually Starlette underneath, with a layer of several
tools on top, you can use Starlette's Request
object directly when you
need to.
Thus, you can use Request
object to get the URL path. For instance:
from fastapi import Request
@app.get('/users/{user_id}')
def get_user(user_id: str, request: Request):
return request.url.path
Output (if the received user_id
was 1
):
/users/1