Using the Nagios XI API

Picture of Louie Mattia
Louie Mattia
What-is-an-API

The built-in Nagios XI API (Application Programming Interface) provides access to a wide range of data, including hosts, services, users, and more. There are times when you may need to interact with the API. To do that you need to learn how to access the API as well as what it contains.

What is contained in the API

The Nagios XI API is divided into three core sections: Objects, Config, and System. Each section serves a distinct purpose, making the API highly flexible and powerful.

Objects: This section is read-only and provides detailed information about various elements within Nagios XI. It allows users to query important resources, such as hosts, services, and other objects, providing insight into their current states and configurations. The data retrieved from this section can be delivered in either XML or JSON formats, making it easy to integrate and process within other applications or systems.

Config: The Config section is designed for administrative tasks, giving administrators the ability to add, remove, and modify objects such as hosts, services, and other configurations within Nagios XI. This section works directly with the Core Config Manager, allowing the creation and deletion of items. It provides a more dynamic role within the API, as it enables direct management and updates of system configurations to meet specific needs or changes in the infrastructure.

System: Like the Config section, the System section is reserved for administrators and provides the ability to manage the core subsystems of Nagios XI. It allows admins to execute system-level commands, configure system settings, and perform administrative tasks that impact the overall functionality and health of the Nagios XI environment.

Types of API Requests

When interacting with the Nagios XI API, you’ll primarily use four types of HTTP requests to interact with the system: GET, POST, PUT, and DELETE. Each request type serves a different purpose, allowing you to retrieve, create, update, or delete data.

  1. GETRetrieve Data
    The GET request is used to retrieve information from the Nagios XI API. It is typically used to query data such as host status, service status, or configuration details. This is a read-only operation and does not modify any data within the system. For example, you might use a GET request to check the current status of a host or service.
    Example: Retrieve host status or service details.
  2. POSTCreate or Submit Data
    The POST request is used to send data to the server, typically to create new resources or submit information. For example, when adding a new host or service to Nagios XI, you’ll use a POST request to submit the necessary configuration data. It is used when creating new objects or triggering actions that modify the state of the system.
    Example: Add a new host, service, or update configuration.
  3. PUTUpdate Data
    The PUT request is used to update or modify an existing resource. It’s typically used when you want to change the configuration of a current host, service, or other object in Nagios XI. Unlike POST, which creates new resources, PUT is meant for updating existing ones.
    Example: Update the configuration of an existing host or service.
  4. DELETERemove Data
    The DELETE request is used to remove a resource from the Nagios XI system. It’s used when you want to delete objects such as hosts, services, or configurations. Deleting data through the API is a permanent operation, so it’s important to be sure before making this type of request.
    Example: Remove a host or service from the system.

How to Access the API via URL

The Nagios XI API can be accessed in a similar way to how you interact with Nagios XI itself—using a web browser. However, it’s important to note that this method is limited to GET requests, which allow you to retrieve and view data from the system. For tasks like creating, updating, or deleting resources (such as adding hosts or modifying configurations), you’ll need to use a different approach, typically by making POST, PUT, or DELETE requests through code. To get started, simply enter the following URL in your browser:

http://<Your Nagios XI IP>/nagiosxi/api/v1/
Screenshot 2025 02 24 095921
API Error

At this point, you’ll see an error message—this is expected since no requests have been made yet. To retrieve data, you need to specify the section of the API you want to query and the resource you’re interested in. The URL should look like this:

http://<Your Nagios XI IP>/nagiosxi/api/v1/<section>/<resource>

The section refers to a main area of the API, like objects, config, or system, each offering access to different data or functions. For example, the objects section retrieves information about items like hosts and services, while the config section allows administrators to manage those objects. A resource is a specific data type or object within that section that you query or manipulate. In the objects section, a resource might be hoststatus, showing the current status of hosts, while in the config section, a resource could be service, used to manage service configurations.

To access the API, you’ll also need to include your API key in the URL. This key grants you access to the system and helps determine the permissions you have based on your user role. Depending on your level of access, different sections and resources may be available to you.

To find your API key, navigate to the admin section of Nagios XI. Once you have it, append it to the URL like this:

http://<Your Nagios XI IP>/nagiosxi/api/v1/<section>/<resource>?apikey=<API key>

With everything set up correctly, you should now see real data returned from the API. We’ll use the results from querying hoststatus objects as an example.

API Query Results
Object Host Status Query Results

By default, the output can appear a bit messy. To improve readability, you can check the Pretty-print checkbox in the UI, which automatically organizes the response. Alternatively, append &pretty=1 to the end of the URL for instant formatting. This makes the output clean, organized, and easy to digest.

