Tag Archives: JSON

Getting started with the Zabbix API – Java example

Zabbix provides an API which can be used to automate routine task, integrate Zabbix functionality into your internal apps or you may even write your own client application.

The API is based on JSON-RPC so you need to use the JSON encoded commands to communicate with the API.

In the following example we will authenticate with the Zabbix server (get the authentication token), which is mandatory before making any other API calls.

All other API calls are done in a similar way, so I guess this example is enough to get started.

The example uses DavidWebb HTTP-Client (with dependecies) which makes JSON REST calls very simple.

import org.json.JSONObject;
import org.json.JSONException;
import com.goebl.david.Webb;

public class ZabbixAPIExample {

   public static void main(String[] args) {

     try {

       JSONObject mainJObj = new JSONObject();
       JSONObject paramJObj = new JSONObject();

       mainJObj.put("jsonrpc", "2.0");
       mainJObj.put("method", "user.login");

       paramJObj.put("user", "Zabbix_username");
       paramJObj.put("password", "Zabbix_user_password");

       mainJObj.put("params", paramJObj);
       mainJObj.put("id", "1");

       Webb webb = Webb.create();

       System.out.println("Data to send: " + mainJObj.toString());

       JSONObject result = webb.post("http://zabbix_server_url/api_jsonrpc.php")
                                    .header("Content-Type", "application/json")
                                    .useCaches(false)
                                    .body(mainJObj)
                                    .ensureSuccess()
                                    .asJsonObject()
                                    .getBody();

       System.out.println("Authentication token: " + result.getString("result"));

     } catch (JSONException je) {

       System.out.println("Error creating JSON request to Zabbix API..." + je.getMessage());

     }

  }

}