Replies: 1 comment
-
The routing phase will inject route info in request, so you can can access to those information after you received your response. In your case: class HTTPMiddleware(BaseHTTPMiddleware):
def __init__(self, app):
super().__init__(app)
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
# print path like /api/example/1234/cheese/567/info
print(f"Received {request.method} on {request.url.path}")
# TODO: print path as well like /api/example/{company_id}/cheese/{site_id}/info
print(request.scope["route"].path)
return response Just be careful that if a response fails, exceptions are not handled, or the routing phase is never reached due to an error, then the routing information will not be injected. Always check if the route key exists. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
I'm working on some FastAPI middlewear which we use for logging all of our API requests. At present I'm logging the request path, but I'd like to also log the template URL for the endpoint e.g. the literal string
/api/example/{company_id}/cheese/{site_id}/info
so that we can later filter our logs and see all request to a given endpoint, regardless of the particular IDs in the url.Is this possible with FastAPI? Somehow Sentry is able to tag errors with the endpoint URL in the "template form" we want, but I can't figure out how to access that information myself.
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.104.1
Pydantic Version
2.6.1
Python Version
3.11.10
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions