'Programmatically using python, import grafana dashboard data from grafana website

I have a visual and aggregate result showin in grafana.<<my_company>>.com. I can manually go to the menu click export and export the data to my local in format option I have. This works great. Is there a way I can script that in python that hit grafana server and get result what I need ? So that I can automate it. Looking for info thanks in advance 🙂



Solution 1:[1]

Check out the Grafana HTTP API.

There is also explained, how to get a dashboard by using the dashboards uid. In python, you can for example use the requests package to make http requests. In the JSON response you're getting for the linked request, dashboard will provide the data you are looking for.

Solution 2:[2]

W can use wrapper library as in https://pypi.org/project/grafana-api/.

With requests library a sample snippet is pasted below,

headers = {"Authorization": f"Bearer {os.getenv('GRAFANA_TOKEN')}"}

s = requests.Session()
s.headers = headers
r = s.get(grafana_url + "/api/search?query=&", headers=headers)
dashboards = r.json()
print(dashboards)

dashboard_dir = f"dashboards_{grafana_server}"
if not os.path.isdir(dashboard_dir):
    os.makedirs(dashboard_dir)
for entry in dashboards:
    if entry["type"] != "dash-db":
        continue
    print(entry["uid"])
    try:
        url = grafana_url + f"/api/dashboards/uid/{entry['uid']}"
        print(url)
        r = s.get(url)
        data = r.json()
        filename = dashboard_dir + "/" + data["meta"]["slug"] + ".json"
        with open(filename, "w") as fd:
            json.dump(data, fd, indent=4)
    except Exception as e:
        print(e)

Also to create dashboards through codes refer - https://github.com/weaveworks/grafanalib/tree/main/grafanalib/tests/examples

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dnnshssm
Solution 2 sathish