Hi, Im currently trying to export Grafana alert rules through the alerts API in version 9.0.5 Grafana.
I am able to get a JSON response with all the information that i want, but the alert rules i export are the first state of the rule, not the current. When i run the script i get a state that was made in January 2023, but the current state was made in March 2023.
The way that i found out that this was the wrong state is by looking in the state history, where i can see that the edits made in the time between January → March was not included and the parts of the alert rule that has been deleted since January still exists in the JSON file that i exported via my script.
My Code:
import requests
import json
# Set the Grafana API URL and API key
GRAFANA_API_URL = "https://<Grafana instance>/api/alerts/<Alert ID>"
GRAFANA_API_KEY = <Personal Grafana API Key>
# Set the name of the output JSON file
OUTPUT_FILE = "alert_rules.json"
# Set the headers for the API requests
headers = {
"Authorization": f"Bearer {GRAFANA_API_KEY}",
"Content-Type": "application/json",
}
# Make the API request to get the list of alert rules
response = requests.get(GRAFANA_API_URL, headers=headers)
# Write the raw JSON response to a file
with open(OUTPUT_FILE, "w") as outfile:
json.dump(response.json(), outfile, indent=4)
# Print a success message
print(f"All alert rules have been exported to {OUTPUT_FILE}.")
I used the following documentation: