Skip to main content

Grafana API Basics

Introduction

Grafana is a popular open-source platform for monitoring and observability that allows you to query, visualize, and alert on your metrics no matter where they're stored. While the Grafana UI provides a rich interface for creating dashboards and visualizations, there are times when you need to automate tasks or integrate Grafana with other systems.

This is where the Grafana HTTP API comes in. The API allows you to:

  • Create, update, and delete dashboards programmatically
  • Manage users, teams, and permissions
  • Configure data sources and alerts
  • Export and import dashboards
  • Automate repetitive tasks

In this guide, we'll explore the fundamentals of working with the Grafana API, including authentication, making requests, and common use cases.

API Authentication

Before making any API requests, you need to authenticate. Grafana supports several authentication methods for its API:

API Keys

API keys are the simplest way to authenticate with the Grafana API.

  1. Log in to your Grafana instance
  2. Go to ConfigurationAPI Keys
  3. Click Add API key
  4. Provide a name, select a role (Admin, Editor, or Viewer), and set an expiration time
  5. Click Add

Once created, you'll receive an API key that you can use to authenticate your requests:

bash
# Example API key request
curl -X GET -H "Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk" \
https://your-grafana-instance/api/dashboards/home

Bearer Tokens

If you're using Grafana's built-in authentication, you can also use your login session token:

bash
# Authenticate and get a token
curl -X POST -H "Content-Type: application/json" \
-d '{"user":"admin","password":"admin"}' \
https://your-grafana-instance/login

# Use the returned token in subsequent requests
curl -X GET -H "Authorization: Bearer xQD..." \
https://your-grafana-instance/api/dashboards/home

Basic Authentication

For simple scenarios, you can also use HTTP Basic Authentication:

bash
curl -X GET -u admin:admin \
https://your-grafana-instance/api/dashboards/home

Making API Requests

The Grafana API follows REST principles, using standard HTTP methods:

  • GET: Retrieve resources
  • POST: Create resources
  • PUT: Update resources
  • DELETE: Remove resources

All API responses are returned in JSON format.

API Base URL

The base URL for API requests is your Grafana instance URL followed by /api:

https://your-grafana-instance/api

Common Endpoints

Here are some commonly used API endpoints:

EndpointDescription
/dashboards/uid/:uidWork with dashboards
/datasourcesManage data sources
/usersUser management
/orgsOrganization management
/alertsAlert management
/annotationsWork with annotations

Example: Working with Dashboards

Let's look at some practical examples of using the API to work with dashboards.

Getting Dashboard Information

bash
# Get dashboard by UID
curl -X GET -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
https://your-grafana-instance/api/dashboards/uid/cIBgcSjkk

Response:

json
{
"dashboard": {
"id": 1,
"uid": "cIBgcSjkk",
"title": "Production Overview",
"tags": ["production", "metrics"],
"timezone": "browser",
"schemaVersion": 16,
"version": 1,
"panels": [
// Panel objects...
]
},
"meta": {
"isStarred": false,
"url": "/d/cIBgcSjkk/production-overview",
"folderId": 0,
"folderUid": "",
"folderTitle": "General",
"folderUrl": "",
"provisioned": false,
"provisionedExternalId": ""
}
}

Creating a Dashboard

To create a new dashboard, you need to send a POST request with the dashboard definition:

bash
curl -X POST -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
-H "Content-Type: application/json" \
-d '{
"dashboard": {
"id": null,
"title": "API Created Dashboard",
"tags": ["api", "example"],
"timezone": "browser",
"panels": [
{
"id": 1,
"type": "graph",
"title": "API Created Panel",
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
}
}
],
"schemaVersion": 16,
"version": 0
},
"folderId": 0,
"overwrite": false
}' \
https://your-grafana-instance/api/dashboards/db

Response:

json
{
"id": 2,
"uid": "QFluk7nMk",
"url": "/d/QFluk7nMk/api-created-dashboard",
"status": "success",
"version": 1
}

Updating a Dashboard

Updating a dashboard is similar to creating one, but you need to include the dashboard's id and uid properties, and increment the version number:

bash
curl -X POST -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
-H "Content-Type: application/json" \
-d '{
"dashboard": {
"id": 2,
"uid": "QFluk7nMk",
"title": "Updated Dashboard Title",
"tags": ["api", "example", "updated"],
"timezone": "browser",
"panels": [
// Panel objects...
],
"schemaVersion": 16,
"version": 1
},
"folderId": 0,
"overwrite": true
}' \
https://your-grafana-instance/api/dashboards/db

Deleting a Dashboard

