Ad Widget

Collapse

How to use API

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • s12k34
    Junior Member
    • Jan 2011
    • 13

    #1

    How to use API

    Hi,
    I am new in Zabbix and I want to develop a java application that connects to the zabbix server and run methods via zabbix api.
    I googled lots of web pages about what is the exact url of zabbix api, how to make connection and how to use json rpc. But my mind is really confused about how to do these. I tried to use json rpc but I couldn't achieve.
    I need a clear information that tells step by step how can I use API.
    Is there any document or link to get clear information about how to use zabbix API?
    Thanks...
  • nelsonab
    Senior Member
    Zabbix Certified SpecialistZabbix Certified Professional
    • Sep 2006
    • 1233

    #2
    A few things, first please don't go spamming other threads asking for help, you started this thread, that's good enough, if noone replies then bump the thread again, but please it's bad form to spam threads just to get attention. Lastly be patient, people respond because they want to, not because you want/demand them to.

    Also what is confusing to you? You say you are confused but you don't give us any clues on how to help you.

    Have you read the documentation? That is a good place to start. Or if you want have a look at my api code for Ruby, that may give you a clue.

    Bottom line, noone can show you the solution you want, but we can help you figure out the solution you need if you put forth the effort and meet those of us who can help in the middle.
    RHCE, author of zbxapi
    Ansible, the missing piece (Zabconf 2017): https://www.youtube.com/watch?v=R5T9NidjjDE
    Zabbix and SNMP on Linux (Zabconf 2015): https://www.youtube.com/watch?v=98PEHpLFVHM

    Comment

    • s12k34
      Junior Member
      • Jan 2011
      • 13

      #3
      Zabbix URL

      Ok, I will attend this.
      I want to learn the zabbix API url. When I want to mahe http.open("POST", URL, true) operation I need the URL of zabbix API.
      For example is IRL like;
      http://<myapp_ip>/zabbix/api_jsonrpc.php
      or is it like
      http://<myapp_ip>/zabbix/JSON-RPC
      or it is only
      http://<myapp_ip>/zabbix
      which one is the URL of Zabbix.
      Or maybe another thing is the URL I don't know.
      When I read document I saw all the urls that seen in above was given as solution.
      Thanks...

      Comment

      • s12k34
        Junior Member
        • Jan 2011
        • 13

        #4
        Hi all,
        You can find how to connect and execute rpc method via Zabbix API in Java.
        I hope it will be useful...

        Code:
        import java.io.ByteArrayInputStream;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.UnsupportedEncodingException;
        
        import org.apache.commons.httpclient.HttpClient;
        import org.apache.commons.httpclient.HttpException;
        import org.apache.commons.httpclient.methods.PutMethod;
        import org.json.JSONException;
        import org.json.JSONObject;
        
        public class ZabbixApiClient {
        	private static String ZABBIX_API_URL = "http://1.2.3.4/zabbix/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip
        	
        	public static void testClient() throws JSONException, FileNotFoundException, UnsupportedEncodingException {
        	
        		HttpClient client = new HttpClient();
        		
        		PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
        		putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this
        		
        		// create json object for apiinfo.version 
        		JSONObject jsonObj=new JSONObject("{\"jsonrpc\":\"2.0\",\"method\":\"apiinfo.version\",\"params\":[],\"auth\":\"a6e895b98fde40f4f7badf112fd983bf\",\"id\":2}");
        		
        		putMethod.setRequestBody(fromString(jsonObj.toString())); // put the json object as input stream into request body 
        		
        		System.out.println("jsonObj:\n"+jsonObj);
        		
        		String loginResponse = "";
        		
        		try {
        			client.executeMethod(putMethod); // send to request to the zabbix api
        			
        			loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response
        			
        			System.out.println("loginResponse: \n"+loginResponse); // print the result of the response
        			
        			// Work with the data using methods like...
        			JSONObject obj = new JSONObject(loginResponse); 
        			String id = obj.getString("id");
        			String result = obj.getString("result");
        			System.out.println("id:"+id);
        			System.out.println("result:"+result);
        			
        		} catch (HttpException e) {
        			e.printStackTrace();
        		} catch (IOException e) {
        			e.printStackTrace();
        		}		
        	}
        	
        	public static InputStream fromString(String str) throws UnsupportedEncodingException {
        		byte[] bytes = str.getBytes("UTF-8");
        		return new ByteArrayInputStream(bytes);
        	}
        
        	
        	public static void main(String[] args) {
        		try {
        			testClient();
        		} catch (JSONException e) {
        			e.printStackTrace();
        		} catch (FileNotFoundException e) {
        			e.printStackTrace();
        		} catch (UnsupportedEncodingException e) {
        			e.printStackTrace();
        		}
        	}
        
        }
        After the execution of above code, output is like this:

        Code:
        jsonObj:
        {"id":2,"method":"apiinfo.version","params":[],"jsonrpc":"2.0","auth":"a6e895b98fde40f4f7badf112fd983bf"}
        loginResponse: 
        {"jsonrpc":"2.0","result":"1.1","id":2}
        id:2
        result:1.1

        Comment

        • marwaIF
          Junior Member
          • Mar 2013
          • 6

          #5
          hi,
          if i try to ask API version with java code
          i get the result:1.1
          but if i change the method host.get
          JSONObject jsonObj=new JSONObject("{\"jsonrpc\":\"2.0\",\"method\":\"host .get\",\"params\":{\"output\":\"extend\"},\"auth\" :\"5fce1b3e34b520afeffb37ce08c7cd66\",\"id\":2}" );
          i get this reponse:
          loginResponse:
          {"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params.","data":"Not authorized"},"id":2}
          can you help me please
          thanks,

          Comment

          • s12k34
            Junior Member
            • Jan 2011
            • 13

            #6
            Firstly you should call authentication metod for API authentication as like following,

            Code:
            public void authenticateUser() {
            		try {
            			JSONObject jsonObj=new JSONObject();
            			jsonObj.put("jsonrpc", "2.0");		
            			jsonObj.put("method", "user.authenticate");
            //			jsonObj.put("method", "user.login"); -May need to use this
            			jsonObj.put("params", (new JSONObject().put("user", ZabbixApiHelper.ZABBIX_USERNAME).put("password", ZabbixApiHelper.ZABBIX_PASSWORD)));
            			jsonObj.put("id", 0);
            
            			String resultStr = executeRpcMethod(jsonObj);
            			AUTH_VALUE = (String) (new JSONObject(resultStr)).get("result");
            		
            		} catch (JSONException e) {
            			logger.error("Error occurred in authenticateUser method. Exception: "+e.getMessage());
            		}
            	}
            Then use the AUTH_VALUE for get.host method as following

            Code:
            public Integer getHostId(String dslamIp) throws JSONException {    	
                    JSONObject getHostReqObj = new JSONObject();
                    getHostReqObj.put("jsonrpc", "2.0");
                    getHostReqObj.put("method", "host.get");
                    getHostReqObj.put("id", 4);
                    getHostReqObj.put("params", (new JSONObject().put("filter", (new JSONObject()).putOpt("ip", dslamIp)).put("output", "extend")));
            
                    authenticateUser();
                    getHostReqObj.put("auth", AUTH_VALUE);
            
                    String responseStr = executeRpcMethod(getHostReqObj);
                    JSONObject resObj = new JSONObject(responseStr);
                    Object value = resObj.opt("result");
            
                    if (value != null) {
                        if (value instanceof JSONArray) {
                            JSONArray hostsArray = (JSONArray) value;
            
                            if(hostsArray.length() == 1)  {
                                JSONObject hostObj = (JSONObject) hostsArray.opt(0);
                                return hostObj.getInt("hostid");
                            }
                        }
                    }
                    return null;
                }

            Comment

            • marwaIF
              Junior Member
              • Mar 2013
              • 6

              #7
              Thank you for your response,
              but sorry i'm a debutante i don't understand in authentication where i use my url, in the method executeRpcMethod?

              Comment

              Working...