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?
@app.get("/services/{service}", name="abc")
async def list_services() -> dict:
do something
Update 1: Output of request.scope
{'type': 'http', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'server': ('127.0.0.1', 8001), 'client': ('127.0.0.1', 56670), 'scheme': 'http', 'root_path': '', 'headers': [(b'user-agent', b'PostmanRuntime/7.29.2'), (b'accept', b'*/*'), (b'postman-token', b'f2da2d0f-e721-44c8-b14f-e19750ea8a68'), (b'host', b'localhost:8001'), (b'accept-encoding', b'gzip, deflate, br'), (b'connection', b'keep-alive')], 'method': 'GET', 'path': '/health', 'raw_path': b'/health', 'query_string': b'', 'app': <fastapi.applications.FastAPI object at 0x1036d5790>}
Update 2:
Providing middleware code where request.scope["route"]
is breaking.
from fastapi import FastAPI,Request
app = FastAPI()
@app.middleware("http")
async def logging_middleware(request: Request, call_next):
print(request.scope['route'].name)
response = await call_next(request)
return response
@app.get('/', name='abc')
def get_name(request: Request):
return request.scope['route'].name