API Tokens
Introduction
API tokens in Grafana provide a secure way to authenticate automated systems and external applications that need to interact with your Grafana instance. Rather than sharing user credentials, API tokens offer a dedicated, revocable method for programmatic access to Grafana's HTTP API.
In this guide, you'll learn how to create, manage, and use API tokens to unlock powerful automation capabilities and integrate Grafana with your existing workflows and tools.
What Are API Tokens?
API tokens are special keys that grant specific levels of access to Grafana's HTTP API. They serve as an alternative to username/password authentication when you need to:
- Automate dashboard creation or updates
- Pull metrics or alerts programmatically
- Integrate Grafana with CI/CD pipelines
- Connect external systems to your Grafana instance
Types of API Tokens in Grafana
Grafana offers different types of API tokens depending on your needs:
- Service Account Tokens (Recommended): Associated with service accounts rather than users.
- API Keys (Legacy): Traditional API keys with specific roles.
Service Account Tokens
Service accounts were introduced to provide better security and management of machine-to-machine authentication. They're the recommended approach for API access.
Creating a Service Account Token
Let's create a service account and generate a token:
- Navigate to Administration → Service Accounts in your Grafana UI
- Click + Add service account
- Fill in the details:
- Name:
my-automation
- Role: Select appropriate role (e.g.,
Editor
for dashboard management)
- Name:
- Click Create
- From the service account page, click Add token
- Set a name and expiration:
- Name:
automation-token
- Expiration: Choose an expiration period (e.g., 30 days)
- Name:
- Click Generate token
- IMPORTANT: Copy the token immediately! It will only be shown once.
Here's what the token creation screen looks like:
Name: automation-token
Expiration: 30 days
[Cancel] [Generate token]
After generation, you'll see a confirmation with your token:
Your service account token has been generated.
Make sure to copy your service account token now. You won't be able to see it again.
eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk...
[Copy to clipboard]
Using API Tokens in Requests
Once you have your token, you can use it in HTTP requests to the Grafana API. Here's how to include it:
Using curl
curl -H "Authorization: Bearer eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk..." \
https://your-grafana-instance.com/api/dashboards/home
Using JavaScript/Fetch
const apiToken = 'eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk...';
fetch('https://your-grafana-instance.com/api/dashboards/home', {
headers: {
'Authorization': `Bearer ${apiToken}`
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Using Python/Requests
import requests
api_token = 'eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk...'
headers = {
'Authorization': f'Bearer {api_token}'
}
response = requests.get(
'https://your-grafana-instance.com/api/dashboards/home',
headers=headers
)
print(response.json())
Practical Examples
Let's explore some real-world applications of API tokens in Grafana.
Example 1: Creating a Dashboard Programmatically
You can use the API to create dashboards automatically:
import requests
import json
api_token = 'eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk...'
grafana_url = 'https://your-grafana-instance.com'
# Dashboard JSON definition
dashboard = {
"dashboard": {
"id": None,
"title": "API Created Dashboard",
"tags": ["automated", "api-created"],
"timezone": "browser",
"panels": [
{
"id": 1,
"title": "API Panel",
"type": "graph",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}
}
],
"schemaVersion": 27,
"version": 0
},
"folderId": 0,
"overwrite": False
}
headers = {
'Authorization': f'Bearer {api_token}',
'Content-Type': 'application/json'
}
response = requests.post(
f'{grafana_url}/api/dashboards/db',
headers=headers,
data=json.dumps(dashboard)
)
print(response.json())
Example 2: Setting Up Automated Health Checks
You can create a script that regularly checks your Grafana health status:
import requests
import time
import smtplib
from email.message import EmailMessage
api_token = 'eyJrIjoiT0tTcG1pUlY2RnVKZTFVaDFsNFZXdE9ZWmNrMkZYbk...'
grafana_url = 'https://your-grafana-instance.com'
headers = {
'Authorization': f'Bearer {api_token}'
}
def check_health():
try:
response = requests.get(f'{grafana_url}/api/health', headers=headers)
return response.status_code == 200
except Exception:
return False
def send_alert(message):
# Configure your email sending logic here
email = EmailMessage()
email['Subject'] = 'Grafana Health Alert'
email['From'] = '[email protected]'
email['To'] = '[email protected]'
email.set_content(message)
# Send email (simplified)
with smtplib.SMTP('smtp.example.com', 587) as server:
server.send_message(email)
# Main monitoring loop
while True:
if not check_health():
send_alert("Grafana instance is not responding!")
time.sleep(300) # Check every 5 minutes
Managing API Tokens
Proper token management is essential for security:
View Existing Tokens
Navigate to Administration → Service Accounts, select your service account, and click the Tokens tab to see all active tokens.
Revoking Tokens
If a token is compromised or no longer needed:
- Go to Administration → Service Accounts
- Select the service account
- Click the Tokens tab
- Find the token you want to revoke
- Click the trash icon to revoke it
Best Practices for Token Security
- Use short-lived tokens: Set appropriate expiration dates
- Apply least privilege principle: Grant only necessary permissions
- Rotate tokens regularly: Create new tokens and revoke old ones
- Monitor token usage: Check audit logs for unusual activity
- Never commit tokens to version control: Use environment variables or secrets management
Troubleshooting API Token Issues
Common issues and their solutions:
"Unauthorized" Errors
If you're receiving 401 Unauthorized errors:
- Verify the token hasn't expired
- Ensure you're using the correct format:
Bearer <token>
- Check if the token has been revoked
- Confirm the service account has appropriate permissions
Rate Limiting
Grafana implements rate limiting to prevent API abuse. If you're hitting limits:
- Reduce the frequency of API calls
- Implement backoff strategies in your code
- Contact your Grafana administrator to adjust limits if necessary
Summary
API tokens are a powerful feature of Grafana that enable secure automation and integration with external systems. By using service account tokens, you can grant programmatic access to Grafana's API without compromising security.
In this guide, you've learned:
- What API tokens are and when to use them
- How to create service account tokens
- How to use tokens in API requests with different programming languages
- Real-world examples of Grafana API automation
- Best practices for token management and security
With this knowledge, you can now integrate Grafana into your automation workflows, build custom applications that interact with your dashboards and data, and enhance your monitoring infrastructure.
Additional Resources
Exercise
Try these exercises to reinforce your learning:
- Create a service account with viewer permissions and use its token to fetch a list of dashboards
- Write a script that exports all your dashboards as JSON files for backup purposes
- Build a simple application that displays key metrics from Grafana using the API
- Create a CI/CD pipeline that automatically updates a dashboard when your code changes
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)