Exporting alerts json data using Grafana API in Grafana v10

446 views Asked by At

I am using Grafana cloud v10.0.3 and could not find any way to exports alerts json data. I tried to write a python script to access alerts json data but it is not showing any output. Below is the python script

import requests
import json

# Replace this with your actual token
token = "api token"

grafana_url = "https://domain.grafana.net"
alert_name = "NetworkDevice Down" //alert name

headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/json",
    "Content-Type": "application/json"
}

response = requests.get(f"{grafana_url}/api/alerts", headers=headers)

if response.status_code == 200:
    alerts = response.json()
    for alert in alerts:
        if alert['name'] == alert_name:
            print(json.dumps(alert, indent=4))
else:
    print(f"Request failed with status code {response.status_code}")

Any idea what I am doing wrong? Thanks

1

There are 1 answers

1
LoGo124 On

In Grafana v10, the endpoint for retrieving alerts has been changed. Instead of /api/alerts, you need to use /api/v2/alerts to access the alerts API. Additionally, the response format has also been updated.

Modify your code as follows:

import requests
import json

# Replace this with your actual token
token = "api token"

grafana_url = "https://domain.grafana.net"
alert_name = "NetworkDevice Down"  # alert name

headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/json",
    "Content-Type": "application/json"
}

response = requests.get(f"{grafana_url}/api/v2/alerts", headers=headers)

if response.status_code == 200:
    alerts = response.json()["results"]
    for alert in alerts:
        if alert['name'] == alert_name:
            print(json.dumps(alert, indent=4))
else:
    print(f"Request failed with status code {response.status_code}")

The main changes include:

Updating the endpoint from /api/alerts to /api/v2/alerts.
Accessing the alerts using response.json()["results"].

Make sure to replace "api token" and "https://domain.grafana.net" with your actual API token and Grafana URL respectively.

With these changes, the script should be able to retrieve and print the alerts JSON data for the specified alert name.