{"id":3818,"library":"starlette-exporter","title":"Prometheus Metrics Exporter for Starlette","description":"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.","status":"active","version":"0.23.0","language":"python","source_language":"en","source_url":"https://github.com/stephenhillier/starlette_exporter","tags":["starlette","prometheus","metrics","monitoring","middleware","fastapi"],"install":[{"cmd":"pip install starlette-exporter","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Required for the Starlette application framework.","package":"starlette","optional":false},{"reason":"Core library for Prometheus client functionality.","package":"prometheus_client","optional":false}],"imports":[{"symbol":"PrometheusMiddleware","correct":"from starlette_exporter import PrometheusMiddleware"},{"note":"Used to expose the /metrics endpoint in your Starlette routes.","symbol":"handle_metrics","correct":"from starlette_exporter import handle_metrics"},{"note":"Helper for adding metric series labels from request headers.","symbol":"from_header","correct":"from starlette_exporter import from_header"},{"note":"Helper for adding metric series labels from response headers (added in v0.22.0).","symbol":"from_response_header","correct":"from starlette_exporter import from_response_header"}],"quickstart":{"code":"from starlette.applications import Starlette\nfrom starlette.responses import PlainTextResponse\nfrom starlette.routing import Route\nfrom starlette_exporter import PrometheusMiddleware, handle_metrics\nimport uvicorn\n\nasync def homepage(request):\n    return PlainTextResponse(\"Hello, world!\")\n\nasync def user_page(request):\n    username = request.path_params.get(\"username\")\n    return PlainTextResponse(f\"Hello, {username}!\")\n\nroutes = [\n    Route(\"/\", homepage),\n    Route(\"/users/{username}\", user_page),\n    Route(\"/metrics\", handle_metrics) # Expose the metrics endpoint\n]\n\napp = Starlette(routes=routes)\napp.add_middleware(\n    PrometheusMiddleware,\n    app_name=\"my_starlette_app\",\n    group_paths=True, # Recommended for clean metrics paths\n    # labels={\"environment\": \"staging\"}, # Example custom labels\n    # group_unhandled_paths=True # New in v0.23.0 to group 404s under '__unknown__'\n)\n\n# To run this application:\n# 1. Save the code as `main.py`\n# 2. Install dependencies: `pip install uvicorn starlette starlette-exporter prometheus_client`\n# 3. Run: `uvicorn main:app --reload`\n# Then, access metrics at http://127.0.0.1:8000/metrics\n# And application routes at http://127.0.0.1:8000/ or http://127.0.0.1:8000/users/alice","lang":"python","description":"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."},"warnings":[{"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.","message":"The default values for `group_paths` and `filter_unhandled_paths` changed from `False` to `True`.","severity":"breaking","affected_versions":">=0.18.0"},{"fix":"Ensure your project uses Starlette 0.35.0 or newer and Python 3.8 or newer. Upgrade your environment and dependencies accordingly.","message":"Minimum supported Starlette version increased to 0.35, and Python 3.7 support was dropped.","severity":"breaking","affected_versions":">=0.18.0"},{"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).","message":"The `skip_paths` option now accepts regular expressions, which can subtly change behavior if existing exact path strings were coincidentally valid regex patterns.","severity":"gotcha","affected_versions":">=0.20.0"},{"fix":"Update any monitoring alerts or dashboards that specifically look for `500` status codes for client disconnections to include `499`.","message":"Client disconnections (before a response is sent) are now reported with status code `499` instead of `500`.","severity":"gotcha","affected_versions":">=0.17.0"},{"fix":"To get metrics for requests against unhandled paths, set `group_unhandled_paths=True` in the `PrometheusMiddleware` constructor. This option overrides `filter_unhandled_paths`.","message":"Unhandled paths (404s) can now be grouped under a special `__unknown__` label, but this feature requires explicit enablement.","severity":"gotcha","affected_versions":">=0.23.0"}],"env_vars":null,"search_vec":"'/metrics':38 '0.23.0':44 'applic':19 'automat':35 'cadenc':51 'current':41 'durat':26 'easi':21 'enabl':20 'endpoint':39 'export':3,8 'expos':36 'fastapi':62 'featur':54 'follow':47 'improv':56 'integr':31 'librari':12 'metric':2,16,59 'middlewar':34,61 'monitor':22,60 'new':53 'prometheus':1,15,58 'provid':14 'python':11 'rate':25 'regular':49 'releas':50 'request':24 'respons':28 'starlett':5,7,18,57 'starlette-export':6 'status':29 'version':42","created_at":"2026-04-11T17:46:00.031163+00:00","updated_at":"2026-04-17T14:37:24.919865+00:00","problems":[{"fix":"pip install starlette-exporter","cause":"The 'starlette_exporter' package is not installed in the Python environment.","error":"ModuleNotFoundError: No module named 'starlette_exporter'"},{"fix":"pip install fastapi==0.89.1 starlette==0.22.0","cause":"Version incompatibility between FastAPI and Starlette.","error":"AttributeError: 'FastAPI' object has no attribute '_debug'"},{"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)`.","cause":"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.","error":"AttributeError: 'Mount' object has no attribute '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.","cause":"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.","error":"starlette-exporter metrics not showing /metrics endpoint empty"},{"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.","cause":"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.","error":"starlette_request_duration_seconds_bucket showing wrong data with BackgroundTasks"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.24.0","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/stephenhillier/starlette_exporter","docs":null,"changelog":null,"pypi":"https://pypi.org/project/starlette-exporter/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["observability","web-framework"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-29","next_check":"2026-07-28","install_tag":null}}