Grafana Client
A client library for accessing the Grafana HTTP API, written in Python. It covers most available Grafana HTTP API endpoints and supports Grafana 5.x-9.x, with ongoing compatibility for newer versions, including Grafana 11. The library is actively maintained with a regular release cadence, supporting HTTP Basic authentication and token-based authentication.
Common errors
-
Max retries exceeded with url: /api/datasources
cause This error typically indicates a network connectivity issue, an incorrect Grafana URL, or a firewall blocking access to the Grafana instance from where the Python script is run. It's not usually an API-level error.fixVerify that the `GRAFANA_URL` is correct and accessible from the machine running the script. Check network connectivity, firewall rules, and proxy settings. Ensure the Grafana instance is running and listening on the specified port. -
An unexpected error happened DetailsTypeError: Cannot read properties of undefined (reading 'usageBilling')
cause While the HTTP status code might be 200 OK, the actual response body from Grafana indicates an internal server-side error, often related to Grafana Cloud billing or a similar service-specific issue that prevents the operation from completing.fixAlways inspect the `response.text` or content even on 200 OK status for Grafana-specific error messages. In this particular case, contact Grafana Cloud support or check your Grafana instance's billing and service status. -
NameError: name 'requests' is not defined (or similar import error for 'requests.exceptions.Timeout')
cause Since version 4.0.0, `grafana-client` no longer directly uses the `requests` library for its HTTP backend. Code that relies on importing `requests` or catching `requests.exceptions.Timeout` will fail.fixRemove direct `import requests` if it's only for `grafana-client` operations. Update exception handling for timeouts to catch `grafana_client.errors.GrafanaTimeoutError` instead of `requests.exceptions.Timeout`. If you need `requests` for other purposes, import it explicitly.
Warnings
- breaking Version 5.0.0 introduced a breaking change: authentication is now *obligatory* for all API calls, as the library fetches the Grafana version from `/api/frontend/settings` instead of `/api/health`. The `/api/health` endpoint previously allowed unauthenticated access. Additionally, the 'database' status is no longer represented in the response.
- breaking Version 4.0.0 changed the underlying HTTP backend from `requests` to `niquests`. This primarily affects error handling, as `requests.exceptions.Timeout` exceptions are no longer propagated. Instead, `GrafanaTimeoutError` is used. Python 3.6 support was also dropped.
- gotcha Insufficient Grafana API Key Permissions: A common issue is providing an API key with inadequate permissions for the desired operations (e.g., a Viewer key trying to create dashboards). While the API might return a 200 OK, the operation may silently fail or return an empty result.
- gotcha Grafana Organization Context with HTTP Basic Authentication: When using HTTP Basic Authentication, requests are made within the authenticated user's current organization context. This might lead to unexpected behavior if the user is part of multiple organizations and the desired organization is not active. API tokens are typically bound to a single organization.
Install
-
pip install --upgrade grafana-client
Imports
- GrafanaApi
from grafana_client import GrafanaApi
- AsyncGrafanaApi
from grafana_client import AsyncGrafanaApi
- GrafanaAPI
from grafana_api.grafana_api import GrafanaAPI
from grafana_client import GrafanaApi
Quickstart
import os
from grafana_client import GrafanaApi
GRAFANA_URL = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
GRAFANA_TOKEN = os.environ.get('GRAFANA_TOKEN', 'eyJrIjoiV1N...') # Or 'admin:admin' for basic auth
# For API token authentication
# grafana = GrafanaApi.from_url(f"{GRAFANA_URL}", token=GRAFANA_TOKEN)
# For basic authentication (e.g., admin user)
username, password = GRAFANA_TOKEN.split(':', 1) if ':' in GRAFANA_TOKEN else ('', '')
if not username or not password:
print("Warning: GRAFANA_TOKEN env var not set correctly for basic auth (e.g., 'admin:admin').")
print("Trying with API token instead.")
grafana = GrafanaApi.from_url(GRAFANA_URL, token=GRAFANA_TOKEN)
else:
grafana = GrafanaApi.from_url(GRAFANA_URL, basic_auth=(username, password))
try:
# Get Grafana's current version (requires authentication since 5.0.0)
version_info = grafana.version()
print(f"Connected to Grafana version: {version_info.get('version')}")
# Example: List all dashboards
dashboards = grafana.search.search_dashboards()
print(f"Found {len(dashboards)} dashboards.")
if dashboards:
print(f"First dashboard title: {dashboards[0].get('title')}")
except Exception as e:
print(f"An error occurred: {e}")
print("Ensure GRAFANA_URL and GRAFANA_TOKEN are correctly set.")