TypeScript client for Zabbix JSON-RPC API with token authentication
npm install sc-zabbix-apiA TypeScript library for consuming the Zabbix JSON-RPC API with support for both token authentication and user/password login.
- ✅ 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
``bash`
npm install
1. Copy the .env.example file to .env:
`bash`
cp .env.example .env
2. Configure your Zabbix credentials in the .env file:
`bash`
ZABBIX_URL=https://your-zabbix-server.com/api_jsonrpc.php
ZABBIX_TOKEN=your-api-token-here
ZABBIX_TIMEOUT=10000
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)
`typescript
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();
`
`typescript
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();
`
The library provides enhanced error handling with specific error types:
`typescript
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;
}
}
}
`
`typescript
// 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"],
});
`
`typescript`
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)
#### 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
Returns all Zabbix hosts.
Returns: Array of Host objects with hostid and host.
#### getItems(hostId: string): Promise
Returns all items from a specific host.
Parameters:
- hostId: string - Host ID
Returns: Array of Item objects with itemid, name, key_ and lastvalue.
#### call
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.
`typescript`
interface Host {
hostid: string;
host: string;
}
`typescript`
interface Item {
itemid: string;
name: string;
key_: string;
lastvalue: string;
}
1. Access your Zabbix instance
2. Go to Administration → General → API tokens
3. Click Create API token
4. Fill in the name and select the user
5. Configure expiration (if needed)
6. Click Add
7. Copy the generated token
Run tests using Vitest:
`bashRun all tests
npm test
Important: Tests make real calls to your Zabbix API. Make sure to configure the
.env file with your credentials before running tests.Build
`bash
npm run build
`Development
`bash
npm run dev # Watch mode
`Development Testing
`bash
npm test # Watch mode for tests
``For more information about available methods, see the official Zabbix API documentation.
MIT