]> granicus.if.org Git - icinga2/blob - doc/12-icinga2-api.md
Change http:// links to https:// links where a website exists
[icinga2] / doc / 12-icinga2-api.md
1 # <a id="icinga2-api"></a> Icinga 2 API
2
3 ## <a id="icinga2-api-setup"></a> Setting up the API
4
5 You can run the CLI command `icinga2 api setup` to enable the
6 `api` [feature](11-cli-commands.md#enable-features) and set up
7 certificates as well as a new API user `root` with an auto-generated password in the
8 `/etc/icinga2/conf.d/api-users.conf` configuration file:
9
10     # icinga2 api setup
11
12 Make sure to restart Icinga 2 to enable the changes you just made:
13
14     # service icinga2 restart
15
16 If you prefer to set up the API manually, you will have to perform the following steps:
17
18 * Set up X.509 certificates for Icinga 2
19 * Enable the `api` feature (`icinga2 feature enable api`)
20 * Create an `ApiUser` object for authentication
21
22 The next chapter provides a quick overview of how you can use the API.
23
24 ## <a id="icinga2-api-introduction"></a> Introduction
25
26 The Icinga 2 API allows you to manage configuration objects
27 and resources in a simple, programmatic way using HTTP requests.
28
29 The URL endpoints are logically separated allowing you to easily
30 make calls to
31
32 * query, create, modify and delete [config objects](12-icinga2-api.md#icinga2-api-config-objects)
33 * perform [actions](12-icinga2-api.md#icinga2-api-actions) (reschedule checks, etc.)
34 * subscribe to [event streams](12-icinga2-api.md#icinga2-api-event-streams)
35 * [manage configuration packages](12-icinga2-api.md#icinga2-api-config-management)
36 * evaluate [script expressions](12-icinga2-api.md#icinga2-api-console)
37
38 ### <a id="icinga2-api-requests"></a> Requests
39
40 Any tool capable of making HTTP requests can communicate with
41 the API, for example [curl](https://curl.haxx.se/).
42
43 Requests are only allowed to use the HTTPS protocol so that
44 traffic remains encrypted.
45
46 By default the Icinga 2 API listens on port `5665` which is shared with
47 the cluster stack. The port can be changed by setting the `bind_port` attribute
48 for the [ApiListener](9-object-types.md#objecttype-apilistener)
49 object in the `/etc/icinga2/features-available/api.conf`
50 configuration file.
51
52 Supported request methods:
53
54   Method | Usage
55   -------|--------
56   GET    | Retrieve information about configuration objects. Any request using the GET method is read-only and does not affect any objects.
57   POST   | Update attributes of a specified configuration object.
58   PUT    | Create a new object. The PUT request must include all attributes required to create a new object.
59   DELETE | Remove an object created by the API. The DELETE method is idempotent and does not require any check if the object actually exists.
60
61 All requests apart from `GET` require that the following `Accept` header is set:
62
63     Accept: application/json
64
65 Each URL is prefixed with the API version (currently "/v1").
66
67 ### <a id="icinga2-api-responses"></a> Responses
68
69 Successful requests will send back a response body containing a `results`
70 list. Depending on the number of affected objects in your request, the
71 `results` list may contain more than one entry.
72
73 The output will be sent back as a JSON object:
74
75
76     {
77         "results": [
78             {
79                 "code": 200.0,
80                 "status": "Object was created."
81             }
82         ]
83     }
84
85 Tip: If you are working on the CLI with curl you can also use [jq](https://stedolan.github.io/jq/)
86 to format the returned JSON output in a readable manner. The documentation
87 prefers `python -m json.tool` as Python is available nearly everywhere.
88
89 > **Note**
90 >
91 > Future versions of Icinga 2 might set additional fields. Your application
92 > should gracefully handle fields it is not familiar with, for example by
93 > ignoring them.
94
95 ### <a id="icinga2-api-http-statuses"></a> HTTP Statuses
96
97 The API will return standard [HTTP statuses](https://www.ietf.org/rfc/rfc2616.txt)
98 including error codes.
99
100 When an error occurs, the response body will contain additional information
101 about the problem and its source.
102
103 A status code between 200 and 299 generally means that the request was
104 successful.
105
106 Return codes within the 400 range indicate that there was a problem with the
107 request. Either you did not authenticate correctly, you are missing the authorization
108 for your requested action, the requested object does not exist or the request
109 was malformed.
110
111 A status in the range of 500 generally means that there was a server-side problem
112 and Icinga 2 is unable to process your request.
113
114 ### <a id="icinga2-api-authentication"></a> Authentication
115
116 There are two different ways for authenticating against the Icinga 2 API:
117
118 * username and password using HTTP basic auth
119 * X.509 certificate
120
121 In order to configure a new API user you'll need to add a new [ApiUser](9-object-types.md#objecttype-apiuser)
122 configuration object. In this example `root` will be the basic auth username
123 and the `password` attribute contains the basic auth password.
124
125     # vim /etc/icinga2/conf.d/api-users.conf
126
127     object ApiUser "root" {
128       password = "icinga"
129     }
130
131 Alternatively you can use X.509 client certificates by specifying the `client_cn`
132 the API should trust. The X.509 certificate has to be signed by the CA certificate
133 that is configured in the [ApiListener](9-object-types.md#objecttype-apilistener) object.
134
135     # vim /etc/icinga2/conf.d/api-users.conf
136
137     object ApiUser "root" {
138       client_cn = "CertificateCommonName"
139     }
140
141 An `ApiUser` object can have both authentication methods configured.
142
143 You can test authentication by sending a GET request to the API:
144
145     $ curl -k -s -u root:icinga 'https://localhost:5665/v1'
146
147 In case you get an error message make sure to check the API user credentials.
148
149 When using client certificates for authentication you'll need to pass your client certificate
150 and private key to the curl call:
151
152     $ curl -k --cert example.localdomain.crt --key example.localdomain.key 'https://example.localdomain:5665/v1/status'
153
154 In case of an error make sure to verify the client certificate and CA.
155
156 The curl parameter `-k` disables certificate verification and should therefore
157 only be used for testing. In order to securely check each connection you'll need to
158 specify the trusted CA certificate using the curl parameter`--cacert`:
159
160     $ curl -u root:icinga --cacert ca.crt 'icinga2.node1.localdomain:5665/v1'
161
162 Read the next chapter on [API permissions](12-icinga2-api.md#icinga2-api-permissions)
163 in order to configure authorization settings for your newly created API user.
164
165 ### <a id="icinga2-api-permissions"></a> Permissions
166
167 By default an API user does not have any permissions to perform
168 actions on the URL endpoints.
169
170 Permissions for API users must be specified in the `permissions` attribute
171 as array. The array items can be a list of permission strings with wildcard
172 matches.
173
174 Example for an API user with all permissions:
175
176     permissions = [ "*" ]
177
178 Note that you can use wildcards. Here's another example that only allows the user
179 to perform read-only object queries for hosts and services:
180
181     permissions = [ "objects/query/Host", "objects/query/Service" ]
182
183 You can also further restrict permissions by specifying a filter expression. The
184 filter expression has to be a [lambda function](17-language-reference.md#nullary-lambdas)
185 which must return a boolean value.
186
187 The following example allows the API user to query all hosts and services which have a
188 custom attribute `os` that matches the regular expression `^Linux`.
189 The [regex function](18-library-reference.md#global-functions-regex) is available as global function.
190
191     permissions = [
192       {
193         permission = "objects/query/Host"
194         filter = {{ regex("^Linux", host.vars.os) }}
195       },
196       {
197         permission = "objects/query/Service"
198         filter = {{ regex("^Linux", service.vars.os) }}
199       }
200     ]
201
202 More information about filters can be found in the [filters](12-icinga2-api.md#icinga2-api-filters) chapter.
203
204 Available permissions for specific URL endpoints:
205
206   Permissions                   | URL Endpoint  | Supports Filters
207   ------------------------------|---------------|-----------------
208   actions/&lt;action&gt;        | /v1/actions   | Yes
209   config/query                  | /v1/config    | No
210   config/modify                 | /v1/config    | No
211   console                       | /v1/console   | No
212   events/&lt;type&gt;           | /v1/events    | No
213   objects/query/&lt;type&gt;    | /v1/objects   | Yes
214   objects/create/&lt;type&gt;   | /v1/objects   | No
215   objects/modify/&lt;type&gt;   | /v1/objects   | Yes
216   objects/delete/&lt;type&gt;   | /v1/objects   | Yes
217   status/query                  | /v1/status    | Yes
218   templates/&lt;type&gt;        | /v1/templates | Yes
219   types                         | /v1/types     | Yes
220   variables                     | /v1/variables | Yes
221
222 The required actions or types can be replaced by using a wildcard match ("\*").
223
224 ### <a id="icinga2-api-parameters"></a> Parameters
225
226 Depending on the request method there are two ways of
227 passing parameters to the request:
228
229 * JSON object as request body (all request methods other than `GET`)
230 * Query string as URL parameter (all request methods)
231
232 Reserved characters by the HTTP protocol must be [URL-encoded](https://en.wikipedia.org/wiki/Percent-encoding)
233 as query string, e.g. a space character becomes `%20`.
234
235 Example for a URL-encoded query string:
236
237     /v1/objects/hosts?filter=match(%22example.localdomain*%22,host.name)&attrs=name&attrs=state
238
239 Here are the exact same query parameters as a JSON object:
240
241     { "filter": "match(\"example.localdomain*\",host.name)", "attrs": [ "host.name", "host.state" ] }
242
243 The [match function](18-library-reference.md#global-functions-match) is available as global function
244 in Icinga 2.
245
246 ### <a id="icinga2-api-requests-method-override"></a> Request Method Override
247
248 `GET` requests do not allow you to send a request body. In case you cannot pass everything as URL
249 parameters (e.g. complex filters or JSON-encoded dictionaries) you can use the `X-HTTP-Method-Override`
250 header. This comes in handy when you are using HTTP proxies disallowing `PUT` or `DELETE` requests too.
251
252 Query an existing object by sending a `POST` request with `X-HTTP-Method-Override: GET` as request header:
253
254     $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: GET' 'https://localhost:5665/v1/objects/hosts'
255
256 Delete an existing object by sending a `POST` request with `X-HTTP-Method-Override: DELETE` as request header:
257
258     $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -X POST -H 'X-HTTP-Method-Override: DELETE' 'https://localhost:5665/v1/objects/hosts/example.localdomain'
259
260 ### <a id="icinga2-api-filters"></a> Filters
261
262 #### <a id="icinga2-api-simple-filters"></a> Simple Filters
263
264 By default actions and queries operate on all objects unless further restricted by the user. For
265 example, the following query returns all `Host` objects:
266
267     https://localhost:5665/v1/objects/hosts
268
269 If you're only interested in a single object, you can limit the output to that object by specifying its name:
270
271     https://localhost:5665/v1/objects/hosts?host=localhost
272
273 **The name of the URL parameter is the lower-case version of the type the query applies to.** For
274 example, for `Host` objects the URL parameter therefore is `host`, for `Service` objects it is
275 `service` and so on.
276
277 You can also specify multiple objects:
278
279     https://localhost:5665/v1/objects/hosts?hosts=first-host&hosts=second-host
280
281 Again -- like in the previous example -- the name of the URL parameter is the lower-case version of the type. However, because we're specifying multiple objects here the **plural form** of the type is used.
282
283 When specifying names for objects which have composite names like for example services the
284 full name has to be used:
285
286     https://localhost:5665/v1/objects/services?service=localhost!ping6
287
288 The full name of an object can be obtained by looking at the `__name` attribute.
289
290 #### <a id="icinga2-api-advanced-filters"></a> Advanced Filters
291
292 Most of the information provided in this chapter applies to both permission filters (as used when
293 configuring `ApiUser` objects) and filters specified in queries.
294
295 Advanced filters allow users to filter objects using lambda expressions. The syntax for these filters is the same like for [apply rule expressions](3-monitoring-basics.md#using-apply-expressions).
296
297 > **Note**
298 >
299 > Filters used as URL parameter must be URL-encoded. The following examples
300 > are **not URL-encoded** for better readability.
301
302 Example matching all services in NOT-OK state:
303
304     https://localhost:5665/v1/objects/services?filter=service.state!=ServiceOK
305
306 Example [matching](18-library-reference.md#global-functions-match) all hosts by a name string pattern:
307
308     https://localhost:5665/v1/objects/hosts?filter=match("example.localdomain*",host.name)
309
310 Example for all hosts which are in the host group `linux-servers`:
311
312     https://localhost:5665/v1/objects/hosts?filter="linux-servers" in host.groups
313
314 User-specified filters are run in a sandbox environment which ensures that filters cannot
315 modify Icinga's state, for example object attributes or global variables.
316
317 When querying objects of a specific type the filter expression is evaluated for each object
318 of that type. The object is made available to the filter expression as a variable whose name
319 is the lower-case version of the object's type name.
320
321 For example when querying objects of type `Host` the variable in the filter expression is named
322 `host`. Additionally related objects such as the host's check command are also made available
323 (e.g., via the `check_command` variable). The variable names are the exact same as for the `joins`
324 query parameter; see [object query joins](12-icinga2-api.md#icinga2-api-config-objects-query-joins)
325 for details.
326
327 The object is also made available via the `obj` variable. This makes it easier to build
328 filters which can be used for more than one object type (e.g., for permissions).
329
330 Some queries can be performed for more than just one object type. One example is the 'reschedule-check'
331 action which can be used for both hosts and services. When using advanced filters you will also have to specify the
332 type using the `type` parameter:
333
334     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
335     -d '{ "type": "Service", "filter": "service.name==\"ping6\"" }' | python -m json.tool
336
337 When building filters you have to ensure that values such as
338 `"linux-servers"` are escaped properly according to the rules of the Icinga 2 configuration
339 language.
340
341 To make using the API in scripts easier you can use the `filter_vars` attribute to specify
342 variables which should be made available to your filter expression. This way you don't have
343 to worry about escaping values:
344
345     $ curl -k -s -u 'root:icinga' -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5665/v1/objects/hosts' \
346     -d '{ "filter": "host.vars.os == os", "filter_vars": { "os": "Linux" } }'
347
348 We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override) here because
349 the HTTP specification does not allow message bodies for GET requests.
350
351 The `filters_vars` attribute can only be used inside the request body, but not as
352 a URL parameter because there is no way to specify a dictionary in a URL.
353
354 ## <a id="icinga2-api-config-objects"></a> Config Objects
355
356 Provides methods to manage configuration objects:
357
358 * [creating objects](12-icinga2-api.md#icinga2-api-config-objects-create)
359 * [querying objects](12-icinga2-api.md#icinga2-api-config-objects-query)
360 * [modifying objects](12-icinga2-api.md#icinga2-api-config-objects-modify)
361 * [deleting objects](12-icinga2-api.md#icinga2-api-config-objects-delete)
362
363 ### <a id="icinga2-api-config-objects-cluster-sync"></a> API Objects and Cluster Config Sync
364
365 Newly created or updated objects can be synced throughout your
366 Icinga 2 cluster. Set the `zone` attribute to the zone this object
367 belongs to and let the API and cluster handle the rest.
368
369 Objects without a zone attribute are only synced in the same zone the Icinga instance belongs to.
370
371 > **Note**
372 >
373 > Cluster nodes must accept configuration for creating, modifying
374 > and deleting objects. Ensure that `accept_config` is set to `true`
375 > in the [ApiListener](9-object-types.md#objecttype-apilistener) object
376 > on each node.
377
378 If you add a new cluster instance, or reconnect an instance which has been offline
379 for a while, Icinga 2 takes care of the initial object sync for all objects
380 created by the API.
381
382 ### <a id="icinga2-api-config-objects-query"></a> Querying Objects
383
384 You can request information about configuration objects by sending
385 a `GET` query to the `/v1/objects/<type>` URL endpoint. `<type` has
386 to be replaced with the plural name of the object type you are interested
387 in:
388
389     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts'
390
391 A list of all available configuration types is available in the
392 [object types](9-object-types.md#object-types) chapter.
393
394 The following URL parameters are available:
395
396   Parameters | Type         | Description
397   -----------|--------------|----------------------------
398   attrs      | string array | **Optional.** Limits attributes in the output.
399   joins      | string array | **Optional.** Join related object types and their attributes (`?joins=host` for the entire set, or selectively by `?joins=host.name`).
400   meta       | string array | **Optional.** Enable meta information using `?meta=used_by` (references from other objects) and/or `?meta=location` (location information). Defaults to disabled.
401
402 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) may be provided.
403
404 Instead of using a filter you can optionally specify the object name in the
405 URL path when querying a single object. For objects with composite names
406 (e.g. services) the full name (e.g. `example.localdomain!http`) must be specified:
407
408     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services/example.localdomain!http'
409
410 You can limit the output to specific attributes using the `attrs` URL parameter:
411
412     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/hosts/example.localdomain?attrs=name&attrs=address' | python -m json.tool
413     {
414         "results": [
415             {
416                 "attrs": {
417                     "name": "example.localdomain"
418                     "address": "192.168.1.1"
419                 },
420                 "joins": {},
421                 "meta": {},
422                 "name": "example.localdomain",
423                 "type": "Host"
424             }
425         ]
426     }
427
428 #### <a id="icinga2-api-config-objects-query-result"></a> Object Queries Result
429
430 Each response entry in the results array contains the following attributes:
431
432   Attribute  | Type       | Description
433   -----------|------------|--------------
434   name       | string     | Full object name.
435   type       | string     | Object type.
436   attrs      | dictionary | Object attributes (can be filtered using the URL parameter `attrs`).
437   joins      | dictionary | [Joined object types](12-icinga2-api.md#icinga2-api-config-objects-query-joins) as key, attributes as nested dictionary. Disabled by default.
438   meta       | dictionary | Contains `used_by` object references. Disabled by default, enable it using `?meta=used_by` as URL parameter.
439
440 #### <a id="icinga2-api-config-objects-query-joins"></a> Object Query Joins
441
442 Icinga 2 knows about object relations. For example it can optionally return
443 information about the host when querying service objects.
444
445 The following query retrieves all host attributes:
446
447     https://localhost:5665/v1/objects/services?joins=host
448
449 Instead of requesting all host attributes you can also limit the output to specific
450 attributes:
451
452     https://localhost:5665/v1/objects/services?joins=host.name&joins=host.address
453
454 You can request that all available joins are returned in the result set by using
455 the `all_joins` query parameter.
456
457     https://localhost:5665/v1/objects/services?all_joins=1
458
459 > **Note**
460 >
461 > For performance reasons you should only request attributes which your application
462 > requires.
463
464 The following joins are available:
465
466   Object Type  | Object Relations (`joins` prefix name)
467   -------------|------------------------------------------
468   Service      | host, check\_command, check\_period, event\_command, command\_endpoint
469   Host         | check\_command, check\_period, event\_command, command\_endpoint
470   Notification | host, service, command, period
471   Dependency   | child\_host, child\_service, parent\_host, parent\_service, period
472   User         | period
473   Zones        | parent
474
475 Here's an example that retrieves all service objects for hosts which have had their `os`
476 custom attribute set to `Linux`. The result set contains the `display_name` and `check_command`
477 attributes for the service. The query also returns the host's `name` and `address` attribute
478 via a join:
479
480     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/objects/services?attrs=display_name&attrs=check_command&joins=host.name&joins=host.address&filter=host.vars.os==%22Linux%22' | python -m json.tool
481
482     {
483         "results": [
484             {
485                 "attrs": {
486                     "check_command": "ping4",
487                     "display_name": "ping4"
488                 },
489                 "joins": {
490                     "host": {
491                         "address": "192.168.1.1",
492                         "name": "example.localdomain"
493                     }
494                 },
495                 "meta": {},
496                 "name": "example.localdomain!ping4",
497                 "type": "Service"
498             },
499             {
500                 "attrs": {
501                     "check_command": "ssh",
502                     "display_name": "ssh"
503                 },
504                 "joins": {
505                     "host": {
506                         "address": "192.168.1.1",
507                         "name": "example.localdomain"
508                     }
509                 },
510                 "meta": {},
511                 "name": "example.localdomain!ssh",
512                 "type": "Service"
513             }
514         ]
515     }
516
517 In case you want to fetch all [comments](9-object-types.md#objecttype-comment)
518 for hosts and services, you can use the following query URL (similar example
519 for downtimes):
520
521    https://localhost:5665/v1/objects/comments?joins=host&joins=service
522
523 This is another example for listing all service objects which are unhandled problems (state is not OK
524 and no downtime or acknowledgement set). We're using [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
525 here because we want to pass all query attributes in the request body.
526
527    $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://127.0.0.1:5665/v1/objects/services' \
528     -d '{ "joins": [ "host.name", "host.address" ], "attrs": [ "name", "state", "downtime_depth", "acknowledgement" ], "filter": "service.state != ServiceOK && service.downtime_depth == 0.0 && service.acknowledgement == 0.0" }' | python -m json.tool
529
530     {
531         "results": [
532             {
533                 "attrs": {
534                     "acknowledgement": 0.0,
535                     "downtime_depth": 0.0,
536                     "name": "10807-service",
537                     "state": 3.0
538                 },
539                 "joins": {
540                     "host": {
541                         "address": "",
542                         "name": "10807-host"
543                     }
544                 },
545                 "meta": {},
546                 "name": "10807-host!10807-service",
547                 "type": "Service"
548             }
549         ]
550     }
551
552
553 ### <a id="icinga2-api-config-objects-create"></a> Creating Config Objects
554
555 New objects must be created by sending a PUT request. The following
556 parameters need to be passed inside the JSON body:
557
558   Parameters | Type         | Description
559   -----------|--------------|--------------------------
560   templates  | string array | **Optional.** Import existing configuration templates for this object type. Note: These templates must either be statically configured or provided in [config packages](12-icinga2-api.md#icinga2-api-config-management)-
561   attrs      | dictionary   | **Required.** Set specific object attributes for this [object type](9-object-types.md#object-types).
562
563 The object name must be specified as part of the URL path. For objects with composite names (e.g. services)
564 the full name (e.g. `example.localdomain!http`) must be specified.
565
566 If attributes are of the Dictionary type, you can also use the indexer format. This might be necessary to only override specific custom variables and keep all other existing custom variables (e.g. from templates):
567
568     "attrs": { "vars.os": "Linux" }
569
570 Example for creating the new host object `example.localdomain`:
571
572     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
573     -d '{ "templates": [ "generic-host" ], "attrs": { "address": "192.168.1.1", "check_command": "hostalive", "vars.os" : "Linux" } }' \
574     | python -m json.tool
575     {
576         "results": [
577             {
578                 "code": 200.0,
579                 "status": "Object was created."
580             }
581         ]
582     }
583
584 If the configuration validation fails, the new object will not be created and the response body
585 contains a detailed error message. The following example is missing the `check_command` attribute
586 which is required for host objects:
587
588     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
589     -d '{ "attrs": { "address": "192.168.1.1", "vars.os" : "Linux" } }' \
590     | python -m json.tool
591     {
592         "results": [
593             {
594                 "code": 500.0,
595                 "errors": [
596                     "Error: Validation failed for object 'example.localdomain' of type 'Host'; Attribute 'check_command': Attribute must not be empty."
597                 ],
598                 "status": "Object could not be created."
599             }
600         ]
601     }
602
603 Service objects must be created using their full name ("hostname!servicename") referencing an existing host object:
604
605     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/services/example.localdomain!realtime-load' \
606     -d '{ "templates": [ "generic-service" ], "attrs": { "check_command": "load", "check_interval": 1,"retry_interval": 1 } }'
607
608
609 Example for a new CheckCommand object:
610
611     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X PUT 'https://localhost:5665/v1/objects/checkcommands/mytest' \
612     -d '{ "templates": [ "plugin-check-command" ], "attrs": { "command": [ "/usr/local/sbin/check_http" ], "arguments": { "-I": "$mytest_iparam$" } } }'
613
614
615 ### <a id="icinga2-api-config-objects-modify"></a> Modifying Objects
616
617 Existing objects must be modified by sending a `POST` request. The following
618 parameters need to be passed inside the JSON body:
619
620   Parameters | Type       | Description
621   -----------|------------|---------------------------
622   attrs      | dictionary | **Required.** Set specific object attributes for this [object type](9-object-types.md#object-types).
623
624 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) should be provided.
625
626 > **Note**:
627 >
628 > Modified attributes do not trigger a re-evaluation of existing
629 > static [apply rules](3-monitoring-basics.md#using-apply) and [group assignments](3-monitoring-basics.md#group-assign-intro).
630 > Delete and re-create the objects if you require such changes.
631 >
632 > Furthermore you cannot modify templates which have already been resolved
633 > during [object creation](12-icinga2-api.md#icinga2-api-config-objects-create).
634 > There are attributes which can only be set for [PUT requests](12-icinga2-api.md#icinga2-api-config-objects-create) such as `groups`
635 > or `zone`. A complete list of `no_user_modify` attributes can be fetched from the [types](12-icinga2-api.md#icinga2-api-types) URL endpoint.
636
637 If attributes are of the Dictionary type, you can also use the indexer format:
638
639     "attrs": { "vars.os": "Linux" }
640
641 The following example updates the `address` attribute and the custom attribute `os` for the `example.localdomain` host:
642
643     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/hosts/example.localdomain' \
644     -d '{ "attrs": { "address": "192.168.1.2", "vars.os" : "Windows" } }' \
645     | python -m json.tool
646     {
647         "results": [
648             {
649                 "code": 200.0,
650                 "name": "example.localdomain",
651                 "status": "Attributes updated.",
652                 "type": "Host"
653             }
654         ]
655     }
656
657
658 ### <a id="icinga2-api-config-objects-delete"></a> Deleting Objects
659
660 You can delete objects created using the API by sending a `DELETE`
661 request.
662
663   Parameters | Type    | Description
664   -----------|---------|---------------
665   cascade    | boolean |  **Optional.** Delete objects depending on the deleted objects (e.g. services on a host).
666
667 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) should be provided.
668
669 Example for deleting the host object `example.localdomain`:
670
671     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE 'https://localhost:5665/v1/objects/hosts/example.localdomain?cascade=1' | python -m json.tool
672     {
673         "results": [
674             {
675                 "code": 200.0,
676                 "name": "example.localdomain",
677                 "status": "Object was deleted.",
678                 "type": "Host"
679             }
680         ]
681     }
682
683 ## <a id="icinga2-api-config-templates"></a> Config Templates
684
685 Provides methods to manage configuration templates:
686
687 * [querying templates](12-icinga2-api.md#icinga2-api-config-templates-query)
688
689 Creation, modification and deletion of templates at runtime is not supported.
690
691 ### <a id="icinga2-api-config-templates-query"></a> Querying Templates
692
693 You can request information about configuration templates by sending
694 a `GET` query to the `/v1/templates/<type>` URL endpoint. `<type` has
695 to be replaced with the plural name of the object type you are interested
696 in:
697
698     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts'
699
700 A list of all available configuration types is available in the
701 [object types](9-object-types.md#object-types) chapter.
702
703 A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
704 template object can be accessed in the filter using the `tmpl` variable. In this
705 example the [match function](18-library-reference.md#global-functions-match) is used to
706 check a wildcard string pattern against `tmpl.name`.
707 The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
708 here.
709
710     $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/templates/hosts' \
711     -d '{ "filter": "match(\"g*\", tmpl.name)" }'
712
713 Instead of using a filter you can optionally specify the template name in the
714 URL path when querying a single object:
715
716     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/templates/hosts/generic-host'
717
718 The result set contains the type, name as well as the location of the template.
719
720 ## <a id="icinga2-api-variables"></a> Variables
721
722 Provides methods to manage global variables:
723
724 * [querying variables](12-icinga2-api.md#icinga2-api-variables-query)
725
726 ### <a id="icinga2-api-variables-query"></a> Querying Variables
727
728 You can request information about global variables by sending
729 a `GET` query to the `/v1/variables/` URL endpoint:
730
731     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables'
732
733 A [filter](12-icinga2-api.md#icinga2-api-filters) may be provided for this query type. The
734 variable information object can be accessed in the filter using the `variable` variable.
735 The `filter` attribute is passed inside the request body thus requiring to use [X-HTTP-Method-Override](12-icinga2-api.md#icinga2-api-requests-method-override)
736 here.
737
738     $ curl -k -s -u root:icinga -H 'Accept: application/json' -H 'X-HTTP-Method-Override: GET' -X POST 'https://localhost:5661/v1/variables' \
739     -d '{ "filter": "variable.type in [ \"String\", \"Number\" ]" }'
740
741 Instead of using a filter you can optionally specify the variable name in the
742 URL path when querying a single variable:
743
744     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/variables/PrefixDir'
745
746 The result set contains the type, name and value of the global variable.
747
748 ## <a id="icinga2-api-actions"></a> Actions
749
750 There are several actions available for Icinga 2 provided by the `/v1/actions`
751 URL endpoint. You can run actions by sending a `POST` request.
752
753 In case you have been using the [external commands](14-features.md#external-commands)
754 in the past, the API actions provide a similar interface with filter
755 capabilities for some of the more common targets which do not directly change
756 the configuration.
757
758 All actions return a 200 `OK` or an appropriate error code for each
759 action performed on each object matching the supplied filter.
760
761 Actions which affect the Icinga Application itself such as disabling
762 notification on a program-wide basis must be applied by updating the
763 [IcingaApplication object](12-icinga2-api.md#icinga2-api-config-objects)
764 called `app`.
765
766     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/objects/icingaapplications/app' -d '{ "attrs": { "enable_notifications": false } }'
767
768 ### <a id="icinga2-api-actions-process-check-result"></a> process-check-result
769
770 Process a check result for a host or a service.
771
772 Send a `POST` request to the URL endpoint `/v1/actions/process-check-result`.
773
774   Parameter         | Type         | Description
775   ------------------|--------------|--------------
776   exit\_status      | integer      | **Required.** For services: 0=OK, 1=WARNING, 2=CRITICAL, 3=UNKNOWN, for hosts: 0=OK, 1=CRITICAL.
777   plugin\_output    | string       | **Required.** The plugins main output. Does **not** contain the performance data.
778   performance\_data | string array | **Optional.** The performance data.
779   check\_command    | string array | **Optional.** The first entry should be the check commands path, then one entry for each command line option followed by an entry for each of its argument.
780   check\_source     | string       | **Optional.** Usually the name of the `command_endpoint`
781
782 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
783
784 Example for the service `passive-ping6`:
785
786     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result?service=example.localdomain!passive-ping6' \
787     -d '{ "exit_status": 2, "plugin_output": "PING CRITICAL - Packet loss = 100%", "performance_data": [ "rta=5000.000000ms;3000.000000;5000.000000;0.000000", "pl=100%;80;100;0" ], "check_source": "example.localdomain" }' | python -m json.tool
788
789     {
790         "results": [
791             {
792                 "code": 200.0,
793                 "status": "Successfully processed check result for object 'localdomain!passive-ping6'."
794             }
795         ]
796     }
797
798 Example for using the `Host` type and filter by the host name:
799
800     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result' \
801     -d '{ "filter": "host.name==\"example.localdomain\"", "type": "Host", "exit_status": 1, "plugin_output": "Host is not available." }'
802
803 You can avoid URL encoding of white spaces in object names by using the `filter` attribute in the request body.
804
805 ### <a id="icinga2-api-actions-reschedule-check"></a> reschedule-check
806
807 Reschedule a check for hosts and services. The check can be forced if required.
808
809 Send a `POST` request to the URL endpoint `/v1/actions/reschedule-check`.
810
811   Parameter    | Type      | Description
812   -------------|-----------|--------------
813   next\_check  | timestamp | **Optional.** The next check will be run at this time. If omitted, the current time is used.
814   force\_check | boolean   | **Optional.** Defaults to `false`. If enabled, the checks are executed regardless of time period restrictions and checks being disabled per object or on a global basis.
815
816 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
817
818 The example reschedules all services with the name "ping6" to immediately perform a check
819 (`next_check` default), ignoring any time periods or whether active checks are
820 allowed for the service (`force_check=true`).
821
822     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/reschedule-check' \
823     -d '{ "type": "Service", "filter": "service.name==\"ping6\"", "force_check": true }' | python -m json.tool
824
825     {
826         "results": [
827             {
828                 "code": 200.0,
829                 "status": "Successfully rescheduled check for object 'example.localdomain!ping6'."
830             }
831         ]
832     }
833
834
835 ### <a id="icinga2-api-actions-send-custom-notification"></a> send-custom-notification
836
837 Send a custom notification for hosts and services. This notification
838 type can be forced being sent to all users.
839
840 Send a `POST` request to the URL endpoint `/v1/actions/send-custom-notification`.
841
842   Parameter | Type    | Description
843   ----------|---------|--------------
844   author    | string  | **Required.** Name of the author, may be empty.
845   comment   | string  | **Required.** Comment text, may be empty.
846   force     | boolean | **Optional.** Default: false. If true, the notification is sent regardless of downtimes or whether notifications are enabled or not.
847
848 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
849
850 Example for a custom host notification announcing a global maintenance to
851 host owners:
852
853     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/send-custom-notification' \
854     -d '{ "type": "Host", "author": "icingaadmin", "comment": "System is going down for maintenance", "force": true }' | python -m json.tool
855
856     {
857         "results": [
858             {
859                 "code": 200.0,
860                 "status": "Successfully sent custom notification for object 'host0'."
861             },
862             {
863                 "code": 200.0,
864                 "status": "Successfully sent custom notification for object 'host1'."
865             }
866     }
867
868 ### <a id="icinga2-api-actions-delay-notification"></a> delay-notification
869
870 Delay notifications for a host or a service.
871 Note that this will only have an effect if the service stays in the same problem
872 state that it is currently in. If the service changes to another state, a new
873 notification may go out before the time you specify in the `timestamp` argument.
874
875 Send a `POST` request to the URL endpoint `/v1/actions/delay-notification`.
876
877   Parameter | Type      | Description
878   ----------|-----------|--------------
879   timestamp | timestamp | **Required.** Delay notifications until this timestamp.
880
881 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
882
883 Example:
884
885     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/delay-notification' \
886     -d '{ "type": "Service", "timestamp": 1446389894 }' | python -m json.tool
887
888     {
889         "results": [
890             {
891                 "code": 200.0,
892                 "status": "Successfully delayed notifications for object 'host0!service0'."
893             },
894             {
895                 "code": 200.0,
896                 "status": "Successfully delayed notifications for object 'host1!service1'."
897             }
898     }
899
900 ### <a id="icinga2-api-actions-acknowledge-problem"></a> acknowledge-problem
901
902 Allows you to acknowledge the current problem for hosts or services. By
903 acknowledging the current problem, future notifications (for the same state if `sticky` is set to `false`)
904 are disabled.
905
906 Send a `POST` request to the URL endpoint `/v1/actions/acknowledge-problem`.
907
908   Parameter | Type      | Description
909   ----------|-----------|--------------
910   author    | string    | **Required.** Name of the author, may be empty.
911   comment   | string    | **Required.** Comment text, may be empty.
912   expiry    | timestamp | **Optional.** Whether the acknowledgement will be removed at the timestamp.
913   sticky    | boolean   | **Optional.** Whether the acknowledgement will be set until the service or host fully recovers. Defaults to `false`.
914   notify    | boolean   | **Optional.** Whether a notification of the `Acknowledgement` type will be sent. Defaults to `false`.
915
916 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
917
918 The following example acknowledges all services which are in a hard critical state and sends out
919 a notification for them:
920
921     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/acknowledge-problem?type=Service&filter=service.state==2&service.state_type=1' \
922     -d '{ "author": "icingaadmin", "comment": "Global outage. Working on it.", "notify": true }' | python -m json.tool
923
924     {
925         "results": [
926             {
927                 "code": 200.0,
928                 "status": "Successfully acknowledged problem for object 'example2.localdomain!ping4'."
929             },
930             {
931                 "code": 200.0,
932                 "status": "Successfully acknowledged problem for object 'example.localdomain!ping4'."
933             }
934     }
935
936
937 ### <a id="icinga2-api-actions-remove-acknowledgement"></a> remove-acknowledgement
938
939 Removes the acknowledgements for services or hosts. Once the acknowledgement has
940 been removed notifications will be sent out again.
941
942 Send a `POST` request to the URL endpoint `/v1/actions/remove-acknowledgement`.
943
944 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
945
946 The example removes all service acknowledgements:
947
948     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-acknowledgement?type=Service' | python -m json.tool
949
950     {
951         "results": [
952             {
953                 "code": 200.0,
954                 "status": "Successfully removed acknowledgement for object 'host0!service0'."
955             },
956             {
957                 "code": 200.0,
958                 "status": "Successfully removed acknowledgement for object 'example2.localdomain!aws-health'."
959             }
960     }
961
962 ### <a id="icinga2-api-actions-add-comment"></a> add-comment
963
964 Adds a `comment` from an `author` to services or hosts.
965
966 Send a `POST` request to the URL endpoint `/v1/actions/add-comment`.
967
968   Parameter | Type   | Description
969   ----------|--------|--------------
970   author    | string | **Required.** Name of the author, may be empty.
971   comment   | string | **Required.** Comment text, may be empty.
972
973 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
974
975 The following example adds a comment for all `ping4` services:
976
977     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/add-comment?type=Service&filter=service.name==%22ping4%22' -d '{ "author": "icingaadmin", "comment": "Troubleticket #123456789 opened." }' | python -m json.tool
978     {
979         "results": [
980             {
981                 "code": 200.0,
982                 "legacy_id": 26.0,
983                 "name": "example.localdomain!ping4!example.localdomain-1446824161-0",
984                 "status": "Successfully added comment 'example.localdomain!ping4!example.localdomain-1446824161-0' for object 'example.localdomain!ping4'."
985             },
986             {
987                 "code": 200.0,
988                 "legacy_id": 27.0,
989                 "name": "example2.localdomain!ping4!example.localdomain-1446824161-1",
990                 "status": "Successfully added comment 'example2.localdomain!ping4!example.localdomain-1446824161-1' for object 'example2.localdomain!ping4'."
991             }
992         ]
993     }
994
995 ### <a id="icinga2-api-actions-remove-comment"></a> remove-comment
996
997 Remove the comment using its `name` attribute , returns `OK` if the
998 comment did not exist.
999 **Note**: This is **not** the legacy ID but the comment name returned by
1000 Icinga 2 when [adding a comment](12-icinga2-api.md#icinga2-api-actions-add-comment).
1001
1002 Send a `POST` request to the URL endpoint `/v1/actions/remove-comment`.
1003
1004 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host`, `Service` and `Comment`.
1005
1006 Example for a simple filter using the `comment` URL parameter:
1007
1008     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?comment=example2.localdomain!ping4!mbmif.local-1446986367-0' | python -m json.tool
1009     {
1010         "results": [
1011             {
1012                 "code": 200.0,
1013                 "status": "Successfully removed comment 'example2.localdomain!ping4!mbmif.local-1446986367-0'."
1014             }
1015         ]
1016     }
1017
1018 Example for removing all service comments using a service name filter for `ping4`:
1019
1020     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-comment?filter=service.name==%22ping4%22&type=Service' | python -m json.tool
1021     {
1022         "results": [
1023             {
1024                 "code": 200.0,
1025                 "status": "Successfully removed all comments for object 'example2.localdomain!ping4'."
1026             },
1027             {
1028                 "code": 200.0,
1029                 "status": "Successfully removed all comments for object 'example.localdomain!ping4'."
1030             }
1031         ]
1032     }
1033
1034
1035 ### <a id="icinga2-api-actions-schedule-downtime"></a> schedule-downtime
1036
1037 Schedule a downtime for hosts and services.
1038
1039 Send a `POST` request to the URL endpoint `/v1/actions/schedule-downtime`.
1040
1041   Parameter     | Type      | Description
1042   --------------|-----------|--------------
1043   author        | string    | **Required.** Name of the author.
1044   comment       | string    | **Required.** Comment text.
1045   start\_time   | timestamp | **Required.** Timestamp marking the beginning of the downtime.
1046   end\_time     | timestamp | **Required.** Timestamp marking the end of the downtime.
1047   fixed         | boolean   | **Optional.** Defaults to `true`. If true, the downtime is `fixed` otherwise `flexible`. See [downtimes](8-advanced-topics.md#downtimes) for more information.
1048   duration      | integer   | **Required for flexible downtimes.** Duration of the downtime in seconds if `fixed` is set to false.
1049   trigger\_name | string    | **Optional.** Sets the trigger for a triggered downtime. See [downtimes](8-advanced-topics.md#downtimes) for more information on triggered downtimes.
1050   child\_options | integer  | **Optional.** Schedule child downtimes. `0` does not do anything, `1` schedules child downtimes triggered by this downtime, `2` schedules non-triggered downtimes. Defaults to `0`.
1051
1052 In addition to these parameters a [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host` and `Service`.
1053
1054 Example:
1055
1056     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/schedule-downtime?type=Service&filter=service.name==%22ping4%22' -d '{ "start_time": 1446388806, "end_time": 1446389806, "duration": 1000, "author": "icingaadmin", "comment": "IPv4 network maintenance" }' | python -m json.tool
1057     {
1058         "results": [
1059             {
1060                 "code": 200.0,
1061                 "legacy_id": 2.0,
1062                 "name": "example2.localdomain!ping4!example.localdomain-1446822004-0",
1063                 "status": "Successfully scheduled downtime 'example2.localdomain!ping4!example.localdomain-1446822004-0' for object 'example2.localdomain!ping4'."
1064             },
1065             {
1066                 "code": 200.0,
1067                 "legacy_id": 3.0,
1068                 "name": "example.localdomain!ping4!example.localdomain-1446822004-1",
1069                 "status": "Successfully scheduled downtime 'example.localdomain!ping4!example.localdomain-1446822004-1' for object 'example.localdomain!ping4'."
1070             }
1071         ]
1072     }
1073
1074 ### <a id="icinga2-api-actions-remove-downtime"></a> remove-downtime
1075
1076 Remove the downtime using its `name` attribute , returns `OK` if the
1077 downtime did not exist.
1078 **Note**: This is **not** the legacy ID but the downtime name returned by
1079 Icinga 2 when [scheduling a downtime](12-icinga2-api.md#icinga2-api-actions-schedule-downtime).
1080
1081 Send a `POST` request to the URL endpoint `/v1/actions/remove-downtime`.
1082
1083 A [filter](12-icinga2-api.md#icinga2-api-filters) must be provided. The valid types for this action are `Host`, `Service` and `Downtime`.
1084
1085 Example for a simple filter using the `downtime` URL parameter:
1086
1087     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?downtime=example.localdomain!ping4!mbmif.local-1446979168-6' | python -m json.tool
1088     {
1089         "results": [
1090             {
1091                 "code": 200.0,
1092                 "status": "Successfully removed downtime 'example.localdomain!ping4!mbmif.local-1446979168-6'."
1093             }
1094         ]
1095     }
1096
1097 Example for removing all host downtimes using a host name filter for `example.localdomain`:
1098
1099     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime?filter=host.name==%22example.localdomain%22&type=Host' | python -m json.tool
1100     {
1101         "results": [
1102             {
1103                 "code": 200.0,
1104                 "status": "Successfully removed all downtimes for object 'example.localdomain'."
1105             }
1106         ]
1107     }
1108
1109 Example for removing a downtime from a host but not the services filtered by the author name. This example uses
1110 filter variables explained in the [advanced filters](12-icinga2-api.md#icinga2-api-advanced-filters) chapter.
1111
1112     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/remove-downtime' \
1113             -d $'{
1114       "type": "Downtime",
1115       "filter": "host.name == filterHost && !service && downtime.author == filterAuthor",
1116       "filter_vars": {
1117         "filterHost": "example.localdomain",
1118         "filterAuthor": "icingaadmin"
1119       }
1120     }' | python -m json.tool
1121
1122     {
1123         "results": [
1124             {
1125                 "code": 200.0,
1126                 "status": "Successfully removed downtime 'example.localdomain!mbmif.local-1463043129-3'."
1127             }
1128         ]
1129     }
1130
1131 ### <a id="icinga2-api-actions-shutdown-process"></a> shutdown-process
1132
1133 Shuts down Icinga2. May or may not return.
1134
1135 Send a `POST` request to the URL endpoint `/v1/actions/shutdown-process`.
1136
1137 This action does not support a target type or filter.
1138
1139 Example:
1140
1141     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/shutdown-process' | python -m json.tool
1142
1143     {
1144         "results": [
1145             {
1146                 "code": 200.0,
1147                 "status": "Shutting down Icinga 2."
1148             }
1149         ]
1150     }
1151
1152 ### <a id="icinga2-api-actions-restart-process"></a> restart-process
1153
1154 Restarts Icinga2. May or may not return.
1155
1156 Send a `POST` request to the URL endpoint `/v1/actions/restart-process`.
1157
1158 This action does not support a target type or filter.
1159
1160 Example:
1161
1162     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/restart-process' | python -m json.tool
1163
1164     {
1165         "results": [
1166             {
1167                 "code": 200.0,
1168                 "status": "Restarting Icinga 2."
1169             }
1170         ]
1171     }
1172
1173 ### <a id="icinga2-api-actions-generate-ticket"></a> generate-ticket
1174
1175 Generates a PKI ticket for [CSR auto-signing](6-distributed-monitoring.md#distributed-monitoring-setup-csr-auto-signing).
1176 This can be used in combination with satellite/client setups requesting this ticket number.
1177
1178 Send a `POST` request to the URL endpoint `/v1/actions/generate-ticket`.
1179
1180   Parameter     | Type      | Description
1181   --------------|-----------|--------------
1182   cn            | string    | **Required.** The host's common name for which the ticket should be geenerated.
1183
1184 Example:
1185
1186     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/generate-ticket' \
1187     -d '{ "cn": "icinga2-client1.localdomain" }' | python -m json.tool
1188     {
1189         "results": [
1190             {
1191                 "code": 200.0,
1192                 "status": "Generated PKI ticket '4f75d2ecd253575fe9180938ebff7cbca262f96e' for common name 'icinga2-client1.localdomain'.",
1193                 "ticket": "4f75d2ecd253575fe9180938ebff7cbca262f96e"
1194             }
1195         ]
1196     }
1197
1198
1199 ## <a id="icinga2-api-event-streams"></a> Event Streams
1200
1201 You can subscribe to event streams by sending a `POST` request to the URL endpoint `/v1/events`.
1202 The following parameters need to be specified (either as URL parameters or in a JSON-encoded message body):
1203
1204   Parameter  | Type         | Description
1205   -----------|--------------|-------------
1206   types      | string array | **Required.** Event type(s). Multiple types as URL parameters are supported.
1207   queue      | string       | **Required.** Unique queue name. Multiple HTTP clients can use the same queue as long as they use the same event types and filter.
1208   filter     | string       | **Optional.** Filter for specific event attributes using [filter expressions](12-icinga2-api.md#icinga2-api-filters).
1209
1210 ### <a id="icinga2-api-event-streams-types"></a> Event Stream Types
1211
1212 The following event stream types are available:
1213
1214   Type                   | Description
1215   -----------------------|--------------
1216   CheckResult            | Check results for hosts and services.
1217   StateChange            | Host/service state changes.
1218   Notification           | Notification events including notified users for hosts and services.
1219   AcknowledgementSet     | Acknowledgement set on hosts and services.
1220   AcknowledgementCleared | Acknowledgement cleared on hosts and services.
1221   CommentAdded           | Comment added for hosts and services.
1222   CommentRemoved         | Comment removed for hosts and services.
1223   DowntimeAdded          | Downtime added for hosts and services.
1224   DowntimeRemoved        | Downtime removed for hosts and services.
1225   DowntimeStarted        | Downtime started for hosts and services.
1226   DowntimeTriggered      | Downtime triggered for hosts and services.
1227
1228 Note: Each type requires [API permissions](12-icinga2-api.md#icinga2-api-permissions)
1229 being set.
1230
1231 Example for all downtime events:
1232
1233     &types=DowntimeAdded&types=DowntimeRemoved&types=DowntimeTriggered
1234
1235
1236 ### <a id="icinga2-api-event-streams-filter"></a> Event Stream Filter
1237
1238 Event streams can be filtered by attributes using the prefix `event.`.
1239
1240 Example for the `CheckResult` type with the `exit_code` set to `2`:
1241
1242     &types=CheckResult&filter=event.check_result.exit_status==2
1243
1244 Example for the `CheckResult` type with the service [matching](18-library-reference.md#global-functions-match)
1245 the string pattern "random\*":
1246
1247     &types=CheckResult&filter=match%28%22random*%22,event.service%29
1248
1249
1250 ### <a id="icinga2-api-event-streams-response"></a> Event Stream Response
1251
1252 The event stream response is separated with new lines. The HTTP client
1253 must support long-polling and HTTP/1.1. HTTP/1.0 is not supported.
1254
1255 Example:
1256
1257     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/events?queue=michi&types=CheckResult&filter=event.check_result.exit_status==2'
1258
1259     {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421319.7226390839,"type":"CheckResult"}
1260     {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421324.7226390839,"type":"CheckResult"}
1261     {"check_result":{ ... },"host":"example.localdomain","service":"ping4","timestamp":1445421329.7226390839,"type":"CheckResult"}
1262
1263
1264 ## <a id="icinga2-api-status"></a> Status and Statistics
1265
1266 Send a `GET` request to the URL endpoint `/v1/status` to retrieve status information and statistics for Icinga 2.
1267
1268 Example:
1269
1270     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status' | python -m json.tool
1271     {
1272         "results": [
1273             {
1274                 "name": "ApiListener",
1275                 "perfdata": [ ... ],
1276                 "status": [ ... ]
1277             },
1278             ...
1279             {
1280                 "name": "IcingaAplication",
1281                 "perfdata": [ ... ],
1282                 "status": [ ... ]
1283             },
1284             ...
1285         ]
1286     }
1287
1288 You can limit the output by specifying a status type in the URL, e.g. `IcingaApplication`:
1289
1290     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/status/IcingaApplication' | python -m json.tool
1291     {
1292         "results": [
1293             {
1294                 "perfdata": [],
1295                 "status": {
1296                     "icingaapplication": {
1297                         "app": {
1298                             "enable_event_handlers": true,
1299                             "enable_flapping": true,
1300                             "enable_host_checks": true,
1301                             "enable_notifications": true,
1302                             "enable_perfdata": true,
1303                             "enable_service_checks": true,
1304                             "node_name": "example.localdomain",
1305                             "pid": 59819.0,
1306                             "program_start": 1443019345.093372,
1307                             "version": "v2.3.0-573-g380a131"
1308                         }
1309                     }
1310                 }
1311             }
1312         ]
1313     }
1314
1315
1316 ## <a id="icinga2-api-config-management"></a> Configuration Management
1317
1318 The main idea behind configuration management is to allow external applications
1319 creating configuration packages and stages based on configuration files and
1320 directory trees. This replaces any additional SSH connection and whatnot to
1321 dump configuration files to Icinga 2 directly.
1322 In case you are pushing a new configuration stage to a package, Icinga 2 will
1323 validate the configuration asynchronously and populate a status log which
1324 can be fetched in a separated request.
1325
1326
1327 ### <a id="icinga2-api-config-management-create-package"></a> Creating a Config Package
1328
1329 Send a `POST` request to a new config package called `example-cmdb` in this example. This
1330 will create a new empty configuration package.
1331
1332     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
1333     'https://localhost:5665/v1/config/packages/example-cmdb' | python -m json.tool
1334     {
1335         "results": [
1336             {
1337                 "code": 200.0,
1338                 "package": "example-cmdb",
1339                 "status": "Created package."
1340             }
1341         ]
1342     }
1343
1344 Package names starting with an underscore are reserved for internal packages and must not be used.
1345
1346 ### <a id="icinga2-api-config-management-create-config-stage"></a> Uploading configuration for a Config Package
1347
1348 Configuration files in packages are managed in stages.
1349 Stages provide a way to maintain multiple configuration versions for a package.
1350
1351 Send a `POST` request to the URL endpoint `/v1/config/stages` and add the name of an existing
1352 configuration package to the URL path (e.g. `example-cmdb`).
1353 The request body must contain the `files` attribute with the value being
1354 a dictionary of file targets and their content.
1355
1356 The file path requires one of these two directories inside its path:
1357
1358   Directory   | Description
1359   ------------|------------------------------------
1360   conf.d      | Local configuration directory.
1361   zones.d     | Configuration directory for cluster zones, each zone must be put into its own zone directory underneath. Supports the [cluster config sync](6-distributed-monitoring.md#distributed-monitoring-top-down-config-sync).
1362
1363 Example for a local configuration in the `conf.d` directory:
1364
1365     "files": { "conf.d/host1.conf": "object Host \"local-host\" { address = \"127.0.0.1\", check_command = \"hostalive\" }" }
1366
1367 Example for a host configuration inside the `satellite` zone in the `zones.d` directory:
1368
1369     "files": { "zones.d/satellite/host2.conf": "object Host \"satellite-host\" { address = \"192.168.1.100\", check_command = \"hostalive\" }" }
1370
1371
1372 The example below will create a new file called `test.conf` in the `conf.d`
1373 directory. Note: This example contains an error (`chec_command`). This is
1374 intentional.
1375
1376     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST \
1377     -d '{ "files": { "conf.d/test.conf": "object Host \"cmdb-host\" { chec_command = \"dummy\" }" } }' \
1378     'https://localhost:5665/v1/config/stages/example-cmdb' | python -m json.tool
1379     {
1380         "results": [
1381             {
1382                 "code": 200.0,
1383                 "package": "example-cmdb",
1384                 "stage": "example.localdomain-1441625839-0",
1385                 "status": "Created stage."
1386             }
1387         ]
1388     }
1389
1390 The Icinga 2 API returns the `package` name this stage was created for, and also
1391 generates a unique name for the `stage` attribute you'll need for later requests.
1392
1393 Icinga 2 automatically restarts the daemon in order to activate the new config stage.
1394 If the validation for the new config stage failed, the old stage and its configuration objects
1395 will remain active.
1396
1397 > **Note**
1398 >
1399 > Old stages are not purged automatically. You can [remove stages](12-icinga2-api.md#icinga2-api-config-management-delete-config-stage) that are no longer in use.
1400
1401 Icinga 2 will create the following files in the configuration package
1402 stage after configuration validation:
1403
1404   File        | Description
1405   ------------|--------------
1406   status      | Contains the [configuration validation](11-cli-commands.md#config-validation) exit code (everything else than 0 indicates an error).
1407   startup.log | Contains the [configuration validation](11-cli-commands.md#config-validation) output.
1408
1409 You can [fetch these files](12-icinga2-api.md#icinga2-api-config-management-fetch-config-package-stage-files)
1410 in order to verify that the new configuration was deployed successfully.
1411
1412
1413 ### <a id="icinga2-api-config-management-list-config-packages"></a> List Configuration Packages and their Stages
1414
1415 A list of packages and their stages can be retrieved by sending a `GET` request to the URL endpoint `/v1/config/packages`.
1416
1417 The following example contains one configuration package `example-cmdb`. The package does not currently
1418 have an active stage.
1419
1420     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/packages' | python -m json.tool
1421     {
1422         "results": [
1423             {
1424                 "active-stage": "",
1425                 "name": "example-cmdb",
1426                 "stages": [
1427                     "example.localdomain-1441625839-0"
1428                 ]
1429             }
1430         ]
1431     }
1432
1433
1434 ### <a id="icinga2-api-config-management-list-config-package-stage-files"></a> List Configuration Packages and their Stages
1435
1436 In order to retrieve a list of files for a stage you can send a `GET` request to
1437 the URL endpoint `/v1/config/stages`. You need to include
1438 the package name (`example-cmdb`) and stage name (`example.localdomain-1441625839-0`) in the URL:
1439
1440     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441625839-0' | python -m json.tool
1441     {
1442         "results": [
1443     ...
1444             {
1445                 "name": "startup.log",
1446                 "type": "file"
1447             },
1448             {
1449                 "name": "status",
1450                 "type": "file"
1451             },
1452             {
1453                 "name": "conf.d",
1454                 "type": "directory"
1455             },
1456             {
1457                 "name": "zones.d",
1458                 "type": "directory"
1459             },
1460             {
1461                 "name": "conf.d/test.conf",
1462                 "type": "file"
1463             }
1464         ]
1465     }
1466
1467 ### <a id="icinga2-api-config-management-fetch-config-package-stage-files"></a> Fetch Configuration Package Stage Files
1468
1469 Send a `GET` request to the URL endpoint `/v1/config/files` and add
1470 the package name, the stage name and the relative path to the file to the URL path.
1471
1472 > **Note**
1473 >
1474 > The returned files are plain-text instead of JSON-encoded.
1475
1476 The following example fetches the configuration file `conf.d/test.conf`:
1477
1478     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441625839-0/conf.d/test.conf'
1479
1480     object Host "cmdb-host" { chec_command = "dummy" }
1481
1482 You can fetch a [list of existing files](12-icinga2-api.md#icinga2-api-config-management-list-config-package-stage-files)
1483 in a configuration stage and then specifically request their content.
1484
1485 ### <a id="icinga2-api-config-management-config-package-stage-errors"></a> Configuration Package Stage Errors
1486
1487 Now that we don't have an active stage for `example-cmdb` yet seen [here](12-icinga2-api.md#icinga2-api-config-management-list-config-packages),
1488 there must have been an error.
1489
1490 In order to check for validation errors you can fetch the `startup.log` file
1491 by sending a `GET` request to the URL endpoint `/v1/config/files`. You must include
1492 the package name, stage name and the `startup.log` in the URL path.
1493
1494     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/config/files/example-cmdb/example.localdomain-1441133065-1/startup.log'
1495     ...
1496
1497     critical/config: Error: Attribute 'chec_command' does not exist.
1498     Location:
1499     /var/lib/icinga2/api/packages/example-cmdb/example.localdomain-1441133065-1/conf.d/test.conf(1): object Host "cmdb-host" { chec_command = "dummy" }
1500                                                                                                            ^^^^^^^^^^^^^^^^^^^^^^
1501
1502     critical/config: 1 error
1503
1504 The output is similar to the manual [configuration validation](11-cli-commands.md#config-validation).
1505
1506 > **Note**
1507 >
1508 > The returned output is plain-text instead of JSON-encoded.
1509
1510
1511 ### <a id="icinga2-api-config-management-delete-config-stage"></a> Deleting Configuration Package Stage
1512
1513 You can send a `DELETE` request to the URL endpoint `/v1/config/stages`
1514 in order to purge a configuration stage. You must include the package and
1515 stage name inside the URL path.
1516
1517 The following example removes the failed configuration stage `example.localdomain-1441133065-1`
1518 in the `example-cmdb` configuration package:
1519
1520     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
1521     'https://localhost:5665/v1/config/stages/example-cmdb/example.localdomain-1441133065-1' | python -m json.tool
1522     {
1523         "results": [
1524             {
1525                 "code": 200.0,
1526                 "status": "Stage deleted."
1527             }
1528         ]
1529     }
1530
1531
1532 ### <a id="icinga2-api-config-management-delete-config-package"></a> Deleting Configuration Package
1533
1534 In order to completely purge a configuration package and its stages
1535 you can send a `DELETE` request to the URL endpoint `/v1/config/packages`
1536 with the package name in the URL path.
1537
1538 This example entirely deletes the configuration package `example-cmdb`:
1539
1540     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X DELETE \
1541     'https://localhost:5665/v1/config/packages/example-cmdb' | python -m json.tool
1542     {
1543         "results": [
1544             {
1545                 "code": 200.0,
1546                 "package": "example-cmdb",
1547                 "status": "Deleted package."
1548             }
1549         ]
1550     }
1551
1552
1553 ## <a id="icinga2-api-types"></a> Types
1554
1555 You can retrieve the configuration object types by sending a `GET` request to URL
1556 endpoint `/v1/types`.
1557
1558 Each response entry in the results array contains the following attributes:
1559
1560   Attribute      | Type         | Description
1561   ---------------|--------------|---------------------
1562   name           | string       | The type name.
1563   plural_name    | string       | The plural type name.
1564   fields         | dictionary   | Available fields including details on e.g. the type and attribute accessibility.
1565   abstract       | boolean      | Whether objects can be instantiated for this type.
1566   base           | boolean      | The base type (e.g. `Service` inherits fields and prototype methods from `Checkable`).
1567   prototype_keys | string array | Available prototype methods.
1568
1569 In order to view a specific configuration object type specify its name inside the URL path:
1570
1571     $ curl -k -s -u root:icinga 'https://localhost:5665/v1/types/Object' | python -m json.tool
1572     {
1573         "results": [
1574             {
1575                 "abstract": false,
1576                 "fields": {
1577                     "type": {
1578                         "array_rank": 0.0,
1579                         "attributes": {
1580                             "config": false,
1581                             "navigation": false,
1582                             "no_user_modify": false,
1583                             "no_user_view": false,
1584                             "required": false,
1585                             "state": false
1586                         },
1587                         "id": 0.0,
1588                         "type": "String"
1589                     }
1590                 },
1591                 "name": "Object",
1592                 "plural_name": "Objects",
1593                 "prototype_keys": [
1594                     "clone",
1595                     "notify_attribute",
1596                     "to_string"
1597                 ]
1598             }
1599         ]
1600     }
1601
1602
1603 ## <a id="icinga2-api-console"></a> Console
1604
1605 You can inspect variables and execute other expressions by sending a `POST` request to the URL endpoint `/v1/console/execute-script`.
1606 In order to receive auto-completion suggestions, send a `POST` request to the URL endpoint `/v1/console/auto-complete-script`.
1607
1608 The following parameters need to be specified (either as URL parameters or in a JSON-encoded message body):
1609
1610   Parameter  | Type         | Description
1611   -----------|--------------|-------------
1612   session    | string       | **Optional.** The session ID. Ideally this should be a GUID or some other unique identifier.
1613   command    | string       | **Required.** Command expression for execution or auto-completion.
1614   sandboxed  | number       | **Optional.** Whether runtime changes are allowed or forbidden. Defaults to disabled.
1615
1616 The [API permission](12-icinga2-api.md#icinga2-api-permissions) `console` is required for executing
1617 expressions.
1618
1619 > **Note**
1620 >
1621 > Runtime modifications via `execute-script` calls are not validated and might cause the Icinga 2
1622 > daemon to crash or behave in an unexpected way. Use these runtime changes at your own risk.
1623
1624 If you specify a session identifier, the same script context can be reused for multiple requests. This allows you to, for example, set a local variable in a request and use that local variable in another request. Sessions automatically expire after a set period of inactivity (currently 30 minutes).
1625
1626 Example for fetching the command line from the local host's last check result:
1627
1628     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/execute-script?command=get_host(NodeName).last_check_result.command&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756' | python -m json.tool
1629     {
1630         "results": [
1631             {
1632                 "code": 200.0,
1633                 "result": [
1634                     "/usr/local/sbin/check_ping",
1635                     "-H",
1636                     "127.0.0.1",
1637                     "-c",
1638                     "5000,100%",
1639                     "-w",
1640                     "3000,80%"
1641                 ],
1642                 "status": "Executed successfully."
1643             }
1644         ]
1645     }
1646
1647 Example for fetching auto-completion suggestions for the `Host.` type. This works in a
1648 similar fashion when pressing TAB inside the [console CLI command](11-cli-commands.md#cli-command-console):
1649
1650     $ curl -k -s -u root:icinga -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/console/auto-complete-script?command=Host.&sandboxed=0&session=bb75fd7c-c686-407d-9688-582c04227756' | python -m json.tool
1651     {
1652         "results": [
1653             {
1654                 "code": 200.0,
1655                 "status": "Auto-completed successfully.",
1656                 "suggestions": [
1657                     "Host.type",
1658                     "Host.name",
1659                     "Host.prototype",
1660                     "Host.base",
1661                     "Host.register_attribute_handler",
1662                     "Host.clone",
1663                     "Host.notify_attribute",
1664                     "Host.to_string"
1665                 ]
1666             }
1667         ]
1668     }
1669
1670
1671 ## <a id="icinga2-api-clients"></a> API Clients
1672
1673 There are a couple of existing clients which can be used with the Icinga 2 API:
1674
1675 * [curl](https://curl.haxx.se/) or any other HTTP client really
1676 * [Icinga 2 console (CLI command)](12-icinga2-api.md#icinga2-api-clients-cli-console)
1677 * [Icinga Studio](12-icinga2-api.md#icinga2-api-clients-icinga-studio)
1678 * [Icinga Web 2 Director](https://www.icinga.com/products/icinga-web-2-modules/)
1679
1680 Demo cases:
1681
1682 * [Dashing](https://github.com/Icinga/dashing-icinga2)
1683 * [API examples](https://github.com/Icinga/icinga2-api-examples)
1684
1685 Additional [programmatic examples](12-icinga2-api.md#icinga2-api-clients-programmatic-examples)
1686 will help you getting started using the Icinga 2 API in your environment.
1687
1688 ### <a id="icinga2-api-clients-icinga-studio"></a> Icinga Studio
1689
1690 Icinga Studio is a graphical application to query configuration objects provided by the API.
1691
1692 ![Icinga Studio Connection](images/icinga2-api/icinga2_api_icinga_studio_connect.png)
1693
1694 ![Icinga Studio Overview](images/icinga2-api/icinga2_api_icinga_studio_overview.png)
1695
1696 Please check the package repository of your distribution for available
1697 packages.
1698
1699 > **Note**
1700 > Icinga Studio does not currently support SSL certificate verification.
1701
1702 The Windows installer already includes Icinga Studio. On Debian and Ubuntu the package
1703 `icinga2-studio` can be used to install Icinga Studio.
1704
1705 ### <a id="icinga2-api-clients-cli-console"></a> Icinga 2 Console
1706
1707 By default the [console CLI command](11-cli-commands.md#cli-command-console) evaluates
1708 expressions in a local interpreter, i.e. independently from your Icinga 2 daemon.
1709 Add the `--connect` parameter to debug and evaluate expressions via the API.
1710
1711 ### <a id="icinga2-api-clients-programmatic-examples"></a> API Clients Programmatic Examples
1712
1713 The programmatic examples use HTTP basic authentication and SSL certificate
1714 verification. The CA file is expected in `pki/icinga2-ca.crt`
1715 but you may adjust the examples for your likings.
1716
1717 The [request method](icinga2-api-requests) is `POST` using
1718 [X-HTTP-Method-Override: GET](12-icinga2-api.md#icinga2-api-requests-method-override)
1719 which allows you to send a JSON request body. The examples request
1720 specific service attributes joined with host attributes. `attrs`
1721 and `joins` are therefore specified as array.
1722 The `filter` attribute [matches](18-library-reference.md#global-functions-match)
1723 on all services with `ping` in their name.
1724
1725 #### <a id="icinga2-api-clients-programmatic-examples-python"></a> Example API Client in Python
1726
1727 The following example uses **Python** and the `requests` and `json` module:
1728
1729     # pip install requests
1730     # pip install json
1731
1732     $ vim icinga2-api-example.py
1733
1734     #!/usr/bin/env python
1735     
1736     import requests, json
1737     
1738     # Replace 'localhost' with your FQDN and certificate CN
1739     # for SSL verification
1740     request_url = "https://localhost:5665/v1/objects/services"
1741     headers = {
1742             'Accept': 'application/json',
1743             'X-HTTP-Method-Override': 'GET'
1744             }
1745     data = {
1746             "attrs": [ "name", "state", "last_check_result" ],
1747             "joins": [ "host.name", "host.state", "host.last_check_result" ],
1748             "filter": "match(\"ping*\", service.name)",
1749     }
1750     
1751     r = requests.post(request_url,
1752             headers=headers,
1753             auth=('root', 'icinga'),
1754             data=json.dumps(data),
1755             verify="pki/icinga2-ca.crt")
1756     
1757     print "Request URL: " + str(r.url)
1758     print "Status code: " + str(r.status_code)
1759     
1760     if (r.status_code == 200):
1761             print "Result: " + json.dumps(r.json())
1762     else:
1763             print r.text
1764             r.raise_for_status()
1765
1766     $ python icinga2-api-example.py
1767
1768
1769 #### <a id="icinga2-api-clients-programmatic-examples-ruby"></a> Example API Client in Ruby
1770
1771 The following example uses **Ruby** and the `rest_client` gem:
1772
1773     # gem install rest_client
1774
1775     $ vim icinga2-api-example.rb
1776
1777     #!/usr/bin/ruby
1778     
1779     require 'rest_client'
1780     
1781     # Replace 'localhost' with your FQDN and certificate CN
1782     # for SSL verification
1783     request_url = "https://localhost:5665/v1/objects/services"
1784     headers = {
1785             "Accept" => "application/json",
1786             "X-HTTP-Method-Override" => "GET"
1787     }
1788     data = {
1789             "attrs" => [ "name", "state", "last_check_result" ],
1790             "joins" => [ "host.name", "host.state", "host.last_check_result" ],
1791             "filter" => "match(\"ping*\", service.name)",
1792     }
1793     
1794     r = RestClient::Resource.new(
1795             URI.encode(request_url),
1796             :headers => headers,
1797             :user => "root",
1798             :password => "icinga",
1799             :ssl_ca_file => "pki/icinga2-ca.crt")
1800     
1801     begin
1802             response = r.post(data.to_json)
1803     rescue => e
1804             response = e.response
1805     end
1806     
1807     puts "Status: " + response.code.to_s
1808     if response.code == 200
1809             puts "Result: " + (JSON.pretty_generate JSON.parse(response.body))
1810     else
1811             puts "Error: " + response
1812     end
1813
1814     $ ruby icinga2-api-example.rb
1815
1816 A more detailed example can be found in the [Dashing demo](https://github.com/Icinga/dashing-icinga2).
1817
1818 #### <a id="icinga2-api-clients-programmatic-examples-php"></a> Example API Client in PHP
1819
1820 The following example uses **PHP** and its `curl` library:
1821
1822     $ vim icinga2-api-example.php
1823
1824     #!/usr/bin/env php
1825     <?php
1826     # Replace 'localhost' with your FQDN and certificate CN
1827     # for SSL verification
1828     $request_url = "https://localhost:5665/v1/objects/services";
1829     $username = "root";
1830     $password = "icinga";
1831     $headers = array(
1832             'Accept: application/json',
1833             'X-HTTP-Method-Override: GET'
1834     );
1835     $data = array(
1836             attrs => array('name', 'state', 'last_check_result'),
1837             joins => array('host.name', 'host.state', 'host.last_check_result'),
1838             filter => 'match("ping*", service.name)',
1839     );
1840     
1841     $ch = curl_init();
1842     curl_setopt_array($ch, array(
1843             CURLOPT_URL => $request_url,
1844             CURLOPT_HTTPHEADER => $headers,
1845             CURLOPT_USERPWD => $username . ":" . $password,
1846             CURLOPT_RETURNTRANSFER => true,
1847             CURLOPT_CAINFO => "pki/icinga2-ca.crt",
1848             CURLOPT_POST => count($data),
1849             CURLOPT_POSTFIELDS => json_encode($data)
1850     ));
1851     
1852     $response = curl_exec($ch);
1853     if ($response === false) {
1854             print "Error: " . curl_error($ch) . "(" . $response . ")\n";
1855     }
1856     
1857     $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1858     curl_close($ch);
1859     print "Status: " . $code . "\n";
1860     
1861     if ($code == 200) {
1862             $response = json_decode($response, true);
1863             print_r($response);
1864     }
1865     ?>
1866
1867     $ php icinga2-api-example.php
1868
1869 #### <a id="icinga2-api-clients-programmatic-examples-perl"></a> Example API Client in Perl
1870
1871 The following example uses **Perl** and the `Rest::Client` module:
1872
1873     # perl -MCPAN -e 'install REST::Client'
1874     # perl -MCPAN -e 'install JSON'
1875     # perl -MCPAN -e 'install MIME::Base64'
1876     # perl -MCPAN -e 'install Data::Dumper'
1877
1878     $ vim icinga2-api-example.pl
1879
1880     #!/usr/bin/env perl
1881     
1882     use strict;
1883     use warnings;
1884     use REST::Client;
1885     use MIME::Base64;
1886     use JSON;
1887     use Data::Dumper;
1888     
1889     # Replace 'localhost' with your FQDN and certificate CN
1890     # for SSL verification
1891     my $request_host = "https://localhost:5665";
1892     my $userpass = "root:icinga";
1893     
1894     my $client = REST::Client->new();
1895     $client->setHost($request_host);
1896     $client->setCa("pki/icinga2-ca.crt");
1897     $client->addHeader("Accept", "application/json");
1898     $client->addHeader("X-HTTP-Method-Override", "GET");
1899     $client->addHeader("Authorization", "Basic " . encode_base64($userpass));
1900     my %json_data = (
1901             attrs => ['name', 'state', 'last_check_result'],
1902             joins => ['host.name', 'host.state', 'host.last_check_result'],
1903             filter => 'match("ping*", service.name)',
1904     );
1905     my $data = encode_json(\%json_data);
1906     $client->POST("/v1/objects/services", $data);
1907     
1908     my $status = $client->responseCode();
1909     print "Status: " . $status . "\n";
1910     my $response = $client->responseContent();
1911     if ($status == 200) {
1912             print "Result: " . Dumper(decode_json($response)) . "\n";
1913     } else {
1914             print "Error: " . $response . "\n";
1915     }
1916
1917     $ perl icinga2-api-example.pl
1918