Registry / observability / starlette-exporter

starlette-exporter

JSON →
library0.24.0pypypi✓ verified 22d ago

starlette-exporter is a Python library that provides Prometheus metrics for Starlette applications, enabling easy monitoring of request rates, durations, and response statuses. It integrates as a middleware, automatically exposing a `/metrics` endpoint. The current version is 0.23.0, and it follows a regular release cadence with new features and improvements.

pip install starlette-exporter
INSTALL
IMPORT
SIG · STARLETTE-EXPORTER
S
starlette-exporter
observabilitypythonv0.24.0
Install
2.1s avg
Import
435ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.24.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.464s · 21.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.1s · import 0.406s · 22MB
19MB installed
● package 19MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PrometheusMiddleware
from starlette_exporter import PrometheusMiddleware
handle_metrics
from starlette_exporter import handle_metrics
Used to expose the /metrics endpoint in your Starlette routes.
from_header
from starlette_exporter import from_header
Helper for adding metric series labels from request headers.
from_response_header
from starlette_exporter import from_response_header
Helper for adding metric series labels from response headers (added in v0.22.0).

This quickstart demonstrates how to set up `starlette-exporter` with a basic Starlette application. It defines two simple routes and exposes a `/metrics` endpoint using `handle_metrics`. The `PrometheusMiddleware` is added to the application, configuring it to group paths for cleaner metrics. To run, save the code, install dependencies, and execute with uvicorn.

from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.routing import Route from starlette_exporter import PrometheusMiddleware, handle_metrics import uvicorn async def homepage(request): return PlainTextResponse("Hello, world!") async def user_page(request): username = request.path_params.get("username") return PlainTextResponse(f"Hello, {username}!") routes = [ Route("/", homepage), Route("/users/{username}", user_page), Route("/metrics", handle_metrics) # Expose the metrics endpoint ] app = Starlette(routes=routes) app.add_middleware( PrometheusMiddleware, app_name="my_starlette_app", group_paths=True, # Recommended for clean metrics paths # labels={"environment": "staging"}, # Example custom labels # group_unhandled_paths=True # New in v0.23.0 to group 404s under '__unknown__' ) # To run this application: # 1. Save the code as `main.py` # 2. Install dependencies: `pip install uvicorn starlette starlette-exporter prometheus_client` # 3. Run: `uvicorn main:app --reload` # Then, access metrics at http://127.0.0.1:8000/metrics # And application routes at http://127.0.0.1:8000/ or http://127.0.0.1:8000/users/alice
Debug
Known issues
breakingThe default values for `group_paths` and `filter_unhandled_paths` changed from `False` to `True`.
fix
If your application relied on the previous behavior without explicitly setting these options, you must now explicitly set `group_paths=False` or `filter_unhandled_paths=False` in the `PrometheusMiddleware` constructor to revert to the old defaults.
affects: >=0.18.0
breakingMinimum supported Starlette version increased to 0.35, and Python 3.7 support was dropped.
fix
Ensure your project uses Starlette 0.35.0 or newer and Python 3.8 or newer. Upgrade your environment and dependencies accordingly.
affects: >=0.18.0
gotchaThe `skip_paths` option now accepts regular expressions, which can subtly change behavior if existing exact path strings were coincidentally valid regex patterns.
fix
Review existing `skip_paths` configurations. If you intended exact string matches, ensure they are properly escaped (e.g., `['/my/path/']` might need `['/my/path/?']` if `?` was previously treated as a literal but is now a regex special character).
affects: >=0.20.0
gotchaClient disconnections (before a response is sent) are now reported with status code `499` instead of `500`.
fix
Update any monitoring alerts or dashboards that specifically look for `500` status codes for client disconnections to include `499`.
affects: >=0.17.0
gotchaUnhandled paths (404s) can now be grouped under a special `__unknown__` label, but this feature requires explicit enablement.
fix
To get metrics for requests against unhandled paths, set `group_unhandled_paths=True` in the `PrometheusMiddleware` constructor. This option overrides `filter_unhandled_paths`.
affects: >=0.23.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'starlette_exporter'
The 'starlette_exporter' package is not installed in the Python environment.
fix
pip install starlette-exporter
AttributeError: 'FastAPI' object has no attribute '_debug'
Version incompatibility between FastAPI and Starlette.
fix
pip install fastapi==0.89.1 starlette==0.22.0
AttributeError: 'Mount' object has no attribute 'endpoint'
This error occurs in older versions of `starlette-exporter` (prior to the fix in PR #7) when the `group_paths` option is enabled (which is the default) and the Starlette application includes `Mount` objects, typically used for serving static files.
fix
Upgrade `starlette-exporter` to version `0.23.0` or newer. If upgrading is not immediately possible, disable path grouping by initializing the middleware with `group_paths=False`: `app.add_middleware(PrometheusMiddleware, group_paths=False)`.
starlette-exporter metrics not showing /metrics endpoint empty
The Prometheus middleware is added, but the `/metrics` endpoint handler (`handle_metrics`) is not correctly exposed as a route in the Starlette application, or Prometheus is not configured to scrape the application's `/metrics` endpoint.
fix
Ensure both the `PrometheusMiddleware` is added to your Starlette application AND `handle_metrics` is registered as a route: `app.add_middleware(PrometheusMiddleware)` and `app.add_route('/metrics', handle_metrics)`. Additionally, verify that your Prometheus configuration includes a scrape job targeting your application's `/metrics` endpoint.
starlette_request_duration_seconds_bucket showing wrong data with BackgroundTasks
The `starlette-exporter` middleware measures the request duration until the HTTP response is sent. If your application uses FastAPI/Starlette's `BackgroundTasks`, these tasks execute *after* the response has been sent, meaning their execution time is not included in the middleware's reported request duration.
fix
The middleware is functioning as designed by measuring the duration until the response. If you need to monitor the duration of background tasks, you should instrument those tasks separately using custom Prometheus metrics (e.g., `prometheus_client.Histogram`) within the background task's logic.
Upgrade
Version history
0.24.0latest on PyPI · released Jul 29, 2026
Audit
Dependencies
starletterequiredRequired for the Starlette application framework.
prometheus_clientrequiredCore library for Prometheus client functionality.
Agent activity
26 hits · last 30 days
node
22
Bingbot
1
OpenAI (training)
1
Resources
starlette-exporter — pip install starlette-exporter · libregistry