FastAPI

Learn how to set up Sentry in your FastAPI app, capture your first errors and traces, and view them in Sentry.

You need:

  • A Sentry account and project
  • Your application up and running
  • FastAPI 0.79.0+
  • Python 3.7+

Run the command for your preferred package manager to add the Sentry SDK to your application:

Copied
pip install "sentry-sdk"

Choose the features you want to configure, and this guide will show you how:

Want to learn more about these features?
  • Issues (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and unhandled rejections. If you have something that looks like an exception, Sentry can capture it.
  • Tracing: Track software performance while seeing the impact of errors across multiple systems. For example, distributed tracing allows you to follow a request from the frontend to the backend and back.
  • Profiling: Gain deeper insight than traditional tracing without custom instrumentation, letting you discover slow-to-execute or resource-intensive functions in your app.
  • Logs: Centralize and analyze your application logs to correlate them with errors and performance issues. Search, filter, and visualize log data to understand what's happening in your applications.
  • Application Metrics: Track and analyze custom application metrics, such as response times and database query durations, to understand trends and patterns in your application's performance and behavior over time.

Configuration should happen as early as possible in your application's lifecycle.

Import and initialize the SDK in your app's entry point:

Copied
import sentry_sdk
# ___PRODUCT_OPTION_START___ metrics
from sentry_sdk import metrics
# ___PRODUCT_OPTION_END___ metrics

sentry_sdk.init(
    dsn="___PUBLIC_DSN___",
    # Add data like request headers and IP for users, if applicable;
    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
    send_default_pii=True,
    # ___PRODUCT_OPTION_START___ performance
    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for tracing.
    traces_sample_rate=1.0,
    # ___PRODUCT_OPTION_END___ performance
    # ___PRODUCT_OPTION_START___ profiling
    # To collect profiles for all profile sessions,
    # set `profile_session_sample_rate` to 1.0.
    profile_session_sample_rate=1.0,
    # Profiles will be automatically collected while
    # there is an active span.
    profile_lifecycle="trace",
    # ___PRODUCT_OPTION_END___ profiling
)

To further customize your setup, review the Options section below.

Sentry automatically captures errors and reports issues for you. You can also expect the following for your FastAPI project:

  • By default, all exceptions leading to an Internal Server Error are captured and reported. The HTTP status codes to report on are configurable via the failed_request_status_codes option.
  • Request data will be attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads.
  • Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you set send_default_pii to True.

To learn how to manually report issues, see Capturing Errors.

The Sentry SDK automatically monitors the following parts of your FastAPI project:

  • Middleware stack
  • Middleware send and receive callbacks
  • Database queries
  • Redis commands

You can also manually capture performance data – see Custom Instrumentation to learn more.

Let's test your setup and confirm that data reaches your Sentry project.

To verify that Sentry captures errors and creates issues in your Sentry project, add this intentional error to your application:

Copied
from fastapi import FastAPI

sentry_sdk.init(...)  # same as above

app = FastAPI()

@app.get("/sentry-debug")
async def trigger_error():
    division_by_zero = 1 / 0

To test your tracing configuration, create a custom transaction and span:

Copied
import sentry_sdk

with sentry_sdk.start_transaction(op="task", name="Transaction Name"):
    span = sentry_sdk.start_span(name="Custom Span Name")
    span.finish()

To verify that Sentry catches your logs (which are enabled by default), add some log statements to your application:

Copied
import sentry_sdk

sentry_sdk.logger.info("This is an info log message")
sentry_sdk.logger.warning("This is a warning message")
sentry_sdk.logger.error("This is an error message")

Send test metrics from your app to verify metrics are arriving in Sentry:

Copied
from sentry_sdk import metrics

metrics.count("checkout.failed", 1)
metrics.gauge("queue.depth", 42)
metrics.distribution("cart.amount_usd", 187.5)

Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).

Need help locating the captured errors in your Sentry project?
  • Open the Issues page and select an error from the issues list to view the full details and context of this error. For more details, see the Issue Details documentation.
  • Open the Traces page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, click here.
  • Open the Profiles page, select a transaction, and then a profile ID to view its flame graph. For more information, click here.
  • Open the Logs page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, click here.
  • Open the Application Metrics page to view and analyze your metrics. For more details, see this interactive walkthrough.

Add FastApiIntegration to your sentry_sdk.init() call to set options for FastApiIntegration to change its behavior.

Copied
from sentry_sdk.integrations.starlette import StarletteIntegration
from sentry_sdk.integrations.fastapi import FastApiIntegration

sentry_sdk.init(
    # same as above
    integrations=[
        StarletteIntegration(
            transaction_style="endpoint",
            failed_request_status_codes={403, *range(500, 599)},
            http_methods_to_capture=("GET",),
        ),
        FastApiIntegration(
            transaction_style="endpoint",
            failed_request_status_codes={403, *range(500, 599)},
            http_methods_to_capture=("GET",),
        ),
    ]
)

You can pass the following keyword arguments to StarletteIntegration() and FastApiIntegration():

transaction_style

Typestring
Default"url"

How to name transactions that show up in Sentry tracing. The default is "url".

In the code example, the transaction name will be:

  • "/catalog/product/{product_id}" if you set transaction_style="url"
  • "product_detail" if you set transaction_style="endpoint"
Copied
  import sentry_sdk
  from sentry_sdk.integrations.starlette import StarletteIntegration
  from sentry_sdk.integrations.fastapi import FastApiIntegration

  sentry_sdk.init(
      # ...
      integrations=[
          StarletteIntegration(
              transaction_style="endpoint",
          ),
          FastApiIntegration(
              transaction_style="endpoint",
          ),
      ],
  )

  app = FastAPI()

  @app.get("/catalog/product/{product_id}")
  async def product_detail(product_id):
      return {...}

failed_request_status_codes

Typeset[int]
Default{*range(500, 600)}

A set of integers that determine which status codes should be reported to Sentry.

The failed_request_status_codes option determines whether HTTPException exceptions should be reported to Sentry. Unhandled exceptions that don't have a status_code attribute will always be reported to Sentry.

Examples of valid failed_request_status_codes:

  • {500} will only send events on HTTP 500.
  • {400, *range(500, 600)} will send events on HTTP 400 as well as the 5xx range.
  • {500, 503} will send events on HTTP 500 and 503.
  • set() (the empty set) will not send events for any HTTP status code.

The default is {*range(500, 600)}, meaning that all 5xx status codes are reported to Sentry.

middleware_spans

Typebool
DefaultFalse

Create spans and track performance of all middleware layers in your FastAPI project. Set to True to enable. The default is False.

http_methods_to_capture

Available since2.15.0
TypeTuple[str, ...]
Default("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)

A tuple containing all the HTTP methods (as uppercase strings) that should create a transaction in Sentry. The default is ("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",).

Note that OPTIONS and HEAD are excluded by default.

At this point, you should have integrated Sentry into your application and should already be sending data to your Sentry project.

Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:

Are you having problems setting up the SDK?
Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").