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.
- Log in to your Grafana instance
- Go to Configuration → API Keys
- Click Add API key
- Provide a name, select a role (Admin, Editor, or Viewer), and set an expiration time
- Click Add
Once created, you'll receive an API key that you can use to authenticate your requests:
# 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:
# 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:
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 resourcesPOST
: Create resourcesPUT
: Update resourcesDELETE
: 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:
Endpoint | Description |
---|---|
/dashboards/uid/:uid | Work with dashboards |
/datasources | Manage data sources |
/users | User management |
/orgs | Organization management |
/alerts | Alert management |
/annotations | Work with annotations |
Example: Working with Dashboards
Let's look at some practical examples of using the API to work with dashboards.
Getting Dashboard Information
# Get dashboard by UID
curl -X GET -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
https://your-grafana-instance/api/dashboards/uid/cIBgcSjkk
Response:
{
"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:
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:
{
"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:
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:
curl -X DELETE -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
https://your-grafana-instance/api/dashboards/uid/QFluk7nMk
Response:
{
"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
curl -X GET -H "Authorization: Bearer eyJrIjoiT0tTcG..." \
https://your-grafana-instance/api/datasources
Response:
[
{
"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
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:
{
"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:
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:
- Rate Limits: Some Grafana instances may implement rate limiting to prevent API abuse.
- Performance Impact: Large operations like importing many dashboards can impact Grafana's performance.
- API Changes: The API may change between Grafana versions, so check the documentation for your specific version.
- 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
- Create a script that backs up all your Grafana dashboards to a Git repository daily.
- Write a program that creates a set of identical dashboards for different environments (dev, test, prod) with environment-specific variables.
- Build a simple web form that allows non-technical users to create basic Grafana dashboards using the API.
- Create a script that syncs user permissions between two separate Grafana instances.
- 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! :)