Prometheus FastAPI Instrumentator

7.1.0 · active · verified Thu Apr 09

This library provides a straightforward way to instrument your FastAPI or Starlette applications with Prometheus metrics. It automatically exposes common HTTP request metrics and allows for custom metric definitions. Currently at version 7.1.0, it maintains an active development pace with frequent updates and bug fixes, typically releasing minor versions every few months and major versions annually.

Warnings

Install

Imports

Quickstart

This quickstart initializes a FastAPI app, instruments it with default Prometheus metrics on startup, and exposes a `/metrics` endpoint. Run `python your_app.py` and navigate to `http://localhost:8000/metrics` to see the metrics. It also includes comments on important considerations for multiprocessing.

from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator
import uvicorn
import os

app = FastAPI()

# Best practice: Instrument the app on startup
@app.on_event("startup")
async def startup_event():
    Instrumentator().instrument(app).expose(app)
    print("Prometheus metrics exposed at /metrics")

@app.get("/")
async def read_root():
    return {"message": "Hello Prometheus!"}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id, "message": "An item"}

if __name__ == "__main__":
    # For multiprocessing environments (e.g., Gunicorn with multiple workers),
    # PROMETHEUS_MULTIPROC_DIR must be set to a shared writable directory.
    # Example: os.environ["PROMETHEUS_MULTIPROC_DIR"] = "/tmp/prom_data"
    uvicorn.run(app, host="0.0.0.0", port=8000)

view raw JSON →