Skip to content
Advertisement

How to get route’s name using FastAPI/Starlette?

How can I get the name of a route/endpoint using FastAPI/Starlette? I have access to the Request object and I need this information in one of my middlewares. For example, if I hit services/1, I should then be able to get the abc name. Is this possible in FastAPI?

JavaScript

Update 1: Output of request.scope

JavaScript

Update 2: Providing middleware code where request.scope[“route”] is breaking.

JavaScript

Advertisement

Answer

Option 1

You can get the name value inside an endpoint as follows:

JavaScript

Option 2

In a middleware, make sure to get the route’s name after calling call_next(request), otherwise you would be faced with KeyError: 'route', as the route key/object would not yet exist in the scope dictionary. Example:

JavaScript

Option 3

Instead of a middleware, you could create a custom APIRoute class, which would allow you to get the route’s name before processing the request and getting the response (if that’s a requirement for your app). You could add an endpoint that you would like to be handled by that APIRoute class using @<name_of_router_instance> instead of @app (e.g., @router.get('/', name='abc')). More than one endpoint could be added in the same way. Example:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement