npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sc-zabbix-api

v1.0.5

Published

TypeScript client for Zabbix JSON-RPC API with token authentication

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 install

Configuration

  1. Copy the .env.example file to .env:
cp .env.example .env
  1. Configure your Zabbix credentials in the .env file:
ZABBIX_URL=https://your-zabbix-server.com/api_jsonrpc.php
ZABBIX_TOKEN=your-api-token-here
ZABBIX_TIMEOUT=10000

Configuration 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 password
  • UserCheckAuthentication(params?) - Check if current session/token is valid
  • UserLogout() - Logout and invalidate current session

Information

  • ApiinfoVersion() - Get Zabbix API version

Hosts

  • HostGet(params?) - Retrieve hosts

Items

  • ItemGet(params?) - Retrieve items
  • ItemCreate(params) - Create new items
  • ItemUpdate(params) - Update existing items
  • ItemDelete(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

  1. Access your Zabbix instance
  2. Go to AdministrationGeneralAPI 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

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:coverage

Important: Tests make real calls to your Zabbix API. Make sure to configure the .env file with your credentials before running tests.

Build

npm run build

Development

npm run dev  # Watch mode

Development Testing

npm test  # Watch mode for tests

Zabbix API Documentation

For more information about available methods, see the official Zabbix API documentation.

License

MIT