> ## 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 Flask

> Just a few simple steps to get started with Apitally.

export const language_0 = "python"

export const framework_2 = "Flask"

export const framework_1 = "Flask"

export const extra_0 = "flask"

export const framework_0 = "Flask"

This page guides you through the steps of configuring your [Flask](https://flask.palletsprojects.com) application to work with Apitally. If you don't have an account yet, now would be a good time to [sign up](https://app.apitally.io/?signup).

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

## Create app

To get started, create a new app in the [Apitally dashboard](https://app.apitally.io/apps) and select {framework_0} 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 code snippets you can copy and paste into your project.

<Note>
  The **client ID** 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>

## Add middleware

Next, install the [Apitally SDK](/sdk-reference/python/overview) in your {framework_1} project with the <code>{extra_0}</code> extra.

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

  ```shell poetry theme={null}
  poetry add "apitally[flask]"
  ```

  ```shell uv theme={null}
  uv add "apitally[flask]"
  ```
</CodeGroup>

Add the Apitally middleware to your Flask application and provide the `client_id` for your app.
You'll find the `client_id` on the *Setup instructions* page for your app in the Apitally dashboard, which is displayed immediately after creating the app.

```python theme={null}
from flask import Flask
from apitally.flask import ApitallyMiddleware

app = Flask(__name__)
app.wsgi_app = ApitallyMiddleware(
    app,
    client_id="your-client-id",
    env="dev",  # or "prod" etc.
)
```

<div style={{ marginTop: "-0.5rem" }}>
  <Note>
    If you're also using other middlewares, add the `ApitallyMiddleware` last, so
    that it wraps the existing stack of middlewares.
  </Note>
</div>

<Warning>
  If you're using Gunicorn or uWSGI to serve your {framework_2} app in production, please review the [known issues](#known-issues) section below.
</Warning>

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

<Check>
  At this point the basic setup for your application is complete and you will start seeing data in the Apitally dashboard.
</Check>

## Identify consumers

To analyze and filter API traffic by consumers, you can associate requests with consumer identifiers in your application.

In most cases, use the authenticated identity to identify the consumer.
The identifier should be a string, such as a username, email address, or any other unique identifier.

Optionally, you can also provide a display name and group for each consumer.

Use the `set_consumer` function to associate requests with consumers, for example within a [`before_request`](https://flask.palletsprojects.com/en/2.2.x/api/#flask.Flask.before_request) function or directly in your endpoint functions.

<CodeGroup>
  ```python Before request theme={null}
  from flask import g
  from apitally.flask import set_consumer

  @app.before_request
  def identify_consumer():
      if g.current_user:
          set_consumer(
              identifier=g.current_user["email"],
              name=g.current_user["name"],  # optional
              group=g.current_user["role"],  # optional
          )
  ```

  ```python Endpoint function theme={null}
  from flask import g
  from apitally.flask import set_consumer

  @app.route("/items")
  def list_items():
      if g.current_user:
          set_consumer(
              identifier=g.current_user["email"],
              name=g.current_user["name"],  # optional
              group=g.current_user["role"],  # optional
          )
      return ["item1"]
  ```
</CodeGroup>

<Check>
  The *Consumers* dashboard now shows all consumers that have made requests to your application. You can also filter other dashboards by consumer.
</Check>

## Configure request logging

Logging of individual requests and responses is disabled by default to protect potentially sensitive data.
If you enable it, you can configure in detail what parts of the request and response should be logged.
You can also mask sensitive information (e.g. in headers) and exclude certain requests from logging.

The SDK applies [default masking rules](/data-privacy#data-masking) for common sensitive headers, query parameters and request/response body fields.

{language_0 == "python" && <p>Check out the <a href="/sdk-reference/python/configuration">SDK reference</a> to learn more about the request logging configuration options.</p>}

{language_0 == "javascript" && <p>Check out the <a href="/sdk-reference/javascript/configuration">SDK reference</a> to learn more about the request logging configuration options.</p>}

{language_0 == "go" && <p>Check out the <a href="/sdk-reference/go/configuration">SDK reference</a> to learn more about the request logging configuration options.</p>}

<CodeGroup>
  ```python Basic example theme={null}
  from flask import Flask
  from apitally.flask import ApitallyMiddleware

  app = Flask(__name__)
  app.wsgi_app = ApitallyMiddleware(
      app,
      client_id="your-client-id",
      env="dev",  # or "prod" etc.
      enable_request_logging=True,
      log_request_headers=True,
      log_request_body=True,
      log_response_body=True,
      capture_logs=True,
      capture_traces=False,  # requires instrumentation
  )
  ```

  ```python Advanced example theme={null}
  from flask import Flask
  from apitally.flask import ApitallyMiddleware

  app = Flask(__name__)
  app.wsgi_app = ApitallyMiddleware(
      app,
      client_id="your-client-id",
      env="dev",  # or "prod" etc.
      enable_request_logging=True,
      log_query_params=True,
      log_request_headers=True,
      log_request_body=True,
      log_response_headers=True,
      log_response_body=True,
      log_exception=True,
      capture_logs=True,
      capture_traces=False,  # requires instrumentation
      # Mask query parameters using regex
      mask_query_params=[r"^card_number$"],
      # Mask headers using regex
      mask_headers=[r"^X-Sensitive-Header$"],
      # Mask request/response body fields using regex
      mask_body_fields=[r"^sensitive_field$"],
      # Mask request/response body with custom logic via callbacks (e.g. for admin endpoints)
      # The callback should return None to mask the whole body, or return the (modified) raw body
      mask_request_body_callback=lambda request: None if request["path"].startswith("/admin/") else request["body"],
      mask_response_body_callback=lambda request, response: None if request["path"].startswith("/admin/") else response["body"],
      # Exclude paths from request logging using regex (common health check paths are excluded by default)
      exclude_paths=[r"/metrics$"],
      # Exclude requests from logging with custom logic via callback (e.g. exclude requests from a specific consumer)
      # The callback should return True to exclude the request
      exclude_callback=lambda request, response: request["consumer"] == "some-consumer",
  )
  ```
</CodeGroup>

<Check>
  The *Request logs* dashboard now shows individual requests handled by your application. You can filter, search, and inspect them in detail.
</Check>

## Enable tracing

Tracing gives you a detailed breakdown of time spent during the handling of each request, showing the duration of database queries, HTTP calls, and other operations.

To enable tracing, set `capture_traces` to `True` and instrument the libraries you want to trace with OpenTelemetry. See the [tracing guide](/sdk-reference/python/tracing) for further instructions.

## Known issues

* When running Flask with Gunicorn, the option `preload_app` must be set to `False`. Otherwise, the Apitally client will not work correctly.
* When running Flask with uWSGI, the options `--enable-threads` and `--lazy-apps` must be set. Otherwise, the Apitally client will not work correctly.