To delete a dashboard, you need its UID:

bash
curl -X DELETE -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
https://your-grafana-instance/api/dashboards/uid/QFluk7nMk

Response:

json
{
"title": "Updated Dashboard Title",
"message": "Dashboard Updated Dashboard Title deleted",
"id": 2
}

Data Source Management

Another common use case for the Grafana API is managing data sources.

Listing Data Sources

bash
curl -X GET -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
https://your-grafana-instance/api/datasources

Response:

json
[
{
"id": 1,
"orgId": 1,
"name": "Prometheus",
"type": "prometheus",
"typeLogoUrl": "",
"access": "proxy",
"url": "http://prometheus:9090",
"password": "",
"user": "",
"database": "",
"basicAuth": false,
"isDefault": true,
"jsonData": {},
"readOnly": false
}
]

Creating a Data Source

bash
curl -X POST -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
-H "Content-Type: application/json" \
-d '{
"name": "InfluxDB",
"type": "influxdb",
"url": "http://influxdb:8086",
"access": "proxy",
"basicAuth": false,
"isDefault": false,
"jsonData": {
"defaultBucket": "metrics",
"version": "Flux"
},
"secureJsonData": {
"token": "your-influxdb-token"
}
}' \
https://your-grafana-instance/api/datasources

Response:

json
{
"datasource": {
"id": 2,
"uid": "P20E37347BD83022D",
"orgId": 1,
"name": "InfluxDB",
"type": "influxdb",
"typeLogoUrl": "",
"access": "proxy",
"url": "http://influxdb:8086",
"password": "",
"user": "",
"database": "",
"basicAuth": false,
"isDefault": false,
"jsonData": {
"defaultBucket": "metrics",
"version": "Flux"
},
"readOnly": false
},
"id": 2,
"message": "Datasource added",
"name": "InfluxDB"
}

API Workflow Diagram

Here's a diagram showing a typical workflow when using the Grafana API:

Automating with Scripts

You can use the Grafana API to automate common tasks. Here's an example Python script that exports all dashboards to JSON files:

python
import requests
import json
import os

# Configuration
GRAFANA_URL = "https://your-grafana-instance"
API_KEY = "eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk"
EXPORT_DIR = "dashboard-exports"

# Ensure export directory exists
os.makedirs(EXPORT_DIR, exist_ok=True)

# Set up HTTP headers
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}

# Get list of all dashboards
search_response = requests.get(
f"{GRAFANA_URL}/api/search?query=&type=dash-db",
headers=headers
)
search_results = search_response.json()

# Export each dashboard
for dashboard in search_results:
uid = dashboard["uid"]
title = dashboard["title"]

print(f"Exporting dashboard: {title} (UID: {uid})")

# Get dashboard details
dashboard_response = requests.get(
f"{GRAFANA_URL}/api/dashboards/uid/{uid}",
headers=headers
)
dashboard_data = dashboard_response.json()

# Save to file
safe_title = title.replace(" ", "_").replace("/", "_")
filename = f"{EXPORT_DIR}/{safe_title}_{uid}.json"

with open(filename, "w") as f:
json.dump(dashboard_data, f, indent=2)

print(f" Saved to {filename}")

print(f"
Exported {len(search_results)} dashboards to {EXPORT_DIR}/")

Rate Limiting and API Considerations

When working with the Grafana API, be aware of:

  1. Rate Limits: Some Grafana instances may implement rate limiting to prevent API abuse.
  2. Performance Impact: Large operations like importing many dashboards can impact Grafana's performance.
  3. API Changes: The API may change between Grafana versions, so check the documentation for your specific version.
  4. Error Handling: Always implement proper error handling in your scripts.

Summary

In this guide, we've covered the fundamentals of working with the Grafana API:

  • Authentication methods (API keys, tokens, basic auth)
  • Making API requests (GET, POST, PUT, DELETE)
  • Working with dashboards (create, read, update, delete)
  • Managing data sources
  • Automating tasks with scripts

The Grafana API gives you powerful programmatic control over your Grafana instance, enabling automation, integration, and custom workflows beyond what's possible through the UI alone.

Additional Resources

Exercises

  1. Create a script that backs up all your Grafana dashboards to a Git repository daily.
  2. Write a program that creates a set of identical dashboards for different environments (dev, test, prod) with environment-specific variables.
  3. Build a simple web form that allows non-technical users to create basic Grafana dashboards using the API.
  4. Create a script that syncs user permissions between two separate Grafana instances.
  5. Implement a monitoring system that uses the Grafana API to automatically create alert rules based on your application metrics.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)