Skip to content

Commit d99feb3

Browse files
committed
docs(py-fastapi): Align FastAPI integration page with new Python structure (features, options, logs, tracing, verify, next steps)
1 parent e6665c2 commit d99feb3

File tree

1 file changed

+229
-94
lines changed
  • docs/platforms/python/integrations/fastapi

1 file changed

+229
-94
lines changed

docs/platforms/python/integrations/fastapi/index.mdx

Lines changed: 229 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,46 @@
11
---
22
title: FastAPI
3-
description: "Learn about using Sentry with FastAPI."
3+
description: Learn how to set up and configure Sentry in your FastAPI application, capture your first errors, and view them in Sentry.
4+
caseStyle: snake_case
5+
supportLevel: production
46
---
57

6-
The FastAPI integration adds support for the [FastAPI Framework](https://fastapi.tiangolo.com/).
8+
The FastAPI integration adds support for the FastAPI framework.
9+
10+
<PlatformContent includePath="llm-steering" />
11+
12+
<PlatformContent includePath="getting-started-prerequisites" />
13+
14+
## Features
15+
16+
In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/).
17+
18+
Send <PlatformLink to="/platforms/python/logs/">structured logs</PlatformLink> to Sentry and correlate them with errors and traces.
19+
20+
FastAPI-specific behavior and performance coverage:
21+
22+
- By default, all exceptions leading to an Internal Server Error are captured and reported. You can configure which status codes are reported via the `failed_request_status_codes` option.
23+
- Request data (URL, HTTP method, headers, form data, JSON payloads) is attached to issues. Raw bodies and multipart file uploads are excluded.
24+
- PII (like user IDs, usernames, cookies, auth headers, IPs) is excluded unless you set `send_default_pii=True`.
25+
- Performance spans cover middleware (including `send`/`receive`), database queries, and Redis commands.
26+
27+
![Issues List](./img/fastapi-issues-list.png)
28+
29+
![Performance details are shown as waterfall diagram](./img/fastapi-performance-details.png)
30+
31+
Select which Sentry features you'd like to configure to get the corresponding setup instructions below.
32+
33+
<OnboardingOptionButtons
34+
options={[
35+
{id: "error-monitoring", checked: true, disabled: true},
36+
{id: "performance", checked: true},
37+
{id: "logs", checked: true},
38+
]}
39+
/>
740

841
## Install
942

10-
Install `sentry-sdk` from PyPI with the `fastapi` extra:
43+
Install the Sentry SDK using the FastAPI extra:
1144

1245
```bash {tabTitle:pip}
1346
pip install "sentry-sdk[fastapi]"
@@ -18,69 +51,219 @@ uv add "sentry-sdk[fastapi]"
1851

1952
## Configure
2053

21-
If you have the `fastapi` package in your dependencies, the FastAPI integration will be enabled automatically when you initialize the Sentry SDK.
54+
Configuration should happen as early as possible in your application's lifecycle. If `fastapi` is in your dependencies, the FastAPI integration is enabled automatically when you initialize the SDK.
55+
56+
```python {filename:main.py}
57+
import sentry_sdk
58+
59+
sentry_sdk.init(
60+
dsn="___PUBLIC_DSN___",
61+
62+
# Adds request headers and IP for users, for more info visit:
63+
# https://docs.sentry.io/platforms/python/data-management/data-collected/
64+
send_default_pii=True,
65+
66+
# ___PRODUCT_OPTION_START___ logs
67+
# Enable logs to be sent to Sentry
68+
_experiments={"enable_logs": True},
69+
# ___PRODUCT_OPTION_END___ logs
70+
71+
# ___PRODUCT_OPTION_START___ performance
72+
# Set traces_sample_rate to 1.0 to capture 100%
73+
# of transactions for tracing.
74+
# We recommend adjusting this value in production
75+
# Learn more at
76+
# https://docs.sentry.io/platforms/python/configuration/options/#traces-sample-rate
77+
traces_sample_rate=1.0,
78+
# ___PRODUCT_OPTION_END___ performance
79+
)
80+
```
81+
82+
<Alert>
83+
84+
To record performance data, set [traces_sample_rate](/platforms/python/configuration/options/#traces-sample-rate) when initializing the SDK.
2285

23-
<PlatformContent includePath="getting-started-config" />
86+
</Alert>
87+
88+
## Step 3: Capture Python Errors
89+
90+
The Sentry SDK automatically captures unhandled exceptions. You can also manually capture errors and add context:
2491

25-
## Verify
92+
### Automatic Error Capture
2693

2794
```python
28-
from fastapi import FastAPI
95+
# This will be automatically captured by Sentry
96+
division_by_zero = 1 / 0
97+
```
2998

30-
sentry_sdk.init(...) # same as above
99+
### Manual Error Capture
31100

32-
app = FastAPI()
101+
```python
102+
import sentry_sdk
33103

