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