Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Administration and Provisioning

Dashboards as Code: The Grafana JSON Model, API and Generators

Understand the Grafana dashboard JSON model (uid, panels, gridPos, targets, templating), export and import, the HTTP API, and generate and lint dashboards with code.

Behind every dashboard is a JSON document. Once you can read and write it, you can review dashboards in pull requests, generate fifty similar ones from a loop, copy a panel between instances and fix mistakes the UI makes awkward. This lesson explains the JSON model, the export and import flow, the HTTP API, and tools that generate dashboards from code.

Grafana is not available on this site, so JSON is shown as read-only text and API calls as command examples (never fabricated responses). The runnable blocks are Python stand-ins that generate and lint dashboard JSON, so you can practice the structure.

Getting the JSON

Open a dashboard, go to Settings > JSON Model to see and edit it, or use Export > Export as JSON to copy or download it. The export dialog has an Export for sharing externally switch that replaces data source UIDs with ${DS_NAME} placeholders (stored in an __inputs section) so the importer is asked to choose its own data source. Import with Dashboards > New > Import: paste JSON, upload a file or enter a grafana.com dashboard ID.

The model

A trimmed dashboard looks like this:

JSON
{
  "uid": "svc-health",
  "title": "Service health",
  "tags": ["production", "red"],
  "timezone": "utc",
  "schemaVersion": 39,
  "version": 3,
  "refresh": "30s",
  "time": { "from": "now-6h", "to": "now" },
  "templating": {
    "list": [
      { "name": "service", "type": "query", "multi": true, "includeAll": true,
        "datasource": { "type": "prometheus", "uid": "prom-main" },
        "query": "label_values(http_requests_total, service)" }
    ]
  },
  "annotations": { "list": [] },
  "panels": [
    {
      "id": 1,
      "type": "timeseries",
      "title": "Request rate",
      "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 },
      "datasource": { "type": "prometheus", "uid": "prom-main" },
      "targets": [
        { "refId": "A",
          "expr": "sum by (service) (rate(http_requests_total{service=~\"$service\"}[$__rate_interval]))",
          "legendFormat": "{{service}}" }
      ],
      "fieldConfig": { "defaults": { "unit": "reqps" }, "overrides": [] },
      "transformations": []
    }
  ]
}

The important fields:

  • uid: the stable identifier used in URLs (/d/svc-health/...) and for provisioning. Choose a readable one.
  • id: a database number that is null when creating; do not hard-code it in files meant for provisioning.
  • version: incremented by every save; the API uses it to detect conflicts.
  • schemaVersion: the format version of the JSON. Grafana migrates older dashboards forward when it loads them.
  • templating.list: the variables.
  • panels: the list of panels; each has id (unique in the dashboard), type, title, gridPos, datasource, targets (the queries), fieldConfig (units, thresholds, mappings, overrides), options (visualization-specific), transformations. Rows are panels of type row with their own nested panels when collapsed.
  • time, refresh, timezone: the defaults discussed in time ranges.

The targets structure depends on the data source type: Prometheus uses expr, SQL uses rawSql and format, Loki uses expr too with queryType. When unsure, build the panel in the UI and read its JSON.

Newer Grafana versions are also introducing a Kubernetes-style dashboard resource format (apiVersion and spec), and a v2 dashboard schema; the classic JSON above remains widely supported, so check the documentation of your version before generating files at scale.

The HTTP API

Everything in the UI is available over HTTP. With a service account token in $TOKEN:

Terminal
# Save (create or update) a dashboard
curl -X POST http://localhost:3000/api/dashboards/db \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"dashboard": {...}, "folderUid": "team", "overwrite": true, "message": "CI deploy"}'

# Read one by uid
curl -H "Authorization: Bearer $TOKEN" http://localhost:3000/api/dashboards/uid/svc-health

# Search
curl -H "Authorization: Bearer $TOKEN" "http://localhost:3000/api/search?query=service&type=dash-db"

# Health check (no auth needed)
curl http://localhost:3000/api/health

The save body wraps the dashboard JSON with options: folderUid, overwrite (replace even if the version differs), and a commit-style message. Other useful endpoints: /api/folders, /api/datasources, /api/annotations (create an annotation from a deploy script), /api/teams, /api/serviceaccounts and the alerting provisioning API under /api/v1/provisioning.

Generating dashboards

Typing JSON by hand does not scale. Options:

  • Scripts (Python, TypeScript...) that build dictionaries and write JSON files.
  • Grafonnet (Jsonnet library) and the Grafana Foundation SDK (typed builders in several languages) for declarative dashboards.
  • Terraform grafana_dashboard resources fed with file() or jsonencode().
  • Templates: one function service_dashboard(name) creates a dashboard for every microservice.

Whatever you choose, commit the generated JSON or the generator, and deploy through provisioning or the API.

Python Stand-in: generate dashboard JSON with code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Linting dashboards

Before deploying, check basic rules automatically. A good lint run catches duplicate panel IDs, overlapping gridPos, missing datasource, missing titles and a missing uid.

Python Stand-in: lint a dashboard model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Workflow tips

  • Keep the uid in the file and treat it as permanent.
  • Do not commit id and bump version only through the API; set overwrite carefully.
  • Review dashboards as JSON diffs; in large diffs, a tool that normalizes key order and strips volatile fields (version, iteration) helps.
  • Export with "for sharing externally" only for sharing; for your own environments, keep fixed data source UIDs so provisioned dashboards need no inputs.
  • Prefer provisioning with allowUiUpdates: false plus a "Save as copy" habit, so experiments happen in a scratch folder.
flowchart LR
    UI["Build in the UI"] --> J["Export JSON"]
    J --> G["Git review"]
    G --> L["Lint in CI"]
    L --> P["Provision / API deploy"]
    P --> R["Running dashboard"]

A common path: prototype in the UI, then manage the JSON like code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which field gives a dashboard a stable identity for URLs and provisioning?

    The uid is the permanent identifier; id is an internal database number.
  2. 2. What does the gridPos of a panel describe?

    gridPos holds x, y, w and h in grid units.
  3. 3. What does Export for sharing externally do?

    It adds an __inputs section with placeholders for data sources and other values.
  4. 4. Which API endpoint creates or updates a dashboard?

    POST /api/dashboards/db saves a dashboard from a body with dashboard, folderUid and overwrite.

Summary

  • A dashboard is a JSON document with uid, panels (each with gridPos, targets, fieldConfig), templating, time and more.
  • Export and import move JSON between instances; "for sharing externally" adds data source inputs.
  • The HTTP API (POST /api/dashboards/db, search, folders, annotations) automates everything with a service account token.
  • Generate dashboards with scripts, Grafonnet, the Foundation SDK or Terraform, and lint them in CI.
  • Keep stable uids, avoid committing id, and deploy through provisioning or the API.

Next: Project: A Service Health Dashboard