sc-zabbix-api
v1.0.5
Published
TypeScript client for Zabbix JSON-RPC API with token authentication
Maintainers
Readme
SC Zabbix API Client
A TypeScript library for consuming the Zabbix JSON-RPC API with support for both token authentication and user/password login.
Features
- ✅ Authentication via API token
- ✅ Authentication via username/password with session management
- ✅ Full TypeScript support with strong typing
- ✅ ES modules compatible
- ✅ Specific methods for common operations
- ✅ Generic method for custom calls
- ✅ Robust error handling with detailed error types
- ✅ Automatic retry logic with exponential backoff
- ✅ Connection timeout handling and testing
- ✅ Automatic session management for login-based authentication
Installation
npm installConfiguration
- Copy the
.env.examplefile to.env:
cp .env.example .env- Configure your Zabbix credentials in the
.envfile:
ZABBIX_URL=https://your-zabbix-server.com/api_jsonrpc.php
ZABBIX_TOKEN=your-api-token-here
ZABBIX_TIMEOUT=10000Configuration Options
The ZabbixApiConfig interface supports the following options:
url: string- Zabbix API URL (usually ends with/api_jsonrpc.php)token?: string- Zabbix API token (for token authentication)username?: string- Username (for session authentication)password?: string- Password (for session authentication)timeout?: number- Default timeout in milliseconds (default: 10000)loginTimeout?: number- Timeout for login operations in milliseconds (default: 15000)retries?: number- Number of retry attempts for failed requests (default: 3)retryDelay?: number- Base delay between retries in milliseconds (default: 1000)
Basic Usage
Option 1: Using API Token
import { SCZabbixApi } from "sc-zabbix-api";
const zabbixApi = new SCZabbixApi({
url: "https://your-zabbix-server.com/api_jsonrpc.php",
token: "your-api-token-here",
timeout: 10000, // optional
});
// Get all hosts
const hosts = await zabbixApi.HostGet();Option 2: Using Username/Password
import { SCZabbixApi } from "sc-zabbix-api";
const zabbixApi = new SCZabbixApi({
url: "https://your-zabbix-server.com/api_jsonrpc.php",
timeout: 10000, // optional
});
// Login with username and password
const loginResponse = await zabbixApi.UserLogin({
username: "your-username",
password: "your-password",
userData: true, // optional: retrieve user data
});
console.log("Session ID:", loginResponse.result.sessionid);
// Now you can make API calls
const hosts = await zabbixApi.HostGet();
// Don't forget to logout when done
await zabbixApi.UserLogout();Error Handling
The library provides enhanced error handling with specific error types:
import { SCZabbixApi, ZabbixConnectionError } from "sc-zabbix-api";
try {
const api = new SCZabbixApi({
url: "https://your-zabbix-server.com/api_jsonrpc.php",
token: "your-token",
timeout: 5000,
retries: 3,
});
// Test connectivity
const connectionTest = await api.testConnection();
if (!connectionTest.success) {
console.error(`Connection failed: ${connectionTest.error}`);
return;
}
const hosts = await api.HostGet();
} catch (error) {
if (error instanceof Error && "type" in error) {
const connError = error as ZabbixConnectionError;
switch (connError.type) {
case "TIMEOUT":
console.error("Request timed out - try increasing timeout");
break;
case "CONNECTION_REFUSED":
console.error(
"Server refused connection - check URL and server status"
);
break;
case "NETWORK_ERROR":
console.error("Network error - check connectivity");
break;
case "AUTH_ERROR":
console.error("Authentication failed - check credentials");
break;
}
}
}Example: Get Hosts with Parameters
// Get hosts with specific parameters
const hosts = await zabbixApi.HostGet({
output: ["hostid", "host", "name", "status"],
filter: {
status: [0], // Only enabled hosts
},
selectInterfaces: ["ip", "port", "type"],
limit: 100,
});
const items = await zabbixApi.getItems("12345");
// Generic call for any API method
const result = await zabbixApi.call("hostgroup.get", {
output: ["groupid", "name"],
});API
Constructor
new SCZabbixApi(config: ZabbixApiConfig)ZabbixApiConfig:
url: string- Zabbix API URL (usually ends with/api_jsonrpc.php)token?: string- Zabbix API token (for token authentication)username?: string- Username (for session authentication)password?: string- Password (for session authentication)timeout?: number- Default timeout in milliseconds (default: 10000)loginTimeout?: number- Timeout for login operations in milliseconds (default: 15000)retries?: number- Number of retry attempts for failed requests (default: 3)retryDelay?: number- Base delay between retries in milliseconds (default: 1000)
Methods
Connection Testing
testConnection()- Test connectivity to Zabbix server and return latency information
Authentication
UserLogin(params)- Authenticate with username and passwordUserCheckAuthentication(params?)- Check if current session/token is validUserLogout()- Logout and invalidate current session
Information
ApiinfoVersion()- Get Zabbix API version
Hosts
HostGet(params?)- Retrieve hosts
Items
ItemGet(params?)- Retrieve itemsItemCreate(params)- Create new itemsItemUpdate(params)- Update existing itemsItemDelete(itemIds)- Delete items by ID
getHosts(): Promise<Host[]>
Returns all Zabbix hosts.
Returns: Array of Host objects with hostid and host.
getItems(hostId: string): Promise<Item[]>
Returns all items from a specific host.
Parameters:
hostId: string- Host ID
Returns: Array of Item objects with itemid, name, key_ and lastvalue.
call<T, P>(method: string, params: P): Promise
Generic method for custom calls to the Zabbix API.
Parameters:
method: string- API method name (e.g., 'host.get', 'item.get')params: P- Parameters for the method
Returns: Typed result as specified.
Types
Host
interface Host {
hostid: string;
host: string;
}Item
interface Item {
itemid: string;
name: string;
key_: string;
lastvalue: string;
}How to get an API token
- Access your Zabbix instance
- Go to Administration → General → API tokens
- Click Create API token
- Fill in the name and select the user
- Configure expiration (if needed)
- Click Add
- Copy the generated token
Tests
Run tests using Vitest:
# Run all tests
npm test
# Run tests with visual interface
npm run test:ui
# Run tests once (CI/CD)
npm run test:run
# Run tests with coverage
npm run test:coverageImportant: Tests make real calls to your Zabbix API. Make sure to configure the .env file with your credentials before running tests.
Build
npm run buildDevelopment
npm run dev # Watch modeDevelopment Testing
npm test # Watch mode for testsZabbix API Documentation
For more information about available methods, see the official Zabbix API documentation.
License
MIT
