Tracking FastApi URL hit count over a period of time using Grafana and Prometheus
Setting up Grafana and Prometheus
Follow this link
Install dependencies using pip
pip install prometheus_client==0.20.0
pip install prometheus-fastapi-instrumentator==7.0.0
Now lets create a sample FastAPI server. Here is the main.py file
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Now lets add Prometheus client to it
from prometheus_fastapi_instrumentator import Instrumentator
from prometheus_client import Counter
Add Instrumentor to FastAPI app
instrumentator = Instrumentator().instrument(app)
@app.on_event("startup")
async def _startup():
instrumentator.expose(app)
Now lets see the whole file
from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator
from prometheus_client import Counter
import time
app = FastAPI()
instrumentator = Instrumentator().instrument(app)
@app.on_event("startup")
async def _startup():
instrumentator.expose(app)
REQUEST_COUNT = Counter(
'app_request_count',
'Application Request Count',
['method', 'endpoint', 'http_status']
)
@app.get("/")
async def root():
start_time = time.time()
REQUEST_COUNT.labels('GET', '/', 200).inc()
return {"message": "Hello World"}
This server will be running at port http://localhost:7070/
Now lets add this entry to prometheus.yml file
global:
scrape_interval: 5s
scrape_configs:
- job_name: 'app'
metrics_path: '/metrics'
static_configs:
- targets: ['localhost:7070']
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
remote_write:
- url: http://localhost:3000
basic_auth:
username: admin
password: admin
restart Prometheus server
Now open browser and hit http://localhost:7070/ muliple times. and goto Grafana dashboard
