Create grafana dashboards with api

Vincent picture Vincent · Jul 1, 2015 · Viewed 15.3k times · Source

I'm trying to create grafana dashboards from a template with the api from grafana. I use grafana v2.0.2 at the moment.

I have an api key and I'm able to get the dashboards with curl, but I'm unable to create dashboards.

When I do the following request: curl -i -H "Authorization: Bearer eyJrIobfuscatedlkIjoxfQ==" http://localhost:3000/api/dashboards/db/webserver2 then I get the json back for the dasboard.

When I try to create the simplest dashboard I found in the api examples it does not work: curl -i -H "Authorization: Bearer eyJrIobfuscatedlkIjoxfQ==" -d /tmp/simpledash http://localhost:3000/api/dashboards/db where /tmp/simpledash contains:

{
  "dashboard": {
    "id": null,
    "title": "Production Overview",
    "tags": [ "templated" ],
    "timezone": "browser",
    "rows": [
      {
      }
    ]
    "schemaVersion": 6,
    "version": 0
  },
  "overwrite": false
 }

I get the following response:

HTTP/1.1 422 status code 422
Content-Type: application/json; charset=utf-8
Date: Wed, 01 Jul 2015 16:16:48 GMT
Content-Length: 84

[{"fieldNames":   ["Dashboard"],"classification":"RequiredError","message":"Required"}]

I tried some variations of the json, but I always get that response and on the internet I could not find a working example. Anyone have a working example for me? I like to have this working so I can create dashboard from ansible.

Thanks!

Answer

Danie picture Danie · Feb 24, 2016

The reason why it's failing is that the API needs to know that the payload is json.

with cURL

curl -XPOST -i http://localhost:3000/api/dashboards/db --data-binary @./test.json -H "Content-Type: application/json"

with ansible

- name: postinstall::dashsetups
  uri:
    url: http://{{grafana.ip}}:{{grafana.bind}}/api/dashboards/db
    method: POST
    user: "{{ admin_usr }}"
    password: "{{ admin_pwd }}"
    body: "{{ lookup('template', item.file) }}"
    status_code: 200
    body_format: raw
    force_basic_auth: yes
    HEADER_Content-Type: "application/json"
  with_items: "{{ grafana.dashboards }}"

and vars file containing dashboards,

"grafana":{"dashboards": [
          {
            "name": "t1",
            "file": "./dashboards/filename.json.j2",
            "dash_name": "Test 1"
          },
          {
            "name": "t2",
            "file": "./dashboards/filename2.json.j2",
            "dash_name": "Test 2"
          },
          {
            "name": "t3",
            "file": "./dashboards/template3.json.j2",
            "dash_name": "Test 3"
          }
        ]
}