prometheus_client library.
Minimal Flask app
Here is a minimal Flask app that exposes a single GET endpoint at"/cars":
@app.get("/cars"): any GET request to "/cars" will execute the get_cars function. The app is started on port 5001.
Install the Prometheus client
Install the Python client library:Add a Counter metric
Import and create a PrometheusCounter to track total requests:
Increment the counter in a handler
Increment the counter inside the request handler so it increases on every request:Expose metrics with a separate HTTP server
The simplest way to expose metrics is to usestart_http_server from the Prometheus client. This starts a separate HTTP server that serves all registered metrics (including the default Python metrics):
- Flask App: port
5001 - Prometheus metrics endpoint: port
8000
Expose metrics via Flask (same port)
If you prefer to expose metrics on the same port as your Flask app (e.g., athttp://localhost:5001/metrics), use the WSGI helper make_wsgi_app and DispatcherMiddleware from werkzeug:
http://localhost:5001/metrics. Use whichever approach fits your deployment model: a separate metrics server (good for simple setups) or WSGI middleware (keeps everything on one port).
Multi-route application and counting across all endpoints
Let’s expand the app with additional endpoints and show two ways to ensurehttp_requests_total counts requests across your entire application.
- Manual increments in each handler:
- Increment once for every incoming request using a global hook (recommended to avoid repeating increments). If you expose metrics at
"/metrics"via the same Flask app (for example, if/metricsis handled by Flask), make sure you do not count requests to/metricsitself. If you mount the Prometheus WSGI app viaDispatcherMiddleware, requests to/metricsare handled by the metrics WSGI app and won’t trigger Flaskbefore_requesthooks:
Callouts
If you use
start_http_server, the metrics endpoint is a separate HTTP server (different port) and will not be handled by Flask middleware or Flask hooks like before_request. If you want metrics to be part of the same Flask process and port, use make_wsgi_app with DispatcherMiddleware.If you expose metrics at
"/metrics" on the same Flask app, ensure you do not inadvertently count /metrics requests in your application metrics unless that is intentional.Summary
- Create and register Prometheus metrics (e.g.,
Counter,Gauge,Histogram) usingprometheus_client. - Increment metrics where appropriate (inside handlers, or globally via
before_request). - Expose metrics either with
start_http_server(separate port) or withmake_wsgi_app+DispatcherMiddleware(same port at"/metrics"). - Avoid double-counting metrics (for example, counting scrapes of the
/metricsendpoint itself).