Checkmk
to checkmk.com

1. Introduction

As of Version 2.0.0, there is a new application programming interface in Checkmk: the Checkmk REST-API. This API enables you to perform tasks — that you would otherwise perform in Checkmk in its GUI — to be transmitted to and executed with HTTP requests on the Checkmk server using commands or scripts.

Using an API via HTTP? This may sound familiar to you, of course, since Checkmk has been providing an API for a long time — the so-called Web-API — with which you can perform many administration tasks. So why is there now a new API? Contrary to what the name REST-API might suggest, the new API is not intended to provide the Rest of the functions missing in the Web-API. On the contrary, the REST-API is intended to cover the complete functionality that Checkmk provides via the GUI and via the command interface, thus completely replacing the Web-API.

REST stands for *RE*presentational *S*tate *T*ransfer, and it describes an architecture for the exchange of data on distributed systems — especially for web services. An API implemented according to the REST architecture follows certain principles, e.g. the client-server model, stateless communication and a uniform interface. In practice, the implementation is preferably carried out via the HTTP protocol, whereby the resources are addressed via the Uniform Resource Identifier (URI) and accessed using HTTP methods (GET, POST, PUT, DELETE).

So much for the REST principles. The advantages of these principles can be demonstrated by the concrete features provided by the Checkmk REST-API:

FeatureDescription

Protocol

The Hypertext Transfer Protocol (HTTP/1.1) is used as the transport system for communication.

Coding

The JavaScript Object Notation (JSON) is used as the data format. The payload of the answers is serialised with JSON and encoded in UTF-8. Date and time information is encoded in the ISO-8601 format with valid time zone information.

Language

English is the language for labels, identifiers and API documentation.

Authentication

Access to the API is only granted to a client if it has proven its authorization by means of HTTP authentication (e.g. 'Basic' or 'Bearer').

Versioning

The API is versioned and uses a three-level numbering scheme according to the Semantic Versioning 2.x standard. For details, refer to the Chapter on Versioning below.

Documentation

The API is documented in a machine-readable schema and in a human-readable format in English, with all resources, their input and output parameters and the associated value ranges. The API is created with the OpenAPI Specification (OAS) 3.x, an API description format especially for REST-APIs. The API document created with this specification is displayed to the user with ReDoc, a responsive web design for OpenAPI documents.

Code example

To demonstrate its use, sample code for different applications is provided for each request.

Error display

In the event of an error, the API sends numeric HTTP status codes and a diagnostic message for the problem, which helps to identify possible causes of incorrect requests.

REST-API classification

The API fulfils all four levels (0 to 3) of the Richardson Maturity Model (RMM), which can be used to assess how much REST an API contains. Level 1 requires the introduction of resources to enable communication via the API to individual endpoints rather than to a global one. Level 2 is met if HTTP methods are used for the requests. At the (highest) level 3, the API is effectively self-documenting, in that the server, when responding to a request, communicates any possible next actions and the resources to be addressed, thus enabling the client to discover the available functionality for itself. This provision of additional information is also called 'Hypermedia as the Engine of Application State' (HATEOAS).

In addition to these general comfort functions, the Checkmk REST-API already offers access to more areas in Checkmk than the Web-API, e.g. downtimes, time periods, acknowledgement of problems, agents and the Business Intelligence (BI). For many areas that support both APIs, REST-API also gives you more, and more specific functionality.

Despite all the REST enthusiasm, we do not hide the fact that the REST-API does not yet have all the features of the Web-API (rule sets, for example). Since this is the current situation, you will find a comparison of the functionalities of REST-API and Web-API in the last chapter of this article.

2. The API documentation

2.1. Versioning

One of the advantages of the REST-API is that both the software and its documentation come from the same source: the OpenAPI document. Thus the API documentation always matches the software and describes exactly what the API can do. Therefore it is not necessary to describe the reference part of the available resources, methods, parameters etc. in the Checkmk manual — instead you will find the API documentation separately from this manual, directly in your Checkmk site.

