API & API in Zabbix

API (Application programming interface): 

An API is a set of rules and protocols that allows one software application to interact with another. It defines the methods and data formats that applications can use to request and exchange information.

APIs are typically used for both retrieving data from a service (like fetching information from a database or another web service) and sending data to a service (like submitting a form or updating information).

Zabbix API:

The Zabbix API is a powerful tool that allows you to interact programmatically with the Zabbix monitoring system. It provides endpoints for various operations such as managing hosts, items, triggers, and more.

The Zabbix API is a JSON-RPC-based interface provided by Zabbix for programmatically interacting with and managing the Zabbix monitoring system.

### Key Features

- **Automate Tasks**: Create, update, or delete objects like hosts, items, and triggers.

- **Query Data**: Retrieve monitoring data, configuration details, and more.

- **Custom Integrations**: Integrate Zabbix with other systems or tools.

### Basic Example: Using Zabbix API with Python

Here’s a simple example of how you can use Python to interact with the Zabbix API. This script will log in to Zabbix and retrieve some basic information.

##python

import requests

import json

# Zabbix server URL and API endpoint

zabbix_url = 'http://your-zabbix-server/api_jsonrpc.php'

# API authentication details

headers = {

'Content-Type': 'application/json'

}

# Function to make a request to the Zabbix API

def zabbix_request(method, params):

payload = {

'jsonrpc': '2.0',

'method': method,

'params': params,

'auth': auth_token,

'id': 1

}

Explanation:

import requests: request library is a python module for making http requests.

import json: python module, is used to work with JSON (JavaScript Object Notation) data. Json is a lightweight data-interchange format that is easy for human to read and write and easy for machines to parse and generate.

Content-Type: application/json : HTTP header informs the server that the data being sent in the request body is formatted as JSON.

zabbix_url = 'http://your-zabbix-server/api_jsonrpc.php(API endpoint): The Zabbix API endpoint is the URL where HTTP requests are sent to interact with the Zabbix API. It is the central point through which clients communicate with the Zabbix server using API methods to perform operations such as retrieving, creating, updating, or deleting data.


What is `api_jsonrpc.php`?

api_jsonrpc.php: The `api_jsonrpc.php` file in Zabbix is a key component of its API system.

File: `api_jsonrpc.php` is a PHP script file on the Zabbix server.

Purpose: This file serves as the entry point for all API requests. It processes incoming requests that are made to the Zabbix API and returns responses.

Function: It handles JSON-RPC requests. JSON-RPC is a protocol that allows for remote procedure calls (RPC) using JSON as the data format.

How It Works

1. **Endpoint URL**:

- The URL `http://<zabbix-server>/zabbix/api_jsonrpc.php` is where you send your API requests.

- `<zabbix-server>` is your Zabbix server’s address.

2. **Request Handling**:

- When you make a request to this URL with specific JSON data, `api_jsonrpc.php` processes this data, interacts with the Zabbix backend, and returns the results.

3. **API Methods**:

- The JSON payload in your requests specifies what you want to do (e.g., `host.get` to retrieve host details).

Note: The `api_jsonrpc.php` file is part of the default Zabbix installation. You can find it in the Zabbix server's web directory. Typically, it's located at `/zabbix/api_jsonrpc.php` relative to your Zabbix web root.

JSON format in Zabbix API call

For Zabbix API calls, JSON (JavaScript Object Notation) is the standard and required format. The Zabbix API uses JSON for both requests and responses. So we can say JSON (JavaScript Object Notation) is used for making API calls.

### **Why JSON is Required for Zabbix API**

1. **Standardization**: JSON is the only format supported by Zabbix for its API. The Zabbix API expects all interactions (both requests and responses) to be in JSON format.

2. **Protocol**: The Zabbix API is built on the JSON-RPC protocol, which inherently uses JSON for encoding the data. JSON-RPC is a remote procedure call protocol encoded in JSON, and Zabbix’s API adheres to this standard.

JSON-RPC stands for JavaScript Object Notation Remote Procedure Call. It is a protocol that allows for remote procedure calls (RPC) encoded in JSON format.

Components of JSON-RPC:

1. **JSON**:

- **Format**: JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

2. **RPC**:

- **Remote Procedure Call**: RPC is a protocol used by programs to execute code on a remote server or machine as if it were local. It abstracts the complexities of network communication by allowing you to call functions on a remote server with the same syntax as if they were local.


### **How JSON-RPC Works**

1. **Request Structure**:

- A JSON-RPC request typically includes:

- **`jsonrpc`**: The version of the JSON-RPC protocol being used (e.g., `"2.0"`).

- **`method`**: The name of the API method or function being called.

- **`params`**: A JSON object containing the parameters for the method. It contains instructions like what data to retrieve and how to format the output.

- **`id`**: An identifier to match responses with requests.

**Example Request**:

```json

{

"jsonrpc": "2.0",

"method": "add",

"params": [5, 3],

"id": 1

}

```

2. **Response Structure**:

- A JSON-RPC response typically includes:

- **`jsonrpc`**: The version of the JSON-RPC protocol used.

- **`result`**: The result of the method call, or an error if something went wrong.

- **`id`**: The identifier that matches the response with the original request.

**Example Response**:

```json

{

"jsonrpc": "2.0",

"result": 8,

"id": 1

}

```

Zabbix API work flow:

1. Send Request to API Endpoint

Action: Your client (or code) sends an HTTP request to the Zabbix API endpoint URL.

Data: The request includes HTTP headers (e.g., `Content-Type: application/json`) and a JSON-formatted body containing the method and parameters.

2. Receive and Parse Request

Action: The Zabbix API server receives the HTTP request.

Parsing: The server parses the JSON request body to extract the method name and parameters.

3. Authentication and Authorization

Authentication: If the request requires authentication, the server checks the `auth` token provided in the request against valid sessions.

Authorization: The server verifies whether the authenticated user has permission to perform the requested action.

4. Execute Requested Method

Action: Based on the method specified (e.g., `user.login`, `host.get`), the server performs the requested operation.

user.login: Authenticates the user and generates a session token.

host.get: Retrieves details about hosts from the database.

host.create: Adds a new host to the system.

host.update: Modifies details of an existing host.

host.delete: Removes a host from the system.

5. Generate Response

Result: The server compiles the results of the operation into a JSON-formatted response.

Success: Includes the result data or confirmation of the action taken.

Error: Includes error codes and messages if something went wrong.

6. Send Response to Client

Action: The server sends the JSON response back to the client (your code).

7. Client Receives and Processes Response

Action: Your code receives the HTTP response from the Zabbix API.


API methods used in Zabbix:

apiinfo.version - Retrieves the Zabbix API version.

user.login - Authenticates a user and returns an authentication token.

user.logout - Logs out a user, invalidating their authentication token.

host.get - Retrieves information about hosts.

host.create - Creates a new host.

host.delete - Deletes a host.

item.get - Retrieves information about items.

item.create - Creates a new item.

item.delete - Deletes an item.

trigger.get - Retrieves information about triggers.

trigger.create - Creates a new trigger.

trigger.delete - Deletes a trigger.

event.get - Retrieves information about events.

usergroup.get - Retrieves information about user groups.

usergroup.create - Creates a new user group.

usergroup.delete - Deletes a user group.


How to fetch the host details from Zabbix server:

1. To access any data in zabbix via API, first we need to generate a API token for authentication, there are two methods to generate the API token:

a. Use an existing API token (created in Zabbix frontend or using the Token API);

b. Use an authentication token obtained with the user.login method.

curl --request POST \

     --url 'http://zabbix-server_ip/zabbix/api_jsonrpc.php' \

     --header 'Content-Type: application/json' \

     --data '{

        "jsonrpc": "2.0",

        "method": "user.login",

        "params": {

            "user": "Admin",

            "password": "zabbix"

        },

        "id": 1

     }'


Explanation:

1. curlcurl is a command-line tool for making HTTP requests to web servers. In this case, it is being used to interact with the Zabbix API.

2. --request POST: This specifies the type of HTTP request. POST means you're sending data to the server (in contrast to GET, which retrieves data).

3. --url 'http://zabbix-server_ip/zabbix/api_jsonrpc.php': This is the URL of the Zabbix API. It points to the API endpoint located at zabbix-server_ip. The /zabbix/api_jsonrpc.php is the path to the Zabbix API file, which handles the requests.

4. --header 'Content-Type: application/json-rpc':This header specifies that the data you're sending is in the JSON-RPC format (a protocol that defines how JSON should be structured for remote procedure calls). Content-Type: application/json-rpc tells the server that the body of the request will be in JSON-RPC format.

5. --data: This is the actual data you're sending to the Zabbix API in JSON format:

"jsonrpc":"2.0": Specifies the version of the JSON-RPC protocol (version 2.0 is used by Zabbix).

"method":"user.login": This specifies the method or function you want to call in the API. 

"params":  A JSON object containing the parameters for the method. It contains instructions like what data to retrieve and how to format the output.


2. Now you have a valid user authentication token that can be used to access the data in Zabbix. For example, you can use the host.get method to retrieve the IDs, host names and interfaces of all the configured host

You have two options: directly run the JSON code or create a JSON format file then you can call it.

A. Directly run the JSON code to fetch the host details:

curl --request POST \

--url 'http://34.42.238.178/zabbix/api_jsonrpc.php' \

--header 'Content-Type: application/json-rpc' \

--data '{"jsonrpc":"2.0", "method":"host.get", "params":{"output":["hostid","host"], "selectInterfaces":["interfaceid","ip"]},"auth":"3aba0ea0172b80ff0636a1d2c1b4149290d37ea456fcf24e9080dca4a217d37f", "id":2}'


B. You can create a json file that contains a JSON query

vi data.json

{

   "jsonrpc": "2.0",

   "method": "host.get",

   "params": {

       "output": ["hostid", "host"],

       "selectInterfaces": ["interfaceid", "ip"]

   },

   "auth": "3aba0ea0172b80ff0636a1d2c1b4149290d37ea456fcf24e9080dca4a217d37f",

   "id": 2

}

Now you can make the HTTP request with json query.

curl --request POST \

     --url 'http://34.42.238.178/zabbix/api_jsonrpc.php' \

     --header 'Content-Type: application/json' \

     --data @data.json \

if you want to store the response in any particular file we need to add -o file.json

curl --request POST \

     --url 'http://34.42.238.178/zabbix/api_jsonrpc.php' \

     --header 'Content-Type: application/json' \

     --data @data.json \

     -o host_details.json


If you want to extract the JSON response into plain text you can use the jq tool.

jq -r '.result[] | "Host ID: \(.hostid), Host Name: \(.host), Interface ID: \(.interfaces[].interfaceid), IP Address: \(.interfaces[].ip)"' host_details.json







Comments

Popular posts from this blog

How to enable the syslog monitoring-Zabbix

Zabbix installation: Distribution setup