Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Include route in scope to allow middleware and other tools to extract its information #4603

merged 2 commits into from
Feb 21, 2022


Copy link

@tiangolo tiangolo commented Feb 21, 2022

This is useful, in particular, for external tools handling errors, logs, observability, etc. like Sentry.

There's a counterpart PR in Sentry: getsentry/sentry-python#1349

If you need this now, you can update Sentry's middleware like this:

from typing import TYPE_CHECKING, Any, Optional

from fastapi import FastAPI
from fastapi.routing import APIRoute
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware

    from sentry_sdk._types import Event, Hint

app = FastAPI()

class CustomSentryAsgiMiddleware(SentryAsgiMiddleware):
    def event_processor(
        self, event: "Event", hint: "Hint", asgi_scope: Any
    ) -> "Optional[Event]":
        result_event = super().event_processor(event, hint, asgi_scope)
        route: Optional[APIRoute] = asgi_scope.get("route")
        if route and result_event:
            result_event["transaction"] = route.path
        return result_event


Copy link

codecov bot commented Feb 21, 2022

Codecov Report

Merging #4603 (c5d8244) into master (1ce16c2) will not change coverage.
The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff            @@
##            master     #4603   +/-   ##
  Coverage   100.00%   100.00%           
  Files          525       526    +1     
  Lines        13281     13324   +43     
+ Hits         13281     13324   +43     
Impacted Files Coverage Δ
fastapi/ 100.00% <100.00%> (ø)
tests/ 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 1ce16c2...c5d8244. Read the comment docs.

Copy link

Copy link

📝 Docs preview for commit c5d8244 at:

@tiangolo tiangolo merged commit f5d7df3 into master Feb 21, 2022
@tiangolo tiangolo deleted the scope-include-route branch February 21, 2022 15:51
JeanArhancet pushed a commit to JeanArhancet/fastapi that referenced this pull request Aug 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

Successfully merging this pull request may close these issues.

None yet

1 participant