The API with its documentation is versioned and uses a three-level numbering scheme in X.Y.Z format, where X stands for a main release, Y for a minor release and Z for a patch. A new minor release contains new, backward-compatible functions. A new main release may contain changes that make the API incompatible with the previous main release (so-called breaking changes). The version number of the main release is part of the URL used to send a request to the server.

Important: Note that the REST-API follows a different versioning scheme than that for the Checkmk software. Since a new main release of the API is necessary if there are incompatible API changes, this usually does not match the release cycle of the Checkmk software.

Nevertheless, the correlation between the versions of API documentation and Checkmk software is very straightforward, as you will learn in the next chapter.

2.2. Access

The REST-API documentation is available in HTML format for viewing in a Web browser. It can be opened via the Checkmk GUI and, alternatively/additionally, can also be downloaded from the Checkmk website.

If you open the API documentation via the Checkmk GUI, the appropriate API documentation is automatically displayed. In the Download-Archive you will find the corresponding API documentation when entering the Checkmk software version.

In the Checkmk GUI, open the API documentation from the navigation bar, Help menu > Internal links > REST API documentation. The API documentation is displayed in a new browser window (or browser tab). We will discuss this in more detail in the next chapter.

help menu

Note: You will surely have noticed that there is another REST-API entry in the Help menu called REST API interactive GUI. With this entry you open another view on the REST-API. The entry is called GUI because you are not only shown the REST-API functions, but because you can interact with the API directly from the browser, e.g. by sending requests to the server. We will introduce the REST-API GUI as an alternative to execution by script later in the Chapter on the REST-API GUI.

2.3. Structure and content

The API documentation uses a responsive web design consisting of three sections:

restapi redoc
  • The left-hand section, navigation, is used for orientation, searching and a quick jump to the exact description of the entries in the middle section. The table of contents contains one entry for each API endpoint. An endpoint uses a URL to refer to the resource that the API provides (e.g. for collecting hosts), together with the method used to access the resource (e.g. GET to display a host). The endpoints are organised into several folders.

  • The middle section, content, contains the hard facts on the documentation: all information for defining a request (with parameters, value ranges, default values and descriptions) and the corresponding answers (also with all details). The possible answers are displayed in different colours, depending on whether the returned HTTP status code signals success or an error.

  • The right-hand section, Request samples, shows the method and URL for the endpoint selected in the content section, followed by several examples of requests: the payload in JSON format (if relevant for the endpoint) and code examples, e.g. for cURL, HTTPie, Python Requests and Python Urllib. Then follow the responses according to the HTTP status. All code examples can be copied to the clipboard with the Copy button.

The navigation section is scroll-synchronised with the other two sections, which means that if you scroll up or down in the content section, the navigation section automatically scrolls to the appropriate entry in the table of contents.

The responsive web design ensures that the example section does not appear in a very narrow browser window (the examples are then displayed below the corresponding method), and the navigation section is converted into a menu.

In all sections you will find content that you can show and hide, for example, the entries for the end points in the navigation section and nested parameters in the content section. By clicking on > or Expand all you can show the hidden contents, and with or Collapse all you can hide them again.

How you can use the API documentation to create concrete requests from the information, send them to the Checkmk server, have them executed and monitor their success you will learn about in the next chapter.

3. Using the API

3.1. Authentification

To use the REST-API from a client, automation user must be configured in the Checkmk server. Only this user is allowed to perform operations via the API.

For authentication, you will need the user name and the corresponding 'automation secret for machine accounts' — i.e. the password for the automation user. Both items of information must be transmitted to the Checkmk server in the header of each request. For a newly-created site, the user automation will have already been created. You can find it, like other users, under Setup > Users. Make sure that the roles and the associated permissions for the automation user are set to allow you to execute your requests.

In this article the default automation user is always used as an example.

3.2. Testing the API locally

To test the REST-API, it is advisable to make the requests directly from the Checkmk server, i.e. in this case client and server are on the same computer. If you are working as a site user, you can also use local variables such as $OMD_SITE, which refers to the name of the site.

In the following examples, we use the sample code contained in the API documentation for the command line program cURL, which enables data to be transferred to or from a server without user interaction, for example via HTTP. The curl command is executed within a bash script.

For the preparation, create a script file to which the sample code is later copied:

OMD[mysite]:~$ touch rest-api_test.sh
OMD[mysite]:~$ chmod +x rest-api_test.sh

Before starting, gather some basic information specific to your Checkmk configuration:

VariableDescriptionExample

HOST_NAME

myserver

The Checkmk server’s hostname

SITE_NAME

mysite

The Checkmk site’s name

USERNAME

automation

The automation user’s name

PASSWORD

theautomationsecret

The automation user’s password

These variables are used in the sample code and must be edited by you before sending a request. In the table above you will also find the example values used in the following.

3.3. Making requests using scripts

We will now demonstrate how to use the REST-API with a straightforward example: You create a host with its services using a total of three requests. In principle, you proceed in the same way as you would with the Checkmk GUI:

  1. Create a host

  2. Perform a service discovery on the host

  3. Activate the changes

Creating a host

Open the API documentation and select the entry for creating a host (Create a host) in the left navigation area:

restapi redoc 2pane

In the middle part of the panel you can see the details of the selected request, which HTTP authentication is required (this is identical for all requests via the REST-API), and the required and optional parameters. The name of the host and the folder in which it should be created is required. If you do not want to create the host in the main directory, you would have to make another API request (List all folders) to view the existing folders to determine the ID of the one you want to use.

In our example, we want to create the host myserver123 with the IP address 192.168.0.42 in the main folder.

In the API documentation, click the curl button in the right-hand example area and then click Copy to copy the cURL sample code to the clipboard. Open the prepared script rest-api_test.sh and paste the clipboard’s contents into it:

#!/bin/bash
HOST_NAME="localhost"
SITE_NAME="heute"
API_URL="http://$HOST_NAME/$SITE_NAME/check_mk/api/v0"

USERNAME="automation"
PASSWORD="test123"

curl \
    -X POST \
    --header "Authorization: Bearer $USERNAME $PASSWORD" \
    --header "Accept: application/json" \ \
    --data '{
          "attributes": {
            "ipaddress": "192.168.0.123"
          },
          "folder": "\/",
          "host_name": "example.com"
        }' \
    "$API_URL/domain-types/host_config/collections/all"

In the first part of the example code you will find the four environment variables to be changed, then comes the curl command with the POST method on the resource whose URL is in the last line. With the POST method, following the header lines (one of which defines the HTTP authentication), you will find the data section where the parameters for the new host are set.

Please note that the curl sample code may contain more parameters than you might need in a specific case. For our example this is not the case and you only need to change the two existing parameters host_name and ipaddress.

Now adjust the sample code so that the result looks something like this:

#!/bin/bash
HOST_NAME="*myserver*"
SITE_NAME="*mysite*"
API_URL="http://$HOST_NAME/$SITE_NAME/check_mk/api/v0"

USERNAME="*automation*"
PASSWORD="*theautomationsecret*"

curl \
    -X POST \
    --header "Authorization: Bearer $USERNAME $PASSWORD" \
    --header "Content-Type: application/json" \
    --header "Accept: application/json" \
    --data '{
          "attributes": {
            "ipaddress": "*192.168.0.42*"
          },
          "folder": "*\/*",
          "host_name": "*myserver123*"
        }' \
    "$API_URL/domain-types/host_config/collections/all"

Execute the script:

OMD[mysite]:~$ ./rest-api_test.sh
{
  "domainType":"host_config",
  "id":"myserver",
  "title":null,
  "links":[
    { "rel":"self",
      "href":"\/objects\/host_config\/myserver123",
      "method":"GET",
      "type":"application\/json",
      "domainType":"link" },
    { "rel":"urn:org.restfulobjects:rels\/update",
      "href":"\/objects\/host_config\/myserver123",
      "method":"PUT",
      "type":"application\/json",
      "domainType":"link" },
    { "rel":"urn:org.restfulobjects:rels\/delete",
      "href":"\/objects\/host_config\/myserver123",
      "method":"DELETE",
      "type":"application\/json",
      "domainType":"link" }],
  "members":{
    "folder_config":{
      "id":"folder_config",
      "memberType":"property",
      "value":"\/objects\/folder_config\/8bef58303863484da83f51d99d9caebc",
      "format":"string",
      "title":null,
      "choices":[],
      "links":[
        { "rel":"self",
          "href":"\/objects\/host_config\/myserver123\/properties\/folder_config",
          "method":"GET",
          "type":"application\/json;profile=\"urn:org.restfulobjects:rels\/object_property\"",
          "domainType":"link" }]}},
  "extensions":{
    "attributes":{
      "ipaddress":"192.168.0.42"},
    "is_cluster":false,
    "is_offline":false,
    "cluster_nodes":null}
}

Note: The REST-API outputs all answers in one line (unformatted). For better readability we have formatted the output in the above as multi-line, and likewise in all following examples.

In the response, you can see from the bold entries that the host has been created. Following the host ID, the API returns a selection of requests under links that can be applied to the host you just created — as befits a REST-API. Under members information on the folder is shown (again with a possible follow-up request), and under extensions the parameters and attributes including the IP address that has just been set.

Perform a service discovery on the host

Once the host myserver123 has been created, its services can be discovered. To do this, select the entry for executing a service discovery (Execute a service discovery of a host) in the API documentation, copy the sample code into the script and customise it to match your configuration.

You can copy the first part with the environment variables 1:1 from the previous example. In the curl command, change the name of the host to myserver123. In this request, unlike the previous one, the name is not specified in a data element, but is a part of the URL in the last line:

HOST_NAME="*myserver*"
SITE_NAME="*mysite*"
API_URL="http://$HOST_NAME/$SITE_NAME/check_mk/api/v0"

USERNAME="*automation*"
PASSWORD="*theautomationsecret*"

curl \
    -X POST \
    --header "Authorization: Bearer $USERNAME $PASSWORD" \
    --header "Accept: application/json" \
    "$API_URL/objects/host/*myserver123*/actions/discover-services/mode/tabula-rasa"

Execute this script as well.

Activate the changes

Finally, the changes must be activated. The appropriate request is called Activate pending changes.

As before, take the first part with the environment variables from the previous examples. In the data part of the curl command change the parameter sites and set it to the name of the site - where the changes should be activated:

#!/bin/bash
HOST_NAME="*myserver*"
SITE_NAME="*mysite*"
API_URL="http://$HOST_NAME/$SITE_NAME/check_mk/api/v0"

USERNAME="*automation*"
PASSWORD="*theautomationsecret*"

curl \
    -X POST \
    --header "Authorization: Bearer $USERNAME $PASSWORD" \
    --header "Accept: application/json" \
    --data '{
          "redirect": false,
          "sites": [
            "*mysite*"
          ]
        }' \
    "$API_URL/domain-types/activation_run/actions/activate-changes/invoke"

Execute this script:

OMD[mysite]:~$ ./rest-api_test.sh
{
  "domainType":"activation_run",
  "id":"66d50347-4974-491f-ba5c-2dee126cf796",
  "title":"Activation 66d50347-4974-491f-ba5c-2dee126cf796 was started.",
  "links":[
    { "rel":"self",
      "href":"\/objects\/activation_run\/66d50347-4974-491f-ba5c-2dee126cf796",
      "method":"GET",
      "type":"application\/json",
      "domainType":"link"},
    { "rel":"urn:com.checkmk:rels\/wait-for-completion",
      "href":"\/objects\/activation_run\/66d50347-4974-491f-ba5c-2dee126cf796\/actions\/wait-for-completion\/invoke",
      "method":"GET",
      "type":"application\/json",
      "domainType":"link"}],
  "members":{},
  "extensions":{}
}

The bold text indicates that the activation has been started. Again, the REST-API suggests two useful follow-up requests under links: to query the status of this activation, and to wait for its completion.

3.4. Making requests via the REST-API GUI

With the REST-API GUI you get a new perspective on the API. With this GUI you can interact directly with the API from the browser by sending requests to the server via cURL command, and immediately see the responses. To do this, you have to do without the code examples of the REST-API documentation in the API GUI — both views are optimised for their respective functions.

The REST-API GUI is generated from the same source as the REST-API documentation — the OpenAPI document — and therefore always provides functions that match the API.

You open the API GUI in the Checkmk GUI from the navigation bar, Help menu > Internal links > REST API interactive GUI. The API GUI is displayed in a new browser window (or browser tab):

restapi swaggerui

In the following we outline how you can execute the first request from the above example (create a host) with the REST-API GUI instead of using a script:

  1. Authorize: Click the Authorize button. You will find it above the entry of the first endpoint folder. Enter automation theautomationsecret in the opening dialog box, confirm with Authorize and click Close. The authorization remains valid until the page is reloaded. However, you will only know whether the authorization was successful after sending the first request.

  2. Select the end point: In the Hosts folder, select the endpoint Create a host and click Try it out.

  3. Enter parameter values: In Request body overwrite the example values for host_name and ipaddress.

  4. Send a request: Click Execute.

  5. Check the answer: Under Responses you will first see the sent cURL command and the URL of the endpoint. Then under Server response the response is displayed with HTTP status code and in the Response body with the (multi-line formatted) REST-API response

The REST-API GUI therefore offers you the opportunity to try out the functions of the API quickly and easily, and to familiarise yourself with the details of the input values as well as with concrete responses.

3.5. Error correction

In contrast to the output shown so far for successful commands via script, the REST-API shows you errors in the following way:

{
  "title":"There are changes from other users and foreign changes are not allowed in this API call.",
  "status":401,
  "detail":"An exception occurred.",
  "ext":null
}

Depending on the error, the parameters displayed in the output may vary. However, they always receive in status the HTTP status code, and in title a description of the error cause. In the above example, you can see that there are pending changes in Checkmk, but these were initiated by another user. Only changes that have been made via the API can be activated.

In most cases, detail will show you detailed information, as the name suggests. This can be less helpful (as above), or very helpful as in the next example:

{
  "title": "Bad request.",
  "status": 400,
  "detail": "These fields have problems: host_name",
  "host_name": [
    "'myserver/123' does not match pattern '[-0-9a-zA-Z_.]+'."
  ]
}

The problem here is that a parameter value does not adhere to the valid value range (because of a slash in the host name).

The number of possible errors is of course much greater than the two we have presented here. However, you can see from the examples shown that in its output the REST-API usually provides sufficient information on the cause and thus gives you clues for starting the analysis and troubleshooting.

4. Securing the API

Since sensitive data can be transferred during access via the REST-API and — depending on the authorization of the automation user — considerable alterations could potentially be made to Checkmk, you should secure such access accordingly. Here you will find some of the available options:

  • Checkmk over HTTPS: Use the API exclusively over Hypertext Transfer Protocol Secure (HTTPS), otherwise user names, passwords, and also configuration data will be transmitted in clear text on the network.

  • Give the automation user a password of sufficient length. Since the password is usually only stored in a script, you can easily assign a very long one.

  • Be sure to pay careful attention to the authorization concept for the scripts you use to make requests to the API. The scripts may contain sensitive data such as configuration data, passwords, etc. Therefore, make sure that only authorized users and groups can read these scripts.

5. Comparison of the REST-API and the Web-API

This chapter gives you an overview of the functions available to you via the REST-API and via the Web-API. The following table is structured according to the end points that you will find in the left navigation area of the REST-API documentation. In the table, the column for the REST-API contains the HTTP methods (supplemented with context information in case of ambiguity) and the column for the Web-API contains its commands.

Action

REST-API

Web-API

Activate pending changes

POST activate-changes

activate_changes

Wait for an activation to complete

GET wait-for-completion

-

Show the status of an activation

GET activation_run

-

Show all currently running activations

GET collections running

-

Show

GET

get_folder

Show all

GET all

get_all_folder

Create

POST

add_folder

Update

PUT

edit_folder

Bulk update

PUT bulk-update

-

Move

POST move

-

Delete

DEL

delete_folder

Show

GET

get_host

Show all

GET all

get_all_hosts

Create

POST

add_host

Create cluster host

POST clusters

-

Bulk create

POST bulk-create

-

Update

PUT

edit_host

Update cluster node

PUT nodes

-

Bulk update

PUT bulk-update

-

Rename

PUT rename

-

Move

POST move

-

Delete

DEL

delete_host

Bulk delete

DEL bulk-delete

delete_hosts

Show hosts of specific condition

GET all

-

Show

GET

-

Show all

GET all

get_all_hostgroups

Create

POST

add_hostgroup

Bulk create

POST bulk-create

-

Update

PUT

edit_hostgroup

Bulk update

PUT bulk-update

-

Delete

DEL

delete_hostgroup

Bulk delete

DEL bulk-delete

delete_hosts

Show

GET

get_hosttags

Create

POST

-

Update

PUT

set_hosttags

Delete

DEL

-

Show all

GET all

-

Create

POST

-

Delete

DEL

-

Bulk delete

DEL bulk-delete

-

Execute service discovery

POST

discover_services

Show services of specific state

GET

-

Update the service discovery state

PUT

-

Display services of a state on a host

GET

-

Display services of a state globally

GET all

-

Show

GET

-

Show all

GET all

get_all_servicegroups

Create

POST

add_servicegroup

Bulk create

POST bulk-create

-

Update

PUT

edit_servicegroup

Bulk update

PUT bulk-update

-

Delete

DEL

delete_servicegroup

Bulk delete

DEL bulk-delete

-

Show

-

get_ruleset

Show all

-

get_ruleset_info

Update

-

set_ruleset

Show BI rule

GET bi_rule

-

Update BI rule

PUT bi_rule

-

Delete BI rule

DEL bi_rule

-

Show BI aggregation

GET bi_aggregation

-

Update BI aggregation

PUT bi_aggregation

-

Delete BI aggregation

DEL bi_aggregation

-

Show BI pack

GET bi_pack

-

Show all BI packs

GET all bi_pack

-

Show

GET

-

Create

POST

-

Update

PUT

-

Delete

DEL

-

Show all

-

get_all_users

Bulk create

-

add_users

Bulk update

-

edit_users

Bulk delete

-

delete_users

Show

GET

-

Create

POST

-

Update

PUT

-

Delete

DEL

-

Show

GET

-

Show all

GET all

get_all_contactgroups

Create

POST

add_contactgroup

Bulk create

POST bulk-create

-

Update

PUT

edit_contactgroup

Bulk update

PUT bulk-update

-

Delete

DEL

delete_contactgroup

Bulk delete

DEL bulk-delete

-

Acknowledge for a host

POST host

-

Acknowledge for multiple hosts

POST host bulk-acknowledge

-

Acknowledge for hosts in a host group

POST hostgroup

-

Acknowledge for services on a host

-

Acknowledge for a service globally

POST service

-

Acknowledge for multiple services on a host

POST service bulk-acknowledge

-

Acknowledge for services of a service group

POST servicegroup

-

Show all agents

GET collections agent

-

Bake all agents

POST bake

bake_agents

Sign all agents

POST sign

-

Bake and sign all agents

POST bake_and_sign

-

Show the baking status

GET baking_status

-

Show the status of the automatic deployment

GET automatic-deployment

-

Download agent

GET agent

-

Show

-

get_site

Update

-

set_site

Delete

-

delete_site

Login

-

login_site

Logout

-

logout_site

Show version information

GET version

-

Show sites for a user

-

get_user_sites

Show host names of all sites

-

get_host_names

Show metrics for all services of a host

-

get_metrics_of_host

Show graph information for a service

-

get_graph_recipes

Show metrics for a graph

-

get_graph

Show Service Level Agreement (SLA) information

On this page