Grafana Client

5.0.2 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Grafana instance using either an API token or HTTP Basic Authentication. It then retrieves the Grafana version and lists existing dashboards. Ensure `GRAFANA_URL` and `GRAFANA_TOKEN` environment variables are set. For API token, `GRAFANA_TOKEN` should be the token itself. For basic auth, it should be in `username:password` format.

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.")

view raw JSON →