### Setup Grafana Client Development Environment Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Clones the grafana-client repository, sets up a Python virtual environment, and installs the package with test dependencies. ```bash git clone https://github.com/grafana-toolbox/grafana-client cd grafana-client python3 -m venv .venv source .venv/bin/activate pip install --editable=.[test] ``` -------------------------------- ### Install grafana-client Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/README.md Install the grafana-client library using pip. ```bash pip install grafana-client ``` -------------------------------- ### Connect to Grafana and Get Info (Async) Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/00-overview.md Example of connecting to Grafana asynchronously using a URL and printing the Grafana version. ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://user:pass@grafana.example.com/") info = await grafana.connect() print(f"Connected to Grafana {info['version']}") asyncio.run(main()) ``` -------------------------------- ### Start Microsoft SQL Server Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a Microsoft SQL Server Docker container, exposing the default port. ```bash # Start service. docker run --rm -it --publish=1433:1433 \ ``` -------------------------------- ### Asynchronous API Usage Examples Source: https://github.com/grafana-toolbox/grafana-client/blob/main/README.md Examples demonstrating how to use the asynchronous Grafana API client. ```APIDOC ## Asynchronous API Operations ### Connect to Grafana API (Async) ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://username:password@daq.example.org/grafana/") # Create user (async) user = await grafana.admin.create_user({ "name": "User", "email": "user@example.org", "login": "user", "password": "userpassword", "OrgId": 1, }) # Change user password (async) user = await grafana.admin.change_user_password(2, "newpassword") asyncio.run(main()) ``` ``` -------------------------------- ### Organizations Management Examples Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/types.md Provides examples for switching organizations, listing all organizations, and retrieving a specific organization by its ID using the Grafana client. ```python # Switch to different organization grafana.organizations.switch_organisation(org_id=2) # List all organizations orgs = grafana.organizations.list_organisations() # Get specific organization org = grafana.organizations.get_organisation(org_id=2) ``` -------------------------------- ### Install grafana-client Source: https://github.com/grafana-toolbox/grafana-client/blob/main/README.md Install the package from PyPI using pip. This command upgrades the package if it is already installed. ```bash pip install --upgrade grafana-client ``` -------------------------------- ### Set Up Development Sandbox Source: https://github.com/grafana-toolbox/grafana-client/blob/main/docs/development.md Clone the repository, create and activate a virtual environment, and install the project in editable mode with development dependencies. ```shell git clone https://github.com/grafana-toolbox/grafana-client cd grafana-client python3 -m venv .venv source .venv/bin/activate pip install --editable=.[test,develop] ``` -------------------------------- ### Run Tempo and Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a Tempo instance in Docker and runs the health probe against it. Configured for local storage. ```bash docker run --rm -it --name=tempo --publish=3200:80 grafana/tempo:1.4.1 \ --target=all --storage.trace.backend=local --storage.trace.local.path=/var/tempo --auth.enabled=false python examples/datasource-health-probe.py --type=tempo --url=http://host.docker.internal:3200 ``` -------------------------------- ### Asynchronous API Operations Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/04-search-folder-organization.md Demonstrates how to use the asynchronous Grafana API client to perform search, retrieve folders, and get organization details. ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://user:pass@grafana.example.com/") dashboards = await grafana.search.search_dashboards(tag="monitoring") folders = await grafana.folder.get_all_folders() org = await grafana.organization.get_current_organization() print(f"Found {len(dashboards)} dashboards, {len(folders)} folders in {org['name']}") asyncio.run(main()) ``` -------------------------------- ### Run Zipkin and Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a Zipkin instance in Docker and runs the health probe against it. ```bash docker run --rm -it --publish=9411:9411 openzipkin/zipkin:2.23 python examples/datasource-health-probe.py --type=zipkin --url=http://host.docker.internal:9411 ``` -------------------------------- ### Synchronous API Usage Examples Source: https://github.com/grafana-toolbox/grafana-client/blob/main/README.md Examples demonstrating how to use the synchronous Grafana API client for various operations. ```APIDOC ## Synchronous API Operations ### Connect to Grafana API ```python from grafana_client import GrafanaApi grafana = GrafanaApi.from_url("https://username:password@daq.example.org/grafana/") ``` ### Create User ```python user = grafana.admin.create_user({ "name": "User", "email": "user@example.org", "login": "user", "password": "userpassword", "OrgId": 1, }) ``` ### Change User Password ```python user = grafana.admin.change_user_password(2, "newpassword") ``` ### Search Dashboards by Tag ```python grafana.search.search_dashboards(tag="applications") ``` ### Find User by Email ```python user = grafana.users.find_user("test@example.org") ``` ### Add User to Team ```python grafana.teams.add_team_member(2, user["id"]) ``` ### Create or Update Dashboard ```python grafana.dashboard.update_dashboard( dashboard={"dashboard": {...}, "folderId": 0, "overwrite": True} ) ``` ### Delete Dashboard by UID ```python grafana.dashboard.delete_dashboard(dashboard_uid="foobar") ``` ### Create Organization ```python grafana.organization.create_organization( organization={"name": "new_organization"} ) ``` ``` -------------------------------- ### Install Plugin Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Installs a plugin from the Grafana plugin store. Supports installing the latest version or a specific version. Can be configured to ignore errors if the plugin is already installed. ```python # Install latest grafana.plugin.install("grafana-piechart-panel") # Install specific version grafana.plugin.install("grafana-piechart-panel", version="1.6.0") # Ignore if already installed grafana.plugin.install("grafana-piechart-panel", errors="ignore") ``` -------------------------------- ### Async Dashboard Operations Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/02-dashboard.md Demonstrates asynchronous retrieval of dashboard details and version history using `AsyncGrafanaApi`. ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://user:pass@grafana.example.com/") dashboard = await grafana.dashboard.get_dashboard("my-dashboard") print(f"Title: {dashboard['dashboard']['title']}") versions = await grafana.dashboard_versions.get_dashboard_versions( dashboard_uid="my-dashboard" ) print(f"Total versions: {len(versions)}") asyncio.run(main()) ``` -------------------------------- ### DatasourceModel Creation and Conversion Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/types.md Shows how to instantiate a DatasourceModel and then convert it to a dictionary using the asdict() method for use in an API call. ```python from grafana_client.model import DatasourceModel model = DatasourceModel( name="My Prometheus", type="prometheus", url="http://prometheus:9090", access="proxy", jsonData={"timeInterval": "30s"} ) # Convert to dict for API call grafana.datasource.create_datasource(model.asdict()) ``` -------------------------------- ### Token Authentication Setup Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/types.md Demonstrates how to set up Grafana API client authentication using a Grafana API token. ```python from grafana_client import GrafanaApi, TokenAuth token_auth = TokenAuth(token="eyJrIjoiWHg...dGJpZCI6MX0=") grafana = GrafanaApi( auth=token_auth, host="grafana.example.com", protocol="https" ) ``` -------------------------------- ### Get All Alert Rules Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/06-alerting-annotations.md Retrieve a list of all configured alert rules. This is useful for auditing, inventory, or understanding the current alerting setup. ```python rules = grafana.alertingprovisioning.get_alertrules_all() for rule in rules: print(f"Rule: {rule['title']}") ``` -------------------------------- ### List Installed Plugins Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Retrieves a list of all installed plugins on the Grafana instance. Useful for iterating through installed plugins and displaying their names and versions. ```python plugins = grafana.plugin.list() for plugin in plugins: print(f"{plugin['name']}: {plugin['version']}") ``` -------------------------------- ### Run OpenTSDB and Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts an OpenTSDB instance in Docker and runs the health probe against it. ```bash docker run --rm -it --publish=4242:4242 petergrace/opentsdb-docker:latest python examples/datasource-health-probe.py --type=opentsdb --url=host.docker.internal:4242 ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Demonstrates a comprehensive configuration of the Grafana client using environment variables, `from_url` with overrides, and the explicit constructor. Includes API connection verification and usage. ```python from grafana_client import GrafanaApi, TokenAuth import os # Option 1: From environment variables os.environ["GRAFANA_URL"] = "https://grafana.example.com/prod/" os.environ["GRAFANA_TOKEN"] = "eyJrIjoiWHg...==" os.environ["GRAFANA_TIMEOUT"] = "30.0" grafana = GrafanaApi.from_env() # Option 2: Via from_url with credential override grafana = GrafanaApi.from_url( url="https://grafana.example.com/prod/", credential="eyJrIjoiWHg...==", timeout=30.0 ) # Option 3: Explicit constructor grafana = GrafanaApi( auth=TokenAuth(token="eyJrIjoiWHg...=="), host="grafana.example.com", port=443, url_path_prefix="prod/", protocol="https", verify=True, timeout=(5.0, 30.0), user_agent="my-automation-tool/1.0", organization_id=1, session_pool_size=20 ) # Verify connection info = grafana.connect() print(f"Connected to Grafana {info['version']}") # Use API dashboards = grafana.search.search_dashboards() ``` -------------------------------- ### Run Prometheus and Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a Prometheus instance in Docker and runs the health probe against it. ```bash docker run --rm -it --publish=9090:9090 prom/prometheus python examples/datasource-health-probe.py --type=prometheus --url=http://host.docker.internal:9090 ``` -------------------------------- ### Run MariaDB/MySQL Health Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a MariaDB Docker container and then runs the datasource-health-probe.py script to check its health. ```bash docker run --rm -it --publish=3306:3306 --env "MARIADB_ROOT_PASSWORD=root" mariadb:10 python examples/datasource-health-probe.py --type=mysql --url=host.docker.internal:3306 ``` -------------------------------- ### Accessing API Resources and Performing Actions Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/00-overview.md Example demonstrating how to use API resource attributes to search dashboards, create a user, and check datasource health. ```python grafana = GrafanaApi.from_url("https://user:pass@grafana.example.com/") # Search dashboards dashboards = grafana.search.search_dashboards(tag="applications") # Create a user user = grafana.admin.create_user({ "name": "John Doe", "email": "john@example.com", "login": "john", "password": "secret123", "OrgId": 1 }) # Get datasource health health = grafana.datasource.health("prometheus-uid") ``` -------------------------------- ### Async Grafana API Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Demonstrates the usage of the asynchronous Grafana API for common operations like listing plugins and creating service accounts. ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://user:pass@grafana.example.com/") plugins = await grafana.plugin.list() print(f"Plugins: {len(plugins)}") sa = await grafana.serviceaccount.create({ "name": "my-service-account", "role": "Editor" }) print(f"Created SA: {sa['id']}") asyncio.run(main()) ``` -------------------------------- ### Start Elasticsearch and Submit Data Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Launches an Elasticsearch Docker container, submits a sample data point to create an index, and then runs the health probe. ```bash # Start Elasticsearch. docker run --rm -it --publish=9200:9200 --env="discovery.type=single-node" \ docker.elastic.co/elasticsearch/elasticsearch:7.17.4 # Submit a data point. This automatically creates an index named `testdrive`. {apt,brew} install httpie http POST "http://localhost:9200/testdrive/_doc/1?pretty" "@timestamp=2022-06-20T16:04:22.396Z" "sensor=foobar-1" "value=42.42" python examples/datasource-health-probe.py --type=elasticsearch --url=http://host.docker.internal:9200 ``` -------------------------------- ### Run PostgreSQL and Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a PostgreSQL instance in Docker and runs the health probe against it. Uses trust authentication for simplicity. ```bash docker run --rm -it --publish=5432:5432 --env "POSTGRES_HOST_AUTH_METHOD=trust" postgres:14.3 python examples/datasource-health-probe.py --type=postgres --url=host.docker.internal:5432 ``` -------------------------------- ### Header Authentication Setup Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/types.md Demonstrates how to set up Grafana API client authentication using a custom HTTP header. ```python from grafana_client import GrafanaApi, HeaderAuth header_auth = HeaderAuth(name="X-WEBAUTH-USER", value="john@example.com") grafana = GrafanaApi( auth=header_auth, host="grafana.example.com", protocol="https" ) ``` -------------------------------- ### Start Grafana Docker Container Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Launches a Grafana instance using Docker. Adjust GRAFANA_VERSION to use a specific Grafana release. ```bash export GRAFANA_VERSION=7.5.16 export GRAFANA_VERSION=8.5.6 export GRAFANA_VERSION=9.0.2 export GRAFANA_VERSION=main docker run --rm -it \ --publish=3000:3000 \ --env='GF_SECURITY_ADMIN_PASSWORD=admin' \ grafana/grafana:${GRAFANA_VERSION} ``` -------------------------------- ### Run MSSQL Server and Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a SQL Server instance in Docker and then runs the health probe against it. Ensure the SA_PASSWORD matches. ```bash docker run --rm -it --env="ACCEPT_EULA=Y" --env="SA_PASSWORD=root123?" \ mcr.microsoft.com/mssql/server:2022-latest # Create database `testdrive`. docker run --rm -it --network=host mcr.microsoft.com/mssql/server:2022-latest /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P "root123?" -Q "CREATE DATABASE testdrive;" # Invoke Grafana database probe. python examples/datasource-health-probe.py --type=mssql --url=host.docker.internal:1433 ``` -------------------------------- ### Run CrateDB Health Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a CrateDB Docker container and then runs the datasource-health-probe.py script to check its health. ```bash docker run --rm -it --publish=4200:4200 --publish=5432:5432 crate:4.8.1 python examples/datasource-health-probe.py --type=cratedb --url=host.docker.internal:5432 ``` -------------------------------- ### DatasourceIdentifier Usage Examples Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/types.md Demonstrates how to create a DatasourceIdentifier object and use it to retrieve a data source by its UID, name, or deprecated ID. ```python from grafana_client.model import DatasourceIdentifier # By UID ds = grafana.datasource.get(DatasourceIdentifier(uid="prometheus-uid")) # By name ds = grafana.datasource.get(DatasourceIdentifier(name="Prometheus")) # By ID (deprecated) ds = grafana.datasource.get(DatasourceIdentifier(id="1")) ``` -------------------------------- ### Create and Update User Preferences Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/types.md Demonstrates creating a PersonalPreferences object and updating current user, organization, and team preferences. Also shows how to get a compact dictionary representation. ```python prefs = PersonalPreferences( theme="dark", timezone="UTC", locale="en-US" ) # Update current user preferences grafana.user.update_actual_user_preferences(prefs) # Update organization preferences grafana.organization.update_preferences(prefs) # Update team preferences grafana.teams.update_team_preferences(team_id=3, preferences=prefs) # Get as dict without None fields compact = prefs.asdict(filter_none=True) # Result: {"theme": "dark", "timezone": "UTC", "locale": "en-US"} ``` -------------------------------- ### Run Graphite Health Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a Graphite Docker container and then runs the datasource-health-probe.py script to check its health. ```bash docker run --rm -it --publish=8080:8080 graphiteapp/graphite-statsd:latest python examples/datasource-health-probe.py --type=graphite --url=http://host.docker.internal:8080 ``` -------------------------------- ### Run Loki Health Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a Loki Docker container and then runs the datasource-health-probe.py script to check its health. ```bash docker run --rm -it --name=loki --publish=3100:3100 grafana/loki:2.5.0 python examples/datasource-health-probe.py --type=loki --url=http://host.docker.internal:3100 ``` -------------------------------- ### DatasourceHealthResponse Usage Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/types.md Demonstrates how to retrieve data source health information and access its properties, including using the asdict_compact() method. ```python health = grafana.datasource.health_check("prometheus-uid") print(f"UID: {health.uid}") print(f"Status: {health.status}") print(f"Success: {health.success}") print(f"Message: {health.message}") # Compact representation (no large response field) compact = health.asdict_compact() ``` -------------------------------- ### List All Folders Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/04-search-folder-organization.md Retrieve a list of all folders. Optionally, filter by a parent folder UID to get subfolders. ```python folders = grafana.folder.get_all_folders() for folder in folders: print(f"{folder['title']} (UID: {folder['uid']})") # Get subfolders under a parent subfolders = grafana.folder.get_all_folders(parent_uid="parent-uid") ``` -------------------------------- ### Plugin Management Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Manage Grafana plugins including listing, installing, uninstalling, and checking health and metrics. ```APIDOC ## Method: list ### Description List all installed plugins. ### Returns List of plugin objects with `id`, `type` ("app", "datasource", "panel"), `name`, `version`, `enabled`, `info`, etc. ### Example ```python plugins = grafana.plugin.list() for plugin in plugins: print(f"{plugin['name']}: {plugin['version']}") ``` ## Method: by_id ### Description Get single plugin by ID. ### Parameters #### Path Parameters - **plugin_id** (str) - Required - Plugin identifier ### Returns Plugin object ### Raises `GrafanaClientError` if not found ### Example ```python plugin = grafana.plugin.by_id("grafana-piechart-panel") ``` ## Method: install ### Description Install a plugin from the plugin store. ### Parameters #### Path Parameters - **plugin_id** (str) - Required - Plugin identifier #### Query Parameters - **version** (str) - Optional - Specific version; omit for latest - **errors** (str) - Optional - Error handling: "raise" (default) or "ignore" ### Returns Plugin object or None if error='ignore' ### Raises `GrafanaClientError` if installation fails (unless error='ignore') ### Example ```python # Install latest grafana.plugin.install("grafana-piechart-panel") # Install specific version grafana.plugin.install("grafana-piechart-panel", version="1.6.0") # Ignore if already installed grafana.plugin.install("grafana-piechart-panel", errors="ignore") ``` ## Method: uninstall ### Description Uninstall a plugin. ### Parameters #### Path Parameters - **plugin_id** (str) - Required - Plugin identifier #### Query Parameters - **errors** (str) - Optional - Error handling: "raise" (default) or "ignore" ### Returns Response or None if error='ignore' ### Example ```python grafana.plugin.uninstall("grafana-piechart-panel") ``` ## Method: health ### Description Run health check on a plugin. ### Parameters #### Path Parameters - **plugin_id** (str) - Required - Plugin identifier ### Returns Health status object ### Example ```python health = grafana.plugin.health("my-datasource-plugin") print(f"Status: {health.get('status')}") ``` ## Method: metrics ### Description Get plugin metrics/statistics. ### Parameters #### Path Parameters - **plugin_id** (str) - Required - Plugin identifier ### Returns Metrics object ### Example ```python metrics = grafana.plugin.metrics("my-plugin") ``` ``` -------------------------------- ### Get User Preferences Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/05-user-team.md Retrieves the personal preferences for the authenticated user, such as theme, timezone, and locale. ```python prefs = grafana.user.get_actual_user_preferences() print(f"Theme: {prefs.theme}") ``` -------------------------------- ### Async Grafana API Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/05-user-team.md Demonstrates how to use the asynchronous Grafana API to fetch user information and search for teams. Ensure you import asyncio and AsyncGrafanaApi. ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://user:pass@grafana.example.com/") user = await grafana.user.get_actual_user() print(f"Logged in as: {user['login']}") teams = await grafana.teams.search_teams() print(f"Teams: {len(teams)}") asyncio.run(main()) ``` -------------------------------- ### Get Datasource by Name Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Retrieve a data source configuration using its friendly name. This is convenient when the display name is known. ```python ds = grafana.datasource.get_datasource_by_name("Prometheus") ``` -------------------------------- ### Get Folder Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/04-search-folder-organization.md Retrieves the details of a single folder using its unique identifier (UID). ```APIDOC ## Method: get_folder ### Description Retrieve single folder by UID. ### Parameters #### Path Parameters - **uid** (str) - Required - Folder unique identifier ### Returns Folder object ### Raises `GrafanaClientError` (404) if not found ### Example ```python folder = grafana.folder.get_folder("my-folder") print(f"Title: {folder['title']}") ``` ``` -------------------------------- ### Run Grafana Instance Source: https://github.com/grafana-toolbox/grafana-client/blob/main/docs/development.md Start a Grafana Docker container for development. This command maps port 3000 and sets the admin password to 'admin'. ```shell docker run --rm -it --publish=3000:3000 --env='GF_SECURITY_ADMIN_PASSWORD=admin' grafana/grafana:9.3.6 ``` -------------------------------- ### Run Testdata Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Runs the health probe specifically for the 'testdata' datasource. No external service setup is required. ```bash python examples/datasource-health-probe.py --type=testdata ``` -------------------------------- ### Get All Folders Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/README.md Retrieve a list of all available dashboard folders. This is helpful for understanding the folder structure and managing dashboards. ```python # Get folders folders = grafana.folder.get_all_folders() ``` -------------------------------- ### Async Grafana API Usage Example Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/01-admin.md Demonstrates how to use the asynchronous variant of the Grafana API for non-blocking operations. Requires `asyncio` and `AsyncGrafanaApi`. ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://user:pass@grafana.example.com/") stats = await grafana.admin.stats() print(f"Dashboards: {stats['dashboards']}") user = await grafana.admin.create_user({ "name": "Jane Doe", "email": "jane@example.com", "login": "jane", "password": "pass123" }) print(f"Created user {user['id']}") asyncio.run(main()) ``` -------------------------------- ### Get All Folders Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/04-search-folder-organization.md Lists all available folders. Optionally, it can filter the results to show only subfolders under a specified parent folder UID. ```APIDOC ## Method: get_all_folders ### Description Lists all folders. Optionally filter by parent folder (for nested folders). ### Parameters #### Query Parameters - **parent_uid** (str) - Optional - Parent folder UID for filtering (if nested folders enabled) ### Returns List of folder objects with `uid`, `id`, `title`, `version`, `created`, `updated`, etc. ### Example ```python folders = grafana.folder.get_all_folders() for folder in folders: print(f"{folder['title']} (UID: {folder['uid']})") # Get subfolders under a parent subfolders = grafana.folder.get_all_folders(parent_uid="parent-uid") ``` ``` -------------------------------- ### Run InfluxDB 2.x Health Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts an InfluxDB 2.2 Docker container with initialization credentials and then runs the datasource-health-probe.py script. ```bash # https://docs.influxdata.com/influxdb/v2.0/upgrade/v1-to-v2/docker/#influxdb-2x-initialization-credentials docker run --rm -it --publish=8086:8086 \ --env=DOCKER_INFLUXDB_INIT_MODE=setup \ --env=DOCKER_INFLUXDB_INIT_USERNAME=admin \ --env=DOCKER_INFLUXDB_INIT_PASSWORD=adminadmin \ --env=DOCKER_INFLUXDB_INIT_ORG=example \ --env=DOCKER_INFLUXDB_INIT_BUCKET=default \ --env=DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=admintoken \ influxdb:2.2 python examples/datasource-health-probe.py --type=influxdb+flux --url=http://host.docker.internal:8086 docker run --rm -it --network=host influxdb:2.2 influx org list --token=admintoken docker run --rm -it --network=host influxdb:2.2 influx bucket list --org=example --token=admintoken export INFLUX_TOKEN=admintoken influx bucket list --org=example ``` -------------------------------- ### Run Jaeger Health Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts a Jaeger all-in-one Docker container and then runs the datasource-health-probe.py script to check its health. ```bash docker run --rm -it --name=jaeger --publish=16686:16686 jaegertracing/all-in-one:1 python examples/datasource-health-probe.py --type=jaeger --url=http://host.docker.internal:16686 ``` -------------------------------- ### Get Plugin Metrics Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Retrieves metrics and statistics for a given plugin. This can be useful for monitoring plugin performance or resource usage. ```python metrics = grafana.plugin.metrics("my-plugin") ``` -------------------------------- ### Get Organization Preferences Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/04-search-folder-organization.md Retrieves the current organization's preferences. The returned object contains theme and timezone settings. ```python prefs = grafana.organization.get_preferences() print(f"Theme: {prefs.theme}") print(f"Timezone: {prefs.timezone}") ``` -------------------------------- ### Get Data Source by Name Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/README.md Retrieve the configuration details of a data source using its name. Useful for verifying settings or obtaining its UID. ```python # Get data source ds = grafana.datasource.get_datasource_by_name("Prometheus") ``` -------------------------------- ### Run InfluxDB 1.x Health Probe Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Starts an InfluxDB 1.8 Docker container and then runs the datasource-health-probe.py script to check its health. ```bash docker run --rm -it --publish=8086:8086 influxdb:1.8 docker run --rm -it --network=host influxdb:1.8 influx -host host.docker.internal python examples/datasource-health-probe.py --type=influxdb --url=http://host.docker.internal:8086 ``` -------------------------------- ### Async Grafana Datasource Operations Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Demonstrates how to use the asynchronous Grafana API for datasource operations. All methods require the 'await' keyword. This example shows fetching a datasource by name and checking its health. ```python import asyncio from grafana_client import AsyncGrafanaApi async def main(): grafana = AsyncGrafanaApi.from_url("https://user:pass@grafana.example.com/") ds = await grafana.datasource.get_datasource_by_name("Prometheus") print(f"UID: {ds['uid']}") health = await grafana.datasource.health_check("prometheus-uid") print(f"Health: {health.status}") asyncio.run(main()) ``` -------------------------------- ### Check Various Data Source Healths Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-check.rst This section shows examples of checking the health of different data sources, including Graphite, InfluxDB, Prometheus, Testdata, Cloudwatch, and TwinMaker. Some data sources may not be implemented or found. ```bash export GRAFANA_URL=https://play.grafana.org/ # Graphite # FIXME: Not implemented yet. python examples/datasource-health-check.py --uid=000000001 ``` ```bash # InfluxDB 1 / InfluxQL python examples/datasource-health-check.py --uid=000000002 ``` ```bash # Not found python examples/datasource-health-check.py --uid=000000003 ``` ```bash # Prometheus python examples/datasource-health-check.py --uid=000000008 python examples/datasource-health-check.py --uid=NfggWZLGz ``` ```bash # Testdata python examples/datasource-health-check.py --uid=000000051 ``` ```bash # Cloudwatch python examples/datasource-health-check.py --uid=000000098 ``` ```bash # TwinMaker python examples/datasource-health-check.py --uid=qenjJQtnk ``` -------------------------------- ### Initialize GrafanaApi with Environment Variables (Token) Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Demonstrates setting GRAFANA_URL and GRAFANA_TOKEN in the environment and then initializing GrafanaApi using from_env(). ```python import os from grafana_client import GrafanaApi os.environ["GRAFANA_URL"] = "https://grafana.example.com" os.environ["GRAFANA_TOKEN"] = "eyJrIjoiWHg...==" grafana = GrafanaApi.from_env() ``` -------------------------------- ### get Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Retrieve a data source using a flexible identifier, which can be its ID, UID, or name. This is a versatile method for accessing data source configurations. ```APIDOC ## get dsident ### Description Retrieve data source by flexible identifier (ID, UID, or name). ### Parameters #### Path Parameters - **dsident** (DatasourceIdentifier) - Required - Data source identifier with optional `id`, `uid`, or `name` fields ### Returns Data source object ### Raises `KeyError` if none of id, uid, name are specified ### Example ```python from grafana_client.model import DatasourceIdentifier # By UID ds = grafana.datasource.get(DatasourceIdentifier(uid="prometheus-uid")) # By name ds = grafana.datasource.get(DatasourceIdentifier(name="Prometheus")) # By ID ds = grafana.datasource.get(DatasourceIdentifier(id=1)) ``` ``` -------------------------------- ### Initialize Flatdoc with GitHub Fetcher Source: https://github.com/grafana-toolbox/grafana-client/blob/main/docs/index.html This snippet shows how to initialize Flatdoc using the GitHub fetcher to load documentation from a specific GitHub repository. Ensure Flatdoc is properly included in your project. ```javascript Flatdoc.run({ fetcher: Flatdoc.github('grafana-toolbox/grafana-client') }); ``` -------------------------------- ### Get Datasource by UID Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Retrieve a data source configuration using its unique identifier (UID). Useful for direct access when the UID is known. ```python ds = grafana.datasource.get_datasource_by_uid("prometheus-uid") print(f"Type: {ds['type']}") print(f"URL: {ds['url']}") ``` -------------------------------- ### Get Datasource by Flexible Identifier Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Retrieve a data source using a flexible identifier, which can be its ID, UID, or name. Requires importing DatasourceIdentifier. ```python from grafana_client.model import DatasourceIdentifier # By UID ds = grafana.datasource.get(DatasourceIdentifier(uid="prometheus-uid")) # By name ds = grafana.datasource.get(DatasourceIdentifier(name="Prometheus")) # By ID ds = grafana.datasource.get(DatasourceIdentifier(id=1)) ``` -------------------------------- ### get_dashboards_tags Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/02-dashboard.md Get list of all dashboard tags in use. ```APIDOC ## get_dashboards_tags ### Description Get list of all dashboard tags in use. ### Method GET ### Endpoint /api/dashboards/tags ### Response #### Success Response (200) - **tags** (list) - List of tag dictionaries with `term` (tag name) and `count` (number of dashboards) ### Response Example [ { "term": "production", "count": 5 }, { "term": "monitoring", "count": 10 } ] ``` -------------------------------- ### Create Datasource Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Create a new data source by providing its configuration details in a dictionary. Requires 'name', 'type', 'url', and 'access' fields. ```python ds = grafana.datasource.create_datasource({ "name": "My Prometheus", "type": "prometheus", "url": "http://prometheus:9090", "access": "proxy", "jsonData": { "timeInterval": "30s" } }) print(f"Created datasource UID: {ds['uid']}") ``` -------------------------------- ### Get Team by Name Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/05-user-team.md Looks up a team by its exact name. Returns a list of matching team objects. ```python teams = grafana.teams.get_team_by_name("Backend Team") if teams: team = teams[0] ``` -------------------------------- ### Get Folder by UID Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/04-search-folder-organization.md Retrieve a single folder's details using its unique identifier (UID). ```python folder = grafana.folder.get_folder("my-folder") print(f"Title: {folder['title']}") ``` -------------------------------- ### Initialize GrafanaApi from Environment Variables Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Initializes GrafanaApi using GRAFANA_URL and GRAFANA_TOKEN from the environment. Ensure these variables are set before calling this method. ```python from grafana_client import GrafanaApi grafana = GrafanaApi.from_env() # Uses GRAFANA_URL and GRAFANA_TOKEN from environment ``` -------------------------------- ### Get Library Element by UID Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Retrieves a specific library element using its unique identifier (UID). ```python elem = grafana.libraryelement.get_library_element("my-panel-lib") print(f"Type: {elem['type']}") ``` -------------------------------- ### Initialize GrafanaApi with API Token via Constructor Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Demonstrates initializing GrafanaApi using the TokenAuth object directly in the constructor with a provided token, host, and protocol. ```python from grafana_client import GrafanaApi, TokenAuth # Via constructor grafana = GrafanaApi( auth=TokenAuth(token="eyJrIjoiWHg...=="), host="grafana.example.com", protocol="https" ) ``` -------------------------------- ### Get User Teams Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/05-user-team.md Retrieves a list of teams that a specific user is a member of. Requires the user's ID. ```python teams = grafana.users.get_user_teams(5) ``` -------------------------------- ### Connect to Grafana using Environment Variables Source: https://github.com/grafana-toolbox/grafana-client/blob/main/README.md Initialize the Grafana API client by reading the Grafana URL and API token from environment variables (`GRAFANA_URL` and `GRAFANA_TOKEN`). This is a convenient way to manage credentials. ```python grafana = GrafanaApi.from_env() ``` -------------------------------- ### Get Specific Dashboard Version Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/02-dashboard.md Retrieves a specific version of a dashboard using its UID and the desired version ID. ```python version = grafana.dashboard_versions.get_dashboard_version( dashboard_uid="my-dashboard", version_id=5 ) ``` -------------------------------- ### Get Dashboard Permissions by UID Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/02-dashboard.md Lists all permission entries for a specific dashboard using its unique identifier (UID). ```python perms = grafana.dashboard.get_permissions_by_uid("my-dashboard") ``` -------------------------------- ### Interactive MSSQL Client Console Source: https://github.com/grafana-toolbox/grafana-client/blob/main/examples/datasource-health-probe.rst Launches an interactive SQL Server client console for manual interaction. ```bash docker run --rm -it --network=host mcr.microsoft.com/mssql/server:2022-latest /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P root123? ``` -------------------------------- ### Get Dashboard by Name (Slug) Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/02-dashboard.md Retrieve a dashboard using its slug, which is the URL-friendly name. This is an alternative to fetching by UID. ```python dashboard = grafana.dashboard.get_dashboard_by_name("my-dashboard") ``` -------------------------------- ### GrafanaClient Constructor Parameters Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Details the parameters for initializing the low-level GrafanaClient, which are identical to GrafanaApi. ```python GrafanaClient( auth, host="localhost", port=None, url_path_prefix="", protocol="http", verify=True, timeout=5.0, user_agent=None, organization_id=None, session_pool_size=10 ) ``` -------------------------------- ### Initialize GrafanaApi with API Token via from_url Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Initializes GrafanaApi using the from_url method, providing the Grafana URL and the API token as a credential. ```python # Via from_url grafana = GrafanaApi.from_url( url="https://grafana.example.com/", credential="eyJrIjoiWHg...==" ) ``` -------------------------------- ### Initialize GrafanaApi with Custom Timeout from Environment Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Shows how to set a custom timeout using the GRAFANA_TIMEOUT environment variable and initialize GrafanaApi using from_env(). ```python import os from grafana_client import GrafanaApi os.environ["GRAFANA_TIMEOUT"] = "30.0" grafana = GrafanaApi.from_env() ``` -------------------------------- ### Get Contact Points Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/06-alerting-annotations.md Retrieves a list of all configured contact points or filters them by name. Useful for listing notification channels. ```python contact_points = grafana.alertingprovisioning.get_contactpoints() for cp in contact_points: print(f"{cp['name']}: {cp['type']}") # Filter by name slack = grafana.alertingprovisioning.get_contactpoints(name="slack-notifications") ``` -------------------------------- ### Get Plugin by ID Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Fetches details for a specific plugin using its unique identifier. Raises GrafanaClientError if the plugin is not found. ```python plugin = grafana.plugin.by_id("grafana-piechart-panel") ``` -------------------------------- ### Initialize GrafanaApi with HTTP Basic Auth via Constructor Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Initializes GrafanaApi using a tuple of (username, password) for authentication directly in the constructor, along with host and protocol. ```python from grafana_client import GrafanaApi # Via constructor grafana = GrafanaApi( auth=("username", "password"), host="grafana.example.com", protocol="https" ) ``` -------------------------------- ### Initialize GrafanaApi with HTTP Basic Auth via from_url Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Initializes GrafanaApi using the from_url method, embedding the username and password directly within the provided URL. ```python # Via from_url (embedded in URL) grafana = GrafanaApi.from_url( url="https://username:password@grafana.example.com/" ) ``` -------------------------------- ### AsyncGrafanaApi Constructor Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/00-overview.md The AsyncGrafanaApi constructor allows for the initialization of an asynchronous Grafana client. It accepts various parameters for connection configuration, similar to the synchronous GrafanaApi, but omits the `session_pool_size` parameter. ```APIDOC ## AsyncGrafanaApi Constructor ### Description Initializes an asynchronous Grafana client. ### Parameters - **auth** (any) - Optional - Authentication credentials. - **host** (string) - Optional - The hostname of the Grafana instance. Defaults to "localhost". - **port** (int) - Optional - The port of the Grafana instance. - **url_path_prefix** (string) - Optional - A prefix for all URLs. - **protocol** (string) - Optional - The protocol to use (e.g., "http", "https"). Defaults to "http". - **verify** (bool) - Optional - Whether to verify SSL certificates. Defaults to True. - **timeout** (float) - Optional - The request timeout in seconds. Defaults to 5.0. - **user_agent** (string) - Optional - A custom User-Agent string. - **organization_id** (int) - Optional - The ID of the organization to use. ``` -------------------------------- ### GrafanaApi Constructor Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/00-overview.md Initializes the synchronous Grafana API client. Allows configuration of authentication, host, port, protocol, and other connection details. ```APIDOC ## Class: GrafanaApi Primary class for synchronous Grafana API interaction. ### Constructor ```python GrafanaApi( auth=None, host="localhost", port=None, url_path_prefix="", protocol="http", verify=True, timeout=5.0, user_agent=None, organization_id=None, session_pool_size=10 ) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | auth | str, tuple, or niquests.auth.AuthBase | None | Authentication credential: API token (string), basic auth (username, password tuple), or custom auth object | | host | str | localhost | Grafana server hostname | | port | int | None | Grafana server port; omit for default HTTP/HTTPS port | | url_path_prefix | str | "" | Path prefix for Grafana instance (e.g., "grafana/" if installed at /grafana/) | | protocol | str | http | HTTP protocol: "http" or "https" | | verify | bool | True | Verify SSL/TLS certificates | | timeout | float or tuple | 5.0 | Request timeout in seconds, or tuple of (read_timeout, connect_timeout) | | user_agent | str | None | Custom User-Agent header; defaults to "grafana-client/VERSION" | | organization_id | int | None | Bind requests to specific Grafana organization via X-Grafana-Org-Id header | | session_pool_size | int | 10 | Connection pool size for underlying niquests session | ``` -------------------------------- ### Get User by ID Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/05-user-team.md Retrieves detailed information for a specific user using their numeric ID. Raises GrafanaClientError if the user is not found. ```python user = grafana.users.get_user(5) print(f"User: {user['login']}") ``` -------------------------------- ### AsyncGrafanaApi connect Method Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/00-overview.md Asynchronous version of the connection check. Returns a dictionary with connection information. ```python async def connect() -> dict ``` -------------------------------- ### Get Dashboard Permissions Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/README.md Retrieve the current permission settings for a specific dashboard identified by its UID. This shows who has access and their permission level. ```python # Get dashboard permissions perms = grafana.dashboard.get_permissions_by_uid("my-dashboard-uid") ``` -------------------------------- ### Get All Dashboard Tags Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/02-dashboard.md Fetch a list of all tags currently applied to dashboards within Grafana. This can be useful for organizing or filtering dashboards. ```python tags = grafana.dashboard.get_dashboards_tags() for tag in tags: print(f"{tag['term']}: {tag['count']} dashboards") ``` -------------------------------- ### GrafanaApi Constructor Parameters Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/configuration.md Defines the parameters available for initializing the GrafanaApi class, including authentication, host, port, and other connection settings. ```python GrafanaApi( auth=None, host="localhost", port=None, url_path_prefix="", protocol="http", verify=True, timeout=5.0, user_agent=None, organization_id=None, session_pool_size=10 ) ``` -------------------------------- ### Get Datasource ID by Name Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Look up the numeric ID of a data source by its name. Returns an object containing the 'id' key. ```python result = grafana.datasource.get_datasource_id_by_name("Prometheus") datasource_id = result["id"] ``` -------------------------------- ### Create Dashboard Snapshot Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/07-plugin-snapshot-service.md Creates a point-in-time capture of a dashboard. Supports setting a name, expiration time, and can be configured to save to an external snapshot server with specified keys. ```python dashboard = grafana.dashboard.get_dashboard("my-dashboard") snapshot = grafana.snapshots.create_new_snapshot( dashboard=dashboard["dashboard"], name="Snapshot 2024", expires=86400 # Expires in 1 day ) print(f"Snapshot URL: {snapshot['url']}") # External snapshot snapshot = grafana.snapshots.create_new_snapshot( dashboard=dashboard["dashboard"], external=True, key="my-snapshot-key", delete_key="my-delete-key" ) ``` -------------------------------- ### Get Datasource by ID Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/03-datasource.md Retrieve a data source using its numeric ID. Note: This method is deprecated in favor of using UID. ```python ds = grafana.datasource.get_datasource_by_id(1) ``` -------------------------------- ### Get All RBAC Roles Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/08-health-rbac.md Lists all available Role-Based Access Control (RBAC) roles. This feature is available for Grafana Enterprise users. ```APIDOC ## Get All RBAC Roles ### Description Lists all RBAC roles. Requires Grafana Enterprise. ### Method `get_rbac_roles_all()` ### Returns List of role objects with `uid`, `name`, `displayName`, `description`, `permissions`. ### Requires Grafana Enterprise ### Example ```python roles = grafana.rbac.get_rbac_roles_all() for role in roles: print(f"Role: {role['name']}") ``` ``` -------------------------------- ### Create Team Source: https://github.com/grafana-toolbox/grafana-client/blob/main/_autodocs/api-reference/05-user-team.md Creates a new team. Can be provided as a team name string or a dictionary with 'name' and 'email' fields. ```python # By string team = grafana.teams.add_team("New Team") # By dict team = grafana.teams.add_team({ "name": "Backend Team", "email": "backend@example.com" }) print(f"Created team ID: {team['id']}") ```