DEV Community

Alex Spinov
Alex Spinov

Posted on

Grafana Has a Free API — Here's How to Build Custom Dashboards Programmatically

Last year a DevOps engineer I know was manually creating 47 Grafana dashboards for each new microservice. Copy-paste, change the service name, repeat. Every. Single. Time.

Then he discovered Grafana's HTTP API. Now a single script creates all 47 dashboards in under 10 seconds.

What Grafana's API Offers for Free

Grafana (self-hosted or Cloud free tier) exposes a full REST API:

  • Dashboard CRUD — create, read, update, delete dashboards
  • Data source management — add Prometheus, InfluxDB, PostgreSQL
  • Alert management — create and manage alert rules
  • Organization & user management
  • Annotations — mark events on graphs
  • Folder management — organize dashboards

Authentication

# Option 1: API Key (Grafana > Configuration > API Keys)
export GRAFANA_URL='http://localhost:3000'
export GRAFANA_API_KEY='your-api-key-here'

# Option 2: Basic auth
curl -u admin:admin $GRAFANA_URL/api/org
Enter fullscreen mode Exit fullscreen mode

Create a Dashboard Programmatically

curl -X POST $GRAFANA_URL/api/dashboards/db \
  -H "Authorization: Bearer $GRAFANA_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "dashboard": {
      "title": "API Latency Monitor",
      "panels": [{
        "title": "Request Duration",
        "type": "timeseries",
        "datasource": "Prometheus",
        "targets": [{
          "expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))",
          "legendFormat": "p95 latency"
        }],
        "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}
      }],
      "refresh": "10s"
    },
    "overwrite": false
  }'
Enter fullscreen mode Exit fullscreen mode

Generate Dashboards from Config (Node.js)

const axios = require('axios');

const grafana = axios.create({
  baseURL: process.env.GRAFANA_URL,
  headers: { 'Authorization': `Bearer ${process.env.GRAFANA_API_KEY}` }
});

async function createServiceDashboard(serviceName) {
  const dashboard = {
    dashboard: {
      title: `${serviceName} — Overview`,
      panels: [
        {
          title: 'Request Rate',
          type: 'timeseries',
          datasource: 'Prometheus',
          targets: [{ expr: `rate(http_requests_total{service="${serviceName}"}[5m])` }],
          gridPos: { h: 8, w: 12, x: 0, y: 0 }
        },
        {
          title: 'Error Rate',
          type: 'stat',
          datasource: 'Prometheus',
          targets: [{ expr: `rate(http_errors_total{service="${serviceName}"}[5m])` }],
          gridPos: { h: 8, w: 12, x: 12, y: 0 }
        }
      ],
      tags: ['auto-generated', serviceName]
    },
    overwrite: true
  };

  const { data } = await grafana.post('/api/dashboards/db', dashboard);
  console.log(`Created: ${data.url}`);
}

// Generate dashboards for all services
const services = ['auth', 'users', 'orders', 'payments', 'inventory'];
services.forEach(createServiceDashboard);
Enter fullscreen mode Exit fullscreen mode

Manage Alerts via API

// Create an alert rule
async function createAlert(dashboardUid, panelId) {
  await grafana.post('/api/ruler/grafana/api/v1/rules/default', {
    name: 'High Error Rate',
    interval: '1m',
    rules: [{
      grafana_alert: {
        title: 'Error rate > 5%',
        condition: 'C',
        data: [{
          refId: 'A',
          datasourceUid: 'prometheus',
          model: { expr: 'rate(http_errors_total[5m]) > 0.05' }
        }]
      }
    }]
  });
}
Enter fullscreen mode Exit fullscreen mode

Practical Automation Ideas

  1. CI/CD Integration: Auto-create dashboard when deploying new service
  2. Incident Annotations: Mark deployments on graphs via API
  3. Dashboard-as-Code: Store dashboard JSON in Git, deploy via API
  4. Multi-tenant Monitoring: Generate per-customer dashboards
  5. Automated Reports: Export dashboard snapshots via API

Need to collect monitoring data from websites or APIs? Check out my web scraping actors on Apify — automated data collection for any site. No coding needed.

Need a custom monitoring pipeline? Email me at spinov001@gmail.com — I build data collection and observability solutions.

Top comments (0)