DEV Community

Alex Spinov
Alex Spinov

Posted on

Grafana Has a Free API — Build Dashboards and Query Metrics Programmatically

Grafana Cloud Free Tier Is Generous

Grafana Cloud gives you free monitoring with 10K metrics, 50GB logs, and 50GB traces. Their API lets you manage dashboards and query data programmatically.

Setup

Get your API key from grafana.com/orgs/YOUR_ORG/api-keys.

import requests

GRAFANA_URL = "https://your-org.grafana.net"
API_KEY = "your_grafana_api_key"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
Enter fullscreen mode Exit fullscreen mode

List Dashboards

def list_dashboards():
    r = requests.get(f"{GRAFANA_URL}/api/search", headers=HEADERS,
                     params={"type": "dash-db"})
    return [{"title": d["title"], "uid": d["uid"], "url": d["url"]}
            for d in r.json()]

for d in list_dashboards():
    print(f"{d[title]}{d[uid]}")
Enter fullscreen mode Exit fullscreen mode

Create a Dashboard

def create_dashboard(title, panels):
    dashboard = {
        "dashboard": {
            "title": title,
            "panels": panels,
            "timezone": "browser"
        },
        "overwrite": False
    }
    r = requests.post(f"{GRAFANA_URL}/api/dashboards/db",
                      headers=HEADERS, json=dashboard)
    return r.json()

# Create a simple panel
panels = [{
    "title": "CPU Usage",
    "type": "timeseries",
    "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
    "targets": [{"expr": "rate(process_cpu_seconds_total[5m])"}]
}]

create_dashboard("My Server Dashboard", panels)
Enter fullscreen mode Exit fullscreen mode

Query Prometheus Data

def query_prometheus(query, start=None, end=None):
    params = {"query": query}
    r = requests.get(f"{GRAFANA_URL}/api/datasources/proxy/1/api/v1/query",
                     headers=HEADERS, params=params)
    return r.json()["data"]["result"]

# Get current CPU usage
result = query_prometheus("rate(process_cpu_seconds_total[5m])")
for r in result:
    print(f"{r[metric]}: {r[value][1]}")
Enter fullscreen mode Exit fullscreen mode

Create Alerts

def create_alert_rule(name, query, threshold):
    rule = {
        "name": name,
        "condition": "gt",
        "threshold": threshold,
        "query": query,
        "for": "5m"
    }
    # Simplified - actual API is more complex
    r = requests.post(f"{GRAFANA_URL}/api/ruler/grafana/api/v1/rules/default",
                      headers=HEADERS, json=rule)
    return r.json()
Enter fullscreen mode Exit fullscreen mode

Real Use Cases

  1. Auto-generate dashboards for new services
  2. Export/import dashboards between environments
  3. Set up alerts programmatically during deployment
  4. Build custom monitoring UIs on top of Grafana data
  5. Scheduled reports — query metrics and send to Slack/email

Free Tier Limits

  • 10,000 Prometheus metrics
  • 50GB logs, 50GB traces
  • 3 users, 10 dashboards
  • 14-day retention

Enough for small to medium projects.


More | GitHub


More from me: 10 Dev Tools I Use Daily | 77 Scrapers on a Schedule | 150+ Free APIs

Top comments (0)