http://<Your Nagios XI IP>/nagiosxi/api/v1/objects/hoststatus?apikey=<API key>&pretty=1
API Query results( Clean)
Object Host Status Query Results Cleaned

Objects are for displaying information, while Config and System are used for adding, removing, or modifying objects. What you write will depend on the action you want to perform with the API. For tasks like editing or modifying data, you’ll need to use code, as this involves making requests that modify the system.

Using with Code

There are many reasons why you might want to access the Nagios XI API programmatically. For instance, you may want to fetch the data posted to the system, monitor host/service statuses, or edit configurations directly through your code. Interacting with the API via code provides flexibility and automation, streamlining your workflow.

To access the API, we can use the appropriate method for interacting with URLs in the programming language you’re working with. Since Nagios XI runs on a web-based interface, the most common language for writing programs inside Nagios XI itself is PHP.

Below is an example of how to access and interact with the Nagios XI API using PHP:

<?php
// Define the server IP and API token
$server_ip = '<Your Nagios XI IP>';  // Replace with your Nagios XI IP
$api_token = '<Your API Key>';  // Replace with your Nagios XI API key

// Build the URL for the API request
$url = "http://$server_ip/nagiosxi/api/v1/<section>/<resource>?apikey=$api_token&pretty=1";

// Initialize cURL session
$ch = curl_init();

// Set the URL for the request
curl_setopt($ch, CURLOPT_URL, $url);

// Set option to return the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request and store the response
$response = curl_exec($ch);

// Check if the request was successful
if ($response === false) {
    echo "Error: " . curl_error($ch);  // Handle errors if the request fails
} else {
    // Decode the JSON response
    $data = json_decode($response, true);
    
    // Output the response (for testing or processing)
    echo "<pre>";
    print_r($data);  // Print the data in a readable format
    echo "</pre>";
}

// Close the cURL session
curl_close($ch);
?>

This code example demonstrates how to send a request to the API, process the response, and display the data in a readable format. It’s a simple and efficient way to automate interactions with Nagios XI.

When interacting with the Nagios XI API to modify data, such as adding a new host, the process differs significantly from simply retrieving information. Instead of making a GET request, we’ll use a POST request, which allows us to send data to the server to create or modify resources. The Config section of the API is used for this purpose, as it enables administrators to make changes to the Nagios XI configuration.

Here’s an example of how you can easily add a host to your Nagios XI setup using the API and PHP. This example walks you through how to structure the API request, send the necessary data, and handle the response. By automating the process like this, you can quickly add hosts to your Nagios XI environment, saving time and reducing the need for manual configuration.

function add_host_via_api($api_token)
{
    // Example: Prepare the POST data
    $data = [
        'host_name'                => 'testapihost',
        'address'                  => '127.0.0.1',
        'check_command'            => 'check_ping!3000,80%!5000,100%',
        'max_check_attempts'       => 2,
        'check_period'             => '24x7',
        'contacts'                 => 'nagiosadmin',
        'notification_interval'    => 5,
        'notification_period'      => '24x7',
        'applyconfig'              => 1
    ];

    // Set up the POST fields
    $post_fields = http_build_query($data);

    // Get the Nagios server IP address
    $server_ip = get_nagios_server_ip();

    // Prepare the URL for the API call
    $url = "http://$server_ip/nagiosxi/api/v1/config/host?apikey=$api_token";

    // Use cURL to send the POST request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

    // Execute the cURL request and get the response
    $response = curl_exec($ch);

    // Check for errors in the cURL request
    if ($response === false) {
        return curl_error($ch);
    }

    // Close the cURL handle
    curl_close($ch);

    // Decode the response (optional)
    $response_data = json_decode($response, true);
    
    // Check for success or failure in response
    if (isset($response_data['error'])) {
        return "API Error: " . $response_data['error'];
    }

    return true;  // Return true if the host was added successfully
}

Once the request is made, the response will let you know if the host was added successfully or if there were any issues. We’ve included error handling to catch potential problems, such as network errors or invalid parameters. If everything goes as planned, the function will return true, confirming the host was added with no issues.

This example highlights how modifying your Nagios XI configuration through the API is quite different from just retrieving data. With POST requests, you gain the ability to create, update, and delete resources, giving you full control over your Nagios XI instance.

Conclusion

The Nagios XI API is a powerful tool for managing your Nagios XI instance, offering programmatic access to key data and configuration management capabilities. By following the steps outlined here, you can quickly integrate the API into your processes, improving your workflow. Whether you’re querying status data, managing configurations, or integrating with other systems, the Nagios XI API gives you the flexibility to enhance your Nagios XI experience.

For additional assistance, be sure to check the Nagios XI help section for more in-depth resources and support regarding the API.

Share: