> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apitally.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Setup guide for FastAPI

> Set up the Apitally SDK for your FastAPI application.

<Info>This setup guide is for v1 of the Python SDK (currently in beta).</Info>

<Tip>Running FastAPI on Cloudflare Workers? Follow [this setup guide](/sdk-reference/python-serverless/v0/setup-guides/fastapi-cloudflare-workers) instead.</Tip>

This page guides you through the setup of the Apitally SDK for your [FastAPI](https://fastapi.tiangolo.com) application. If you don't have an Apitally account yet, [sign up](https://app.apitally.io/?signup) before getting started.

Once you're done with this guide, you will be able to:

* Get detailed metrics on API usage, errors, and performance
* Track API adoption and usage by individual consumers
* Log individual API requests, responses, and correlated application logs
* See what's causing slow API requests with traces
* Monitor uptime and set up custom alerts

## Requirements

Requires Python 3.10+ and FastAPI 0.108+.

## Create app

To get started, create a new app in the [Apitally dashboard](https://app.apitally.io/apps) and select FastAPI as your framework.

<img src="https://assets.apitally.io/docs/2025-12-08/create-app.webp" alt="Create app" className="rounded-xl" />

You can also configure the environments (e.g. `prod` and `dev`) for your app, or simply accept the defaults.

After submitting, you will see tailored setup instructions for your app. These include your write token and code snippets you can copy and paste into your project.

<Note>
  The **write token** (`apt_...`) provided in the setup instructions uniquely identifies your app for the purpose of data ingestion only. It does not grant any kind of read access to your data.
</Note>

## Install the SDK

Install the Apitally SDK with the `fastapi` extra as a dependency in your project.

<CodeGroup>
  ```shell pip theme={null}
  pip install --pre "apitally[fastapi]"
  ```

  ```shell uv theme={null}
  uv add --prerelease allow "apitally[fastapi]"
  ```

  ```shell poetry theme={null}
  poetry add --allow-prereleases "apitally[fastapi]"
  ```
</CodeGroup>

## Initialize Apitally

Call `apitally.init` with your FastAPI application, the write token, and [other configuration options](/sdk-reference/python/v1/configuration) immediately after creating the app.

```python {6-10} theme={null}
import apitally
from fastapi import FastAPI

app = FastAPI()

apitally.init(
    app,
    write_token="your-write-token",
    env="dev",  # or "prod" etc.
)
```

You can also set the `APITALLY_WRITE_TOKEN` and `APITALLY_ENV` environment variables instead of passing `write_token` and `env` in code.

Deploy your application with these changes, or restart it if you're testing locally.

<Check>
  The basic setup is now complete. Metrics and logs will start appearing in the Apitally
  dashboard.
</Check>

## Identify consumers

Consumers are the users or applications calling your API. Identifying them lets you analyze and filter API traffic by consumer in Apitally.

Call `apitally.set_consumer` during request handling to associate the current request with a consumer identifier. You can call it wherever the consumer is known, such as in an endpoint, dependency, existing middleware, or authentication code.

You can also provide a display name and group for each consumer.

<CodeGroup>
  ```python Dependency {10-14} theme={null}
  from typing import Annotated

  import apitally
  from fastapi import Depends, FastAPI


  def identify_consumer(
      current_user: Annotated[User, Depends(get_current_user)],
  ) -> None:
      apitally.set_consumer(
          current_user.user_id,
          name=current_user.name,  # optional
          group=current_user.group,  # optional
      )


  app = FastAPI(dependencies=[Depends(identify_consumer)])
  apitally.init(app, write_token="your-write-token")
  ```

  ```python Endpoint function {14-18} theme={null}
  from typing import Annotated

  import apitally
  from fastapi import Depends, FastAPI

  app = FastAPI()
  apitally.init(app, write_token="your-write-token")


  @app.get("/items")
  async def list_items(
      current_user: Annotated[User, Depends(get_current_user)],
  ) -> list[str]:
      apitally.set_consumer(
          current_user.user_id,
          name=current_user.name,  # optional
          group=current_user.group,  # optional
      )
      return ["item1"]
  ```
</CodeGroup>

## Capture headers and bodies

Only response headers are captured by default. You can opt in to capture request headers as well as request and response bodies when initializing Apitally.

```python {5-7} theme={null}
apitally.init(
    app,
    write_token="your-write-token",
    env="dev",  # or "prod" etc.
    capture_request_headers=True,
    capture_request_body=True,
    capture_response_body=True,
)
```

## Mask sensitive information

The SDK automatically masks common sensitive query parameters, headers, and body fields.

To mask additional data, pass regular expressions matching query parameter names, header names, or body field names to `mask_query_params`, `mask_headers`, or `mask_body_fields`, respectively. Matching is case-insensitive.

```python {4-6} theme={null}
apitally.init(
    app,
    write_token="your-write-token",
    mask_query_params=[r"^account_id$"],
    mask_headers=[r"^X-Custom-Key$"],
    mask_body_fields=[r"^credit_card$"],
)
```

You can use the `mask_request_body` and `mask_response_body` callbacks to mask individual fields or entire bodies using custom logic. Use `mask_log_record` to mask or drop application log records.

More information about masking is available [here](/sdk-reference/python/v1/masking).

## Sample requests

If your application receives a lot of traffic, you may want to sample requests to stay within your request logs quota. Metrics will continue to count every request regardless of sampling.

Use `sample_rate` to capture logs and traces for a fraction of requests.

```python {4} theme={null}
apitally.init(
    app,
    write_token="your-write-token",
    sample_rate=0.1,  # capture logs and traces for 10% of requests
)
```

You can also use the `sample_on_request` and `sample_on_response` callbacks to make sampling decisions using custom logic.

More information about sampling is available [here](/sdk-reference/python/v1/sampling).

## Instrument third-party libraries

Instrumenting third-party libraries adds details about database queries, HTTP calls to external services, and other operations to your request traces. This lets you see how these operations contribute to API response times.

The SDK provides helper functions in `apitally.otel` to instrument popular libraries. Each requires a separate OpenTelemetry instrumentation package. For example, to trace database queries made with SQLAlchemy, install `opentelemetry-instrumentation-sqlalchemy`:

<CodeGroup>
  ```shell pip theme={null}
  pip install opentelemetry-instrumentation-sqlalchemy
  ```

  ```shell uv theme={null}
  uv add opentelemetry-instrumentation-sqlalchemy
  ```

  ```shell poetry theme={null}
  poetry add opentelemetry-instrumentation-sqlalchemy
  ```
</CodeGroup>

Then call `instrument_sqlalchemy` with your SQLAlchemy engine at application startup:

```python theme={null}
from apitally.otel import instrument_sqlalchemy

instrument_sqlalchemy(engine)
```

More information about tracing and the provided instrumentation helpers is available [here](/sdk-reference/python/v1/tracing).
