How to import dashboards from file path to Grafana instance using api post request?

Hi all.
I am writing a python script that can able to export and import dashbords from one Grafana instance to another Grafana instance.
for now I am exporting them to the local path, abled to export all of my dashboards using get request.
note: all data source uids are updated.
right now, trying to import all of the dashboards from file path to Grafana instance, I am using the post request and have this as my host url → ‘{api_url}/api/dashboards/db’ and using the Bearer token for authentication,
I am getting 404 status code when I run the script.
error > “requests.exceptions.HTTPError: 404 Client Error: Not Found for url: {api_url}/api/dashboards/db’”
so my question is, do I use a correct api?
I found this api from here Dashboard HTTP API | Grafana documentation
thanks for all helps in advance.

Please share your python code without the sensitive stuff?

There are other recommended ways other than using the api if you are willing to get your hands dirty.

sorry for late response,
here was the code i tried

def import_dashboards():
    """this function will use to import the dashboards from local path into grafana instance"""
    api_url =  "https://myHost.net"
    api_key = "hardcode token as of now" 
    input_dir = "local path"

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

    for filename in os.listdir(input_dir):
        if filename.endswith('.json'):
            with open(os.path.join(input_dir, filename), 'r') as f:
                dashboard_data = json.load(f)

            response = requests.post(f'{api_url}/api/dashboards/db', headers=headers, json=dashboard_data)
            response.raise_for_status()
            print(f"Dashboard '{dashboard_data['dashboard']['title']}' imported successfully.")
    return "success" 
dashboard_data = import_dashboards()

when i run this, it gave me 404.
the json file is ok and not missing any of valid fields

Check this out

hi.
I tried everything mentioned there. but its not working for me. Looks like json structure is not correct, even i put the dummy json(provided in the grafana documentation) data as dashboard to try and still gave me 400. Could you share the correct json structure we should pass/upload?
below is the updated code-

def import_dashboard():
“”" this function will push the dashboards to new instance 110960
“”"
#dashboard_import_title = export_dashboard.dashboard_title
grafana_url_post = “https://myhost.net
token = “hardcoded token”
headers = {‘Authorization’: f"Bearer {token}“, ‘Content-Type’: ‘application/json’}
#dashboard_json_updated = {“dashboard”:dashboard_json, “folderUid”: “l3KqBxCMz”, “message”: “Made changes to xyz”, “overwrite”: False}
dashboard_json_updated = {
“dashboard”: {
“id”: None,
“uid”: None,
“title”: “Production Overview”,
“tags”: [ “templated” ],
“timezone”: “browser”,
“schemaVersion”: 16,
“version”: 0,
“refresh”: “25s”
},
“folderId”: 0,
“folderUid”: “l3KqBxCMz”,
“message”: “Made changes to xyz”,
“overwrite”: False
}
r = requests.post(url=grafana_url_post+‘/dashboards/db’, data=json.dumps(dashboard_json_updated), headers=headers)
#r = requests.post(url=grafana_url_post+‘/dashboards/db’, data=json.dumps(dashboard_json_updated), headers=headers, verify=False)
print(” this is the response “, r)
print(“r.status_code”,r.status_code)
print(” this is the dashboard_json_updated which printing inside the imort fun", dashboard_json_updated) # this is printing as a list not json dic
if r.status_code == ‘200’:
print(“imported”)
print(r.content)
else:
print(‘error’)

return "Success"

def get_upload_dashboard(dashboard_json_updated, overwrite=False, message=“Updated by grafanlib”):
dashboard = dashboard_json_updated[“dashboard_json”]
print(“dashboard_json_updated”,dashboard_json_updated)
return json.dumps(
{
“dashboard_json”: dashboard_json_updated,
“overwrite”: overwrite,
“message”: message
}, sort_keys=True, indent=2)

ok. i got it working.
for those who interesting to know what was the issue,
from the code i pasted here, i removed the folderUid’s value and it worked.
you can not post a request with a folderUid unless you get the folderUid from your new instance and hardcoding it. otherwise leave it None and your dashboard will be imported under General folder.
also make sure you have the /api after your host_url or add it inside your requests.post
ex: r=requests.post(url=grafana_url_post+‘/api/dashboards/db’)

1 Like