[[create-rule-api]]
== Create rule API
++++
<titleabbrev>Create rule</titleabbrev>
++++

Create {kib} rules.

[NOTE]
====
For the most up-to-date API details, refer to the
{kib-repo}/tree/{branch}/x-pack/plugins/alerting/docs/openapi[open API specification]. For a preview, check out <<rule-apis>>.
====

[[create-rule-api-request]]
=== {api-request-title}

`POST <kibana host>:<port>/api/alerting/rule/<id>`

`POST <kibana host>:<port>/s/<space_id>/api/alerting/rule/<id>`


=== {api-prereq-title}

You must have `all` privileges for the appropriate {kib} features, depending on
the `consumer` and `rule_type_id` of the rules you're creating. For example, the
*Management* > *Stack Rules* feature, *Analytics* > *Discover* and *{ml-app}*
features, *{observability}*, and *Security* features. If the rule has `actions`,
you must also have `read` privileges for the *Management* >
*{connectors-feature}* feature. For more details, refer to
<<kibana-feature-privileges>>.

[[create-rule-api-path-params]]
=== {api-path-parms-title}

`<id>`::
(Optional, string) Specifies a UUID v1 or v4 to use instead of a randomly
generated ID.

`space_id`::
(Optional, string) An identifier for the space. If `space_id` is not provided in
the URL, the default space is used.

[role="child_attributes"]
[[create-rule-api-request-body]]
=== {api-request-body-title}

`actions`::
(Optional, object array) An array of action objects.
+
.Properties of the action objects:
[%collapsible%open]
=====

`group`:::
(Required, string) Grouping actions is recommended for escalations for different
types of alerts. If you don't need this, set this value to `default`.

`id`:::
(Required, string) The ID of the connector saved object, which you can obtain by
using <<get-all-connectors-api>>.

`params`:::
(Required, object) The map to the `params` that the
<<action-types,connector type>> will receive. ` params` are handled as Mustache
templates and passed a default set of context.
=====

`consumer`::
(Required, string) The name of the application or feature that owns the rule.
For example: `alerts`, `apm`, `discover`, `infrastructure`, `logs`, `metrics`,
`ml`, `monitoring`, `securitySolution`, `siem`, `stackAlerts`, or `uptime`.

`enabled`::
(Optional, boolean) Indicates if you want to run the rule on an interval basis
after it is created.

`name`::
(Required, string) The name of the rule. While this name does not have to be
unique, a distinctive name can help you identify a rule.

`notify_when`::
(Required, string) Defines how often alerts generate actions. Valid values are: 
+
--

* `onActionGroupChange`: Actions run when the alert status changes.
* `onActiveAlert`: Actions run when the alert becomes active and at each check
interval while the rule conditions are met.
* `onThrottleInterval`: Actions run when the alert becomes active and at the
interval specified in the `throttle` property while the rule conditions are met.

--

`params`::
(Required, object) The parameters to pass to the rule type executor `params`
value. This will also validate against the rule type params validator, if defined.

`rule_type_id`::
(Required, string) The ID of the rule type that you want to call when the rule
is scheduled to run. For example, `.es-query`, `.index-threshold`,
`logs.alert.document.count`, `monitoring_alert_cluster_health`,
`siem.thresholdRule`, or `xpack.ml.anomaly_detection_alert`. For more
information, refer to <<rule-types>>.

`schedule`::
(Required, object) The check interval, which specifies how frequently the rule
conditions are checked. The interval must be specified in seconds, minutes,
hours or days. For example: `{ "interval": "10s" }`, `{ "interval": "5m" }`,
`{ "interval": "1h" }`, or `{ "interval": "1d" }`.

`tags`::
(Optional, string array) A list of tag names that are applied to a rule.

`throttle`::
(Optional, string) Defines how often an alert generates repeated actions.
This custom action interval must be specified in seconds, minutes, hours, or
days. For example, `10m` or `1h`. This property is used only if `notify_when`
is `onThrottleInterval`.

[[create-rule-api-request-codes]]
===  {api-response-codes-title}

`200`::
    Indicates a successful call.

[[create-rule-api-example]]
=== {api-examples-title}

Create an <<rule-type-index-threshold,index threshold rule>> that has actions
associated with a server log connector:

[source,sh]
--------------------------------------------------
POST api/alerting/rule
{
  "params":{
      "aggType":"avg",
      "termSize":6,
      "thresholdComparator":">",
      "timeWindowSize":5,
      "timeWindowUnit":"m",
      "groupBy":"top",
      "threshold":[
         1000
      ],
      "index":[
         ".test-index"
      ],
      "timeField":"@timestamp",
      "aggField":"sheet.version",
      "termField":"name.keyword"
   },
   "consumer":"alerts",
   "rule_type_id":".index-threshold",
   "schedule":{
      "interval":"1m"
   },
   "actions":[
      {
         "id":"dceeb5d0-6b41-11eb-802b-85b0c1bc8ba2",
         "group":"threshold met",
         "params":{
            "level":"info",
            "message":"Rule '{{rule.name}}' is active for group '{{context.group}}':\n\n- Value: {{context.value}}\n- Conditions Met: {{context.conditions}} over {{rule.params.timeWindowSize}}{{rule.params.timeWindowUnit}}\n- Timestamp: {{context.date}}"
         }
      }
   ],
   "tags":[
      "cpu"
   ],
   "notify_when":"onActionGroupChange",
   "name":"my alert"
}
--------------------------------------------------
// KIBANA

The API returns the following:

[source,sh]
--------------------------------------------------
{
  "id": "41893910-6bca-11eb-9e0d-85d233e3ee35",
  "consumer": "alerts",
  "tags": ["cpu"],
  "name": "my alert",
  "enabled": true,
  "throttle": null,
  "schedule": {"interval": "1m"},
  "params": {
    "aggType": "avg",
    "termSize": 6,
    "thresholdComparator": ">",
    "timeWindowSize": 5,
    "timeWindowUnit": "m",
    "groupBy": "top",
    "threshold": [1000],
    "index": [".test-index"],
    "timeField": "@timestamp",
    "aggField": "sheet.version",
    "termField": "name.keyword"
  },
  "rule_type_id": ".index-threshold",
  "scheduled_task_id": "425b0800-6bca-11eb-9e0d-85d233e3ee35",
  "created_by": "elastic",
  "updated_by": "elastic",
  "created_at": "2022-06-08T17:20:31.632Z",
  "updated_at": "2022-06-08T17:20:31.632Z",
  "api_key_owner": "elastic",
  "notify_when": "onActionGroupChange",
  "mute_all": false,
  "muted_alert_ids": [],
  "execution_status": {
    "last_execution_date": "2022-06-08T17:20:31.632Z",
    "status": "pending"
  },
  "actions": [
    {
      "group": "threshold met",
      "id": "dceeb5d0-6b41-11eb-802b-85b0c1bc8ba2",
      "params": {
        "level": "info",
        "message": "Rule {{rule.name}} is active for group {{context.group}}:\n\n- Value: {{context.value}}\n- Conditions Met: {{context.conditions}} over {{rule.params.timeWindowSize}}{{rule.params.timeWindowUnit}}\n- Timestamp: {{context.date}}"
      },
      "connector_type_id": ".server-log"
    }
  ]
}
--------------------------------------------------
