'FastAPI: How to get raw URL path from request?

I have a GET method with request parameter in path:

@router.get('/users/{user_id}')
async def get_user_from_string(user_id: str):
    return User(user_id)

Is it possible to get base url raw path ('/users/{user_id}') from request?

I have tried to use the following way:

path = [route for route in request.scope['router'].routes if
        route.endpoint == request.scope['endpoint']][0].path

But it doesn't work and I get:

AttributeError: 'Mount' object has no attribute 'endpoint'



Solution 1:[1]

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 FastAPI, Request

app = FastAPI()

@app.get('/users/{user_id}')
async def get_user(user_id: str, request: Request):
    print(request.url.path)
    return "something"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris