Search code examples
pythonurl-routingfastapistarlette

FastAPI: How to get raw URL path from request?


I have a GET method with requested 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 (i.e., '/users/{user_id}') from the 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

  • You can use the APIRout object property in the request to get the actual path

    example:

    raw_path = request.scope['route'].path 
    #'/user/{id}'