| 1 | --- |
| 2 | title: FastAPI + Gunicorn |
| 3 | weight: 5 |
| 4 | --- |
| 5 | |
| 6 | To use Prometheus with [FastAPI](https://fastapi.tiangolo.com/) and [Gunicorn](https://gunicorn.org/) we need to serve metrics through a Prometheus ASGI application. |
| 7 | |
| 8 | Save the snippet below in a `myapp.py` file |
| 9 | |
| 10 | ```python |
| 11 | from fastapi import FastAPI |
| 12 | from prometheus_client import make_asgi_app |
| 13 | |
| 14 | # Create app |
| 15 | app = FastAPI(debug=False) |
| 16 | |
| 17 | # Add prometheus asgi middleware to route /metrics requests |
| 18 | metrics_app = make_asgi_app() |
| 19 | app.mount("/metrics", metrics_app) |
| 20 | ``` |
| 21 | |
| 22 | For Multiprocessing support, use this modified code snippet. Full multiprocessing instructions are provided [here]({{< ref "/multiprocess" >}}). |
| 23 | |
| 24 | ```python |
| 25 | from fastapi import FastAPI |
| 26 | from prometheus_client import make_asgi_app |
| 27 | |
| 28 | app = FastAPI(debug=False) |
| 29 | |
| 30 | # Using multiprocess collector for registry |
| 31 | def make_metrics_app(): |
| 32 | registry = CollectorRegistry() |
| 33 | multiprocess.MultiProcessCollector(registry) |
| 34 | return make_asgi_app(registry=registry) |
| 35 | |
| 36 | |
| 37 | metrics_app = make_metrics_app() |
| 38 | app.mount("/metrics", metrics_app) |
| 39 | ``` |
| 40 | |
| 41 | Run the example web application like this |
| 42 | |
| 43 | ```bash |
| 44 | # Install gunicorn if you do not have it |
| 45 | pip install gunicorn |
| 46 | # If using multiple workers, add `--workers n` parameter to the line below |
| 47 | gunicorn -b 127.0.0.1:8000 myapp:app -k uvicorn.workers.UvicornWorker |
| 48 | ``` |
| 49 | |
| 50 | Visit http://localhost:8000/metrics to see the metrics |