34-
@app.get("/sentry-debug")
35-
async def trigger_error():
36-
division_by_zero = 1 / 0
104+
try:
105+
risky_operation()
106+
except Exception as e:
107+
# Capture the exception with additional context
108+
sentry_sdk.capture_exception(e)
37109
```
38110

39-
When you point your browser to [http://localhost:8000/sentry-debug](http://localhost:8000/sentry-debug) a transaction will be created in the Performance section of [sentry.io](https://sentry.io). Additionally, an error event will be sent to [sentry.io](https://sentry.io) and will be connected to the transaction.
111+
<Alert>
40112

41-
It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io).
113+
Learn more about manually capturing errors in our <PlatformLink to="/usage/">Usage documentation</PlatformLink>.
42114

43-
## Behaviour
115+
</Alert>
44116

45-
### Issue Reporting
117+
### Adding User Context
46118

47-
The following information about your FastAPI project will be available to you on Sentry.io:
119+
```python
120+
import sentry_sdk
121+
122+
# Set user context for all future events
123+
sentry_sdk.set_user({
124+
"id": "123",
125+
"username": "jane.doe",
126+
"email": "[email protected]"
127+
})
128+
129+
# Add custom tags
130+
sentry_sdk.set_tag("page_locale", "en-us")
131+
132+
# Add custom context
133+
sentry_sdk.set_context("character", {
134+
"name": "Mighty Fighter",
135+
"age": 19,
136+
"attack_type": "melee"
137+
})
138+
```
48139

49-
- 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](#options).
50-
- Request data such as URL, HTTP method, headers, form data, and JSON payloads is attached to all issues.
51-
- Sentry excludes raw bodies and multipart file uploads.
52-
- Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you set `send_default_pii` to `True`.
140+
<OnboardingOption optionId="performance">
53141

54-
![Issues List](./img/fastapi-issues-list.png)
142+
<OnboardingOption optionId="logs">
55143

56-
### Monitor Performance
144+
## Step 4: Sending Logs
57145

58-
The following parts of your FastAPI project are monitored:
146+
Now let's add structured logging to capture application insights. Logs are enabled in your configuration above.
59147

60-
- Middleware stack
61-
- Middleware `send` and `receive` callbacks
62-
- Database queries
63-
- Redis commands
148+
Use Python's logging module to capture structured logs with meaningful attributes that help you debug issues and understand user behavior.
64149

65-
![Performance details are shown as waterfall diagram](./img/fastapi-performance-details.png)
150+
```python
151+
import logging
152+
153+
# Configure Python logging
154+
logger = logging.getLogger(__name__)
155+
156+
# Send structured logs with attributes
157+
logger.info(
158+
"User completed checkout",
159+
extra={
160+
"user_id": 123,
161+
"order_id": "order_456",
162+
"amount": 99.99
163+
}
164+
)
66165

67-
<Alert>
166+
logger.error(
167+
"Payment processing failed",
168+
extra={
169+
"error_code": "CARD_DECLINED",
170+
"user_id": 123,
171+
"attempt_count": 3
172+
}
173+
)
174+
175+
# Log with exception information
176+
try:
177+
process_payment()
178+
except PaymentError as e:
179+
logger.exception(
180+
"Payment failed with exception",
181+
extra={"transaction_id": "txn_789"}
182+
)
183+
```
68184

69-
The parameter [traces_sample_rate](/platforms/python/configuration/options/#traces-sample-rate) needs to be set when initializing the Sentry SDK for performance measurements to be recorded.
185+
</OnboardingOption>
70186

71-
</Alert>
187+
## Step 5: Custom Traces with Attributes
188+
189+
Create custom spans to measure specific operations and add meaningful attributes. This helps you understand performance bottlenecks and debug issues with detailed context.
190+
191+
```python
192+
import sentry_sdk
193+
194+
# Create custom spans to measure specific operations
195+
def process_user_data(user_id):
196+
with sentry_sdk.start_span(
197+
op="function",
198+
description="Process User Data",
199+
data={
200+
"user_id": user_id,
201+
"operation": "data_processing",
202+
"version": "2.1"
203+
}
204+
) as span:
205+
# Your business logic here
206+
user_data = fetch_user_data(user_id)
207+
208+
# Nested span for specific operations
209+
with sentry_sdk.start_span(
210+
op="transform",
211+
description="Transform Data",
212+
data={
213+
"record_count": len(user_data),
214+
"transform_type": "normalize"
215+
}
216+
) as inner_span:
217+
result = transform_user_data(user_data)
218+
219+
return result
220+
221+
# Add attributes to existing spans
222+
span = sentry_sdk.get_current_span()
223+
if span:
224+
span.set_data("cache_hit", True)
225+
span.set_data("region", "us-west-2")
226+
span.set_data("performance_score", 0.95)
227+
```
228+
229+
</OnboardingOption>
230+
231+
## Verify Your Setup
232+
233+
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
234+
235+
### Test Error Capturing
236+
237+
```python
238+
from fastapi import FastAPI
239+
240+
app = FastAPI()
241+
242+
@app.get("/sentry-debug")
243+
async def trigger_error():
244+
division_by_zero = 1 / 0
245+
```
246+
247+
Run your application and visit http://localhost:8000/sentry-debug to send an error and transaction to Sentry.
248+
249+
<PlatformContent includePath="getting-started-browser-sandbox-warning" />
250+
251+
### View Captured Data in Sentry
252+
253+
Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear).
254+
255+
<PlatformContent includePath="getting-started-verify-locate-data" />
72256

73257
## Options
74258

75-
By adding `FastApiIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `FastApiIntegration` to change its behavior.
76-
Because FastAPI is based on the Starlette framework, both integrations, `StarletteIntegration` and `FastApiIntegration`, must be instantiated.
259+
If you want to customize behavior, you can explicitly add FastAPI/Starlette integrations and set options:
77260

78261
```python
79262
from sentry_sdk.integrations.starlette import StarletteIntegration
80263
from sentry_sdk.integrations.fastapi import FastApiIntegration
81264

82265
sentry_sdk.init(
83-
# same as above
266+
# ... keep your existing options here ...
84267
integrations=[
85268
StarletteIntegration(
86269
transaction_style="endpoint",
@@ -98,68 +281,20 @@ sentry_sdk.init(
98281

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

101-
- `transaction_style`:
102-
103-
This option lets you influence how the transactions are named in Sentry. For example:
104-
105-
```python
106-
import sentry_sdk
107-
from sentry_sdk.integrations.starlette import StarletteIntegration
108-
from sentry_sdk.integrations.fastapi import FastApiIntegration
109-
110-
sentry_sdk.init(
111-
# ...
112-
integrations=[
113-
StarletteIntegration(
114-
transaction_style="endpoint",
115-
),
116-
FastApiIntegration(
117-
transaction_style="endpoint",
118-
),
119-
],
120-
)
121-
122-
app = FastAPI()
123-
124-
@app.get("/catalog/product/{product_id}")
125-
async def product_detail(product_id):
126-
return {...}
127-
```
128-
129-
In the above code, the transaction name will be:
130-
131-
- `"/catalog/product/{product_id}"` if you set `transaction_style="url"`
132-
- `"product_detail"` if you set `transaction_style="endpoint"`
284+
- `transaction_style`: Controls how transactions are named in Sentry. For example, with a route like `@app.get("/catalog/product/{product_id}")`, the transaction will be `"/catalog/product/{product_id}"` when set to `"url"` and `"product_detail"` when set to `"endpoint"`. Default is `"url"`.
285+
- `failed_request_status_codes`: A set of status codes that should be reported to Sentry for handled HTTP exceptions. Unhandled exceptions without `status_code` are always reported. Defaults to all 5xx.
286+
- `http_methods_to_capture`: Which HTTP methods create transactions. Default is `("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)`.
133287

134-
The default is `"url"`.
135-
136-
- `failed_request_status_codes`:
137-
138-
A `set` of integers that will determine which status codes should be reported to Sentry.
139-
140-
The `failed_request_status_codes` option determines whether [`HTTPException`](https://fastapi.tiangolo.com/reference/exceptions/?h=httpexception) exceptions should be
141-
reported to Sentry. Unhandled exceptions that don't have a `status_code` attribute will always be reported to Sentry.
142-
143-
Examples of valid `failed_request_status_codes`:
144-
145-
- `{500}` will only send events on HTTP 500.
146-
- `{400, *range(500, 600)}` will send events on HTTP 400 as well as the 5xx range.
147-
- `{500, 503}` will send events on HTTP 500 and 503.
148-
- `set()` (the empty set) will not send events for any HTTP status code.
149-
150-
The default is `{*range(500, 600)}`, meaning that all 5xx status codes are reported to Sentry.
151-
152-
- `http_methods_to_capture`:
153-
154-
A tuple containing all the HTTP methods that should create a transaction in Sentry.
155-
156-
The default is `("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)`.
288+
<Alert title="Added in 2.15.0">
289+
The `http_methods_to_capture` option.
290+
</Alert>
157291

158-
(Note that `OPTIONS` and `HEAD` are missing by default.)
292+
## Next Steps
159293

160-
<Alert title="Added in 2.15.0">
161-
The `http_methods_to_capture` option.
162-
</Alert>
294+
- Continue to <PlatformLink to="/configuration">customize your configuration</PlatformLink>
295+
- Learn more about <PlatformLink to="/platforms/python/integrations/">instrumenting frameworks</PlatformLink>
296+
- Learn how to <PlatformLink to="/usage">manually capture errors</PlatformLink>
297+
- Set up <PlatformLink to="/configuration/releases/">release tracking</PlatformLink>
163298

164299
## Supported Versions
165300

0 commit comments

Comments
 (0)