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

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

export const language_0 = "python"

export const framework_1 = "BlackSheep"

export const extra_0 = "blacksheep"

export const framework_0 = "Starlette"

This page guides you through the steps of configuring your [BlackSheep](https://www.neoteroi.dev/blacksheep/) 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[blacksheep]"
  ```

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

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

Add the Apitally middleware to your BlackSheep 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 blacksheep import Application
from apitally.blacksheep import use_apitally

app = Application()
use_apitally(
    app,
    client_id="your-client-id",
    env="dev",  # or "prod" etc.
)
```

<div style={{ marginTop: "-0.5rem" }}>
  <Note>
    Add the Apitally middleware before any other middleware to ensure it wraps the entire stack.
  </Note>
</div>

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.

To associate requests with consumers, provide a callback function that takes a [`Request`](https://www.neoteroi.dev/blacksheep/requests/#the-request-class) object as an argument and returns a consumer identifier, an `ApitallyConsumer` object or `None`.

Alternatively, you can set the `apitally_consumer` claim on the `request.identity` object, for example in your authentication handler.

<CodeGroup>
  ```python Callback theme={null}
  from blacksheep import Application, Request
  from apitally.blacksheep import use_apitally

  def get_consumer(request: Request) -> str | None:
      if request.identity.is_authenticated:
          return request.identity.sub
      return None

  app = Application()
  use_apitally(
      app,
      client_id="your-client-id",
      env="dev",  # or "prod" etc.
      consumer_callback=get_consumer,
  )
  ```

  ```python Callback (with name and group) theme={null}
  from blacksheep import Application, Request
  from apitally.blacksheep import use_apitally, ApitallyConsumer

  def get_consumer(request: Request) -> ApitallyConsumer | None:
      if request.identity.is_authenticated:
          return ApitallyConsumer(
              identifier=request.identity.sub,
              name=request.identity.get("name"),  # optional
              group=request.identity.get("role"),  # optional
          )
      return None

  app = Application()
  use_apitally(
      app,
      client_id="your-client-id",
      env="dev",  # or "prod" etc.
      consumer_callback=get_consumer,
  )
  ```

  ```python Claim on identity theme={null}
  from blacksheep import Request
  from guardpost import AuthenticationHandler, Identity

  class ExampleAuthHandler(AuthenticationHandler):
      async def authenticate(self, context: Request) -> Identity | None:
          header_value = context.get_first_header(b"Authorization")

          if header_value:
              claims = {
                  "name": "John Doe",
                  "email": "john.doe@example.com",
                  "apitally_consumer": "john.doe@example.com",
              }
              context.identity = Identity(claims, "MOCK")
              return context.identity
          else:
              context.identity = None
          return context.identity
  ```
</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 blacksheep import Application
  from apitally.blacksheep import use_apitally

  app = Application()
  use_apitally(
      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 blacksheep import Application
  from apitally.blacksheep import use_apitally

  app = Application()
  use_apitally(
      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.
