A client library for accessing the Grafana HTTP API, written in Python
—
Authentication classes and methods for secure access to the Grafana API. The grafana-client supports multiple authentication mechanisms including API tokens, custom headers, and basic authentication to accommodate different Grafana deployment scenarios and security requirements.
Bearer token authentication using Grafana API tokens for secure API access. This is the recommended authentication method for production use.
class TokenAuth:
"""
Bearer token authentication for Grafana API.
Args:
token (str): Grafana API token
"""
def __init__(self, token: str): ...Usage Example:
from grafana_client import GrafanaApi, TokenAuth
# Create token auth with your API token
auth = TokenAuth(token="glsa_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_yyyyyyyy")
# Use with GrafanaApi
api = GrafanaApi(auth=auth, host="your-grafana-host")
api.connect()Custom header-based authentication for specialized authentication schemes or proxy configurations.
class HeaderAuth:
"""
Custom header authentication for Grafana API.
Args:
name (str): Header name (e.g., 'X-API-Key', 'Authorization')
value (str): Header value
"""
def __init__(self, name: str, value: str): ...Usage Example:
from grafana_client import GrafanaApi, HeaderAuth
# Create custom header auth
auth = HeaderAuth(name="X-API-Key", value="your-api-key")
# Use with reverse proxy authentication
proxy_auth = HeaderAuth(name="X-WEBAUTH-USER", value="admin")
api = GrafanaApi(auth=proxy_auth, host="your-grafana-host")
api.connect()Basic HTTP authentication using username and password credentials. Pass as a tuple to the auth parameter.
# Basic auth is passed as tuple (username, password)
auth_tuple = (username: str, password: str)Usage Example:
from grafana_client import GrafanaApi
# Use basic authentication with username/password tuple
auth = ("admin", "your-password")
api = GrafanaApi(auth=auth, host="your-grafana-host")
api.connect()Authentication can be configured automatically when using factory methods for client instantiation.
From URL:
from grafana_client import GrafanaApi
# URL with embedded credentials
api = GrafanaApi.from_url(
url="https://admin:password@your-grafana-host:3000",
credential="optional-token-or-credential",
timeout=10.0
)From Environment Variables:
import os
from grafana_client import GrafanaApi
# Set environment variables
os.environ['GRAFANA_URL'] = 'https://your-grafana-host:3000'
os.environ['GRAFANA_TOKEN'] = 'your-api-token'
os.environ['GRAFANA_TIMEOUT'] = '10.0'
# Create client from environment
api = GrafanaApi.from_env(timeout=10.0)Supported Environment Variables:
GRAFANA_URL - Complete Grafana URL (e.g., "https://admin:password@grafana.example.com:3000")GRAFANA_TOKEN - API token for TokenAuth (alternative to credentials in URL)GRAFANA_TIMEOUT - Request timeout in seconds (float)All authentication methods work identically with the async API:
import asyncio
from grafana_client import AsyncGrafanaApi, TokenAuth
async def main():
auth = TokenAuth(token="your-api-token")
api = AsyncGrafanaApi(auth=auth, host="your-grafana-host")
await api.connect()
version = await api.version
print(f"Connected to Grafana {version}")
asyncio.run(main())For advanced scenarios, you can implement custom authentication by extending the niquests.auth.AuthBase class:
import niquests.auth
from grafana_client import GrafanaApi
class CustomAuth(niquests.auth.AuthBase):
"""Custom authentication implementation"""
def __init__(self, custom_token: str):
self.custom_token = custom_token
def __call__(self, r):
# Add custom authentication to request
r.headers['X-Custom-Auth'] = f"Bearer {self.custom_token}"
return r
# Use custom authentication
auth = CustomAuth("your-custom-token")
api = GrafanaApi(auth=auth, host="your-grafana-host")Authentication errors are represented by specific exception types:
class GrafanaUnauthorizedError(GrafanaClientError):
"""Raised for 401 Unauthorized errors"""
pass
class GrafanaClientError(GrafanaException):
"""Base class for 4xx HTTP errors"""
passHandling Authentication Errors:
from grafana_client import GrafanaApi, TokenAuth, GrafanaUnauthorizedError
try:
auth = TokenAuth(token="invalid-token")
api = GrafanaApi(auth=auth, host="your-grafana-host")
api.connect()
except GrafanaUnauthorizedError as e:
print(f"Authentication failed: {e.message}")
print(f"Status code: {e.status_code}")
except Exception as e:
print(f"Connection error: {e}")protocol="https")verify=True)Secure Configuration Example:
import os
from grafana_client import GrafanaApi, TokenAuth
# Secure configuration
auth = TokenAuth(token=os.environ['GRAFANA_TOKEN'])
api = GrafanaApi(
auth=auth,
host=os.environ['GRAFANA_HOST'],
protocol="https", # Use HTTPS
verify=True, # Verify SSL certificates
timeout=10.0, # Reasonable timeout
organization_id=int(os.environ.get('GRAFANA_ORG_ID', '1'))
)
try:
api.connect()
print("Successfully authenticated with Grafana")
except Exception as e:
print(f"Authentication failed: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-grafana-client@5.0.1