API

API version: v2

The Sensu backend REST API provides a centrally managed control plane for automated, repeatable monitoring and observability workflow configuration and observation event data access.

If you have a healthy clustered backend, you only need to make Sensu API calls to any one of the cluster members. The cluster protocol will replicate your changes to all cluster members.

For information about the Sensu agent API, read the agent reference.

Available APIs

Access all of the data and functionality of Sensu’s first-class API clients, sensuctl and the web UI, with Sensu’s backend REST APIs. Use the Sensu APIs and endpoints to customize your workflows and integrate your favorite Sensu features with other tools and products.

core/v2 API endpoints

The core/v2 API includes endpoints for the following Sensu resources:

Enterprise APIs

COMMERCIAL FEATURE: Access Sensu’s enterprise APIs in the packaged Sensu Go distribution. For more information, read Get started with commercial features.

The enterprise APIs include:

Other endpoints

Sensu offers additional endpoints for basic authentication, health, license, metrics, and version:

URL format

Most core/v2 API endpoints use the standard URL format /api/core/<version>/namespaces/<namespace> where:

  • <version> is the API version: v2.
  • <namespace> is the namespace name.

For enterprise APIs for namespaced resources, the URL format also includes a group that indicates the relevant enterprise feature: /api/enterprise/<group>/<version>/namespaces/<namespace>.

For enterprise APIs for cluster-wide resources, the URL format does not include namespace elements: /api/enterprise/<group>/<version>.

The endpoint-only APIs do not follow a standard URL format.

Namespaces in API URLs

The examples in the API documentation use the default namespace.

The Sensu API requires the authenticated user to have the correct access permissions for the namespace specified in the URL. If the authenticated user has the correct cluster-wide permissions, you can leave out the /namespaces/<namespace> portion of the URL to access Sensu resources across namespaces.

Read the RBAC reference for more information about configuring Sensu users and access controls.

Data format

The Sensu API uses JSON-formatted requests and responses.

In terms of output formats, the Sensu API uses json output format for responses for APIs in the core group. For APIs that are not in the core group, responses are in the wrapped-json output format. The wrapped-json format includes an outer-level spec “wrapping” for resource attributes and lists the resource type and api_version.

Sensu sends events to the backend in json format, without the spec attribute wrapper or type and api_version attributes.

Versioning

The Sensu Go API is versioned according to the format v{majorVersion}{stabilityLevel}{iterationNumber}, in which v2 is stable version 2. The Sensu API guarantees backward compatibility for stable versions of the API.

Sensu does not guarantee that an alpha or beta API will be maintained for any period of time. Consider alpha versions under active development — they may not be published for every release. Beta APIs are more stable than alpha versions, but they offer similarly short-lived lifespans and also are not guaranteed to convert programmatically when the API is updated.

Request size limit

The default limit for API request body size is 0.512 MB. Use the api-request-limit backend configuration option to customize the API request body size limit if needed.

Access control

With the exception of the authentication, health, metrics, ready, and version API endpoints, the Sensu API requires authentication using a JSON Web Token (JWT) access token or API key.

Code examples in the Sensu API docs use the environment variable $SENSU_API_KEY to represent a valid API key in API requests.

NOTE: The authentication information on this page is specific to the Sensu API. For information about using Sensu’s built-in basic authentication or external authentication providers to authenticate to the Sensu web UI, API, or sensuctl, read the Control Access documentation.

Authentication quickstart

To set up a local API testing environment, save your Sensu credentials and access token as environment variables.

Save your Sensu credentials as environment variables:

export SENSU_USER=YOUR_USERNAME && SENSU_PASS=YOUR_PASSWORD

Save your Sensu access token as an environment variable:

NOTE: The command to save your access token as an environment variable requires curl and jq.

export SENSU_ACCESS_TOKEN=`curl -X GET -u "$SENSU_USER:$SENSU_PASS" -s http://localhost:8080/auth | jq -r ".access_token"`

The sensuctl reference demonstrates how to use the sensuctl env command to export your access token, token expiry time, and refresh token as environment variables.

Authenticate with /auth API endpoints

Use the authentication API and your Sensu username and password to generate access tokens and refresh tokens. The /auth API endpoint lets you generate short-lived API tokens using your Sensu username and password.

  1. Retrieve an access token for your user. For example, to generate an access token using example admin credentials:

    curl -u 'YOUR_USERNAME:YOUR_PASSWORD' http://localhost:8080/auth
    The access token should be included in the output, along with a refresh token:
    {
      "access_token": "eyJhbGciOiJIUzI1NiIs...",
      "expires_at": 1544582187,
      "refresh_token": "eyJhbGciOiJIUzI1NiIs..."
    }
    The access and refresh tokens are JWTs that Sensu uses to digitally sign the details of users’ authenticated Sensu sessions.

  2. Use the access token in the authentication header of the API request. For example:

    curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
    http://127.0.0.1:8080/api/core/v2/namespaces/default/events

  3. Refresh your access token every 15 minutes. Access tokens last for approximately 15 minutes. When your token expires, you should receive a 401 Unauthorized response from the API. To generate a new access token, use the /auth/token API endpoint, including the expired access token in the authorization header and the refresh token in the request body:

    curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
    -H 'Content-Type: application/json' \
    -d '{"refresh_token": "eyJhbGciOiJIUzI1NiIs..."}' \
    http://127.0.0.1:8080/auth/token
    The new access token should be included in the output:
    {
      "access_token": "eyJhbGciOiJIUzI1NiIs...",
      "expires_at": 1561055277,
      "refresh_token": "eyJhbGciOiJIUzI1NiIs..."
    }

Generate an API access token with sensuctl

You can also generate an API access token using the sensuctl command line tool. The user credentials that you use to configure sensuctl determine your permissions to get, list, create, update, and delete resources with the Sensu API.

  1. Install and configure sensuctl.

  2. Retrieve an access token for your user:

    cat ~/.config/sensu/sensuctl/cluster|grep access_token
    The access token should be included in the output:
    "access_token": "eyJhbGciOiJIUzI1NiIs...",

  3. Copy the access token into the authentication header of the API request. For example:

    curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
    http://127.0.0.1:8080/api/core/v2/namespaces/default/events

  4. Refresh your access token every 15 minutes. Access tokens last for approximately 15 minutes. When your token expires, you should receive a 401 Unauthorized response from the API. To regenerate a valid access token, run any sensuctl command (like sensuctl event list) and repeat step 2.

Authenticate with an API key

Each Sensu API key (core/v2/apikey) is a persistent universally unique identifier (UUID) that maps to a stored Sensu username. The advantages of authenticating with API keys rather than access tokens include:

  • More efficient integration: Check and handler plugins and other code can integrate with the Sensu API without implementing the logic required to authenticate via the /auth API endpoint to periodically refresh the access token
  • Improved security: API keys do not require providing a username and password in check or handler definitions
  • Better admin control: API keys can be created and revoked without changing the underlying user’s password, but keep in mind that API keys will continue to work even if the user’s password changes

API keys are cluster-wide resources, so only cluster admins can grant, view, and revoke them.

NOTE: API keys are not supported for authentication providers such as LDAP and OIDC.

Configure an environment variable for API key authentication

Configure the SENSU_API_KEY environment variable with your own API key to use it for authentication in your Sensu API requests as shown in the Sensu API code examples.

Follow these steps to generate an API key and export it to the SENSU_API_KEY environment variable:

  1. Generate an API key with sensuctl:

    sensuctl api-key grant admin

    The response will include the new API key:

    Created: /api/core/v2/apikeys/83abef1e-e7d7-4beb-91fc-79ad90084d5b

    PRO TIP: Sensuctl is the most direct way to generate an API key, but you can also use the POST core/v2/apikeys endpoint.

  2. Export your API key to the SENSU_API_KEY environment variable:

    export SENSU_API_KEY="83abef1e-e7d7-4beb-91fc-79ad90084d5b"
    SET SENSU_API_KEY="83abef1e-e7d7-4beb-91fc-79ad90084d5b"
    $Env:SENSU_API_KEY = "83abef1e-e7d7-4beb-91fc-79ad90084d5b"

Authorization header for API key authentication

Similar to the Bearer [token] Authorization header, Key [api-key] will be accepted as an Authorization header for authentication.

For example, a JWT Bearer [token] Authorization header might be:

curl -H "Authorization: Bearer $SENSU_ACCESS_TOKEN" http://127.0.0.1:8080/api/core/v2/namespaces/default/checks

If you’re using Key [api-key] to authenticate instead, the Authorization header might be:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/namespaces/default/checks

Example

This example uses the API key directly (rather than the $SENSU_API_KEY environment variable) to authenticate to core/v2/checks:

curl -H "Authorization: Key 7f63b5bc-41f4-4b3e-b59b-5431afd7e6a2" http://127.0.0.1:8080/api/core/v2/namespaces/default/checks

A successful request will return the HTTP response code HTTP/1.1 200 OK and the definitions for the checks in the default namespace.

Pagination

The Sensu API supports response pagination for most core/v2 GET endpoints that return an array. You can request a paginated response with the limit and continue query parameters.

Limit query parameter

The following request limits the response to a maximum of two objects:

curl http://127.0.0.1:8080/api/core/v2/users?limit=2 -H "Authorization: Key $SENSU_API_KEY"

The response includes the available objects up to the specified limit.

Continue query parameter

If more objects are available beyond the limit you specified in a request, the response header includes a Sensu-Continue token you can use to request the next page of objects.

For example, the following response indicates that more than two users are available because it provides a Sensu-Continue token in the response header:

HTTP/1.1 200 OK
Content-Type: application/json
Sensu-Continue: L2RlZmF1bU2Vuc3UtTWFjQ
Sensu-Entity-Count: 3
Sensu-Entity-Limit: 100
Sensu-Entity-Warning: 
Date: Fri, 14 Feb 2020 15:44:25 GMT
Content-Length: 132
[
  {
    "username": "alice",
    "groups": [
      "ops"
    ],
    "disabled": false
  },
  {
    "username": "bob",
    "groups": [
      "ops"
    ],
    "disabled": false
  }
]

To request the next two available users, use the Sensu-Continue token included in the response header:

curl http://127.0.0.1:8080/api/core/v2/users?limit=2&continue=L2RlZmF1bU2Vuc3UtTWFjQ \
-H "Authorization: Key $SENSU_API_KEY"

If the response header does not include a Sensu-Continue token, there are no further objects to return. For example, this response header indicates that no further users are available:

HTTP/1.1 200 OK
Content-Type: application/json
Sensu-Entity-Count: 3
Sensu-Entity-Limit: 100
Sensu-Entity-Warning: 
Date: Fri, 14 Feb 2020 15:46:02 GMT
Content-Length: 54
[
  {
    "username": "alice",
    "groups": [
      "ops"
    ],
    "disabled": false
  }
]

Etag response headers

All GET and PATCH requests return an Etag HTTP response header that identifies a specific version of the resource. Use the Etag value from the response header to conditionally execute PATCH requests that use the If-Match and If-None-Match headers.

If Sensu cannot execute a PATCH request because one of the conditions failed, the request will return the HTTP response code 412 Precondition Failed.

If-Match example

curl -X PATCH \
-H "Authorization: Key $SENSU_API_KEY" \
-H 'Content-Type: application/merge-patch+json' \
-H 'If-Match: "drrn157624731797"' \
-d '{
  "metadata": {
    "labels": {
      "region": "us-west-1"
    }
  }
}' \
http://127.0.0.1:8080/api/core/v2/namespaces/default/assets/sensu-slack-handler

A successful request will return the HTTP response code HTTP/1.1 200 OK.

If-None-Match example

curl -X PATCH \
-H "Authorization: Key $SENSU_API_KEY" \
-H 'Content-Type: application/merge-patch+json' \
-H 'If-None-Match: "drrn157624731797", "reew237527931897"' \
-d '{
  "metadata": {
    "labels": {
      "region": "us-west-1"
    }
  }
}' \
http://127.0.0.1:8080/api/core/v2/namespaces/default/assets/sensu-slack-handler

A successful request will return the HTTP response code HTTP/1.1 200 OK.

Response filtering

COMMERCIAL FEATURE: Access API response filtering in the packaged Sensu Go distribution. For more information, read Get started with commercial features.

The Sensu API supports response filtering for all GET endpoints that return an array. You can filter resources based on their labels with the labelSelector query parameter and based on certain pre-determined fields with the fieldSelector query parameter.

NOTE: To search based on fields and labels in the Sensu web UI, read Search in the web UI.

Label selector

The labelSelector query parameter allows you to group resources by the label attributes specified in the resource metadata object. All resources support labels within the metadata object.

Field selector

The fieldSelector query parameter allows you to organize and select subsets of resources based on certain fields. Here’s the list of available fields:

Resource Fields
Asset asset.name asset.namespace asset.filters
Check check.name check.namespace check.handlers check.publish check.round_robin check.runtime_assets check.subscriptions
ClusterRole clusterrole.name
ClusterRoleBinding clusterrolebinding.name clusterrolebinding.role_ref.name clusterrolebinding.role_ref.type
Entity entity.name entity.namespace entity.deregister entity.entity_class entity.subscriptions
Event event.name event.namespace event.is_silenced event.check.handlers event.check.is_silenced event.check.name event.check.publish event.check.round_robin event.check.runtime_assets event.check.state event.check.status event.check.subscriptions event.entity.deregister event.entity.entity_class event.entity.name event.entity.subscriptions
Extension extension.name extension.namespace
Filter filter.name filter.namespace filter.action filter.runtime_assets
Handler handler.name handler.namespace handler.filters handler.handlers handler.mutator handler.type
Hook hook.name hook.namespace
Mutator mutator.name mutator.namespace mutator.runtime_assets
Namespace namespace.name
Pipeline pipeline.name pipeline.namespace
Role role.name role.namespace
RoleBinding rolebinding.name rolebinding.namespace rolebinding.role_ref.name rolebinding.role_ref.type
Secrets secret.name secret.namespace secret.provider secret.id
SecretsProviders provider.name
Silenced silenced.name silenced.namespace silenced.check silenced.creator silenced.expire_on_resolve silenced.subscription
User user.username user.disabled user.groups

API-specific syntax

To create an API response filter, you’ll write a brief filter statement. The operators and examples sections demonstrate how to construct API response filter statements for different operators and specific purposes.

The filter statement construction is slightly different for different operators, but there are a few general syntax rules that apply to all filter statements.

Spaces in the filter statement

As shown in this example:

'fieldSelector=silenced.expire_on_resolve == true'
  • Do not use spaces around the = between the selector type and the rest of the filter statement.
  • Do use spaces around the operator (in this example, the ==).

Quotation marks around the filter statement

Place the entire filter statement inside single quotes:

'fieldSelector=linux in check.subscriptions'

Exception: If the filter statement contains a shell variable, you must use double quotation marks around the statement:

"labelSelector=host == $HOSTNAME"

If you use single quotes around a filter statement that contains a shell variable, the single quotes will keep the variable intact instead of expanding it.

NOTE: This exception only applies to shell variables. It does not apply for variables in languages that treat single and double quotation marks interchangeably, like JavaScript.

Values that begin with a number or include special characters

If you are filtering for a value that begins with a number, place the value in double quotes:

'fieldSelector=entity.name == "1b04994n"'

Likewise, to use a label or field selector with string values that include special characters like hyphens and underscores, place the value in double quotes:

'labelSelector:region == "us-west-1"'

Filter operators

Sensu’s API response filtering supports two equality-based operators, two set-based operators, one substring matching operator, and one logical operator.

operator description example
== Equality check.publish == true
!= Inequality check.namespace != "default"
in Included in linux in check.subscriptions
notin Not included in slack notin check.handlers
matches Substring matching check.name matches "linux-"
&& Logical AND check.publish == true && slack in check.handlers

Equality-based operators

Sensu’s two equality-based operators are == (equality) and != (inequality).

For example, to retrieve only checks with the label type and value server:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'labelSelector=type == "server"'

NOTE: Use the flag --data-urlencode in cURL to encode the query parameter. Include the -G flag so the request appends the query parameter data to the URL.

To retrieve checks that are not in the production namespace:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=check.namespace != "production"'

Set-based operators

Sensu’s two set-based operators for lists of values are in and notin.

For example, to retrieve checks with a linux subscription:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=linux in check.subscriptions'

To retrieve checks that do not use the slack handler:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=slack notin check.handlers'

The in and notin operators have two important conditions:

  • First, they only work when the underlying value you’re filtering for is a string. You can filter for strings and arrays of strings with in and notin operators, but you cannot use them to filter for integer, float, array, or Boolean values.
  • Second, to filter for a string, the string must be to the left of the operator: string [in|notin] selector. To filter for an array of strings, the array must be to the right of the operator: selector [in|notin] [string1,string2].

Substring matching operator

Sensu’s substring matching operator is matches.

For example, to retrieve all checks whose name includes linux:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=check.name matches "linux"'

Suppose you are using Sensu to monitor 1000 entities that are named incrementally and according to technology. For example, your webservers are named webserver-1 through webserver-25, and your CPU entities are named cpu-1 through cpu-300, and so on. In this case, you can use matches to retrieve all of your webserver entities:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/entities -G \
--data-urlencode 'fieldSelector=entity.name matches "webserver-"'

Similarly, if you have entities labeled for different regions, you can use matches to find the entities that are labeled for the US (for example, us-east-1, us-west-1, and so on):

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/entities -G \
--data-urlencode 'labelSelector:region matches "us"'

The matches operator only works when the underlying value you’re filtering for is a string. You can filter for strings and arrays of strings with the matches operator, but you cannot use it to filter for integer, float, array, or Boolean values. Also, the string must be to the right of the operator: selector matches string.

Logical operator

Sensu’s logical operator is && (AND). Use it to combine multiple statements separated with the logical operator in field and label selectors.

For example, the following cURL request retrieves checks that are not configured to be published and include the linux subscription:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=check.publish != true && linux in check.subscriptions'

To retrieve checks that are not published, include a linux subscription, and are in the dev namespace:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=check.publish != true && linux in check.subscriptions && dev in check.namespace'

NOTE: Sensu does not have the OR logical operator.

Combined selectors

You can use field and label selectors in a single request. For example, to retrieve only checks that include a linux subscription and do not include a label for type server:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=linux in check.subscriptions' \
--data-urlencode 'labelSelector=type != "server"'

Examples

Values with special characters

To use a label or field selector with string values that include special characters like hyphens and underscores, place the value in single or double quotes:

curl -H "Authorization: Key $SENSU_API_KEY" -X GET http://127.0.0.1:8080/api/core/v2/entities -G \
--data-urlencode 'labelSelector=region == "us-west-1"'
curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/entities -G \
--data-urlencode 'fieldSelector="entity:i-0c1f8a116b84ea50c" in entity.subscriptions'

Use selectors with arrays of strings

To retrieve checks that are in either the dev or production namespace:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=check.namespace in [dev,production]'

Filter events by entity or check

To retrieve events for a specific check (checkhttp):

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/events -G \
--data-urlencode 'fieldSelector=checkhttp in event.check.name'

Similary, to retrieve only events for the server entity:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/events -G \
--data-urlencode 'fieldSelector=server in event.entity.name'

Filter events by severity

Use the event.check.status field selector to retrieve events by severity. For example, to retrieve all events at 2 (CRITICAL) status:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/events -G \
--data-urlencode 'fieldSelector=event.check.status == "2"'

Filter all incidents

To retrieve all incidents (all events whose status is not 0):

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/events -G \
--data-urlencode 'fieldSelector=event.entity.status != "0"'

Filter checks, entities, or events by subscription

To list all checks that include the linux subscription:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/checks -G \
--data-urlencode 'fieldSelector=linux in check.subscriptions'

Similarly, to list all entities that include the linux subscription:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/entities -G \
--data-urlencode 'fieldSelector=linux in entity.subscriptions'

To list all events for the linux subscription, use the event.entity.subscriptions field selector:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/events -G \
--data-urlencode 'fieldSelector=linux in event.entity.subscriptions'

Filter silenced resources and silences

Filter silenced resources by namespace

To list all silenced resources for a particular namespace (in this example, the default namespace):

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/silenced -G \
--data-urlencode 'fieldSelector=silenced.namespace == "default"'

Likewise, to list all silenced resources except those in the default namespace:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/silenced -G \
--data-urlencode 'fieldSelector=silenced.namespace != "default"'

To list all silenced events for all namespaces:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/events -G \
--data-urlencode 'fieldSelector=event.is_silenced == true'

Filter silences by creator

To list all silences created by the user alice:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/silenced -G \
--data-urlencode 'fieldSelector=silenced.creator == "alice"'

To list all silences that were not created by the admin user:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/silenced -G \
--data-urlencode 'fieldSelector=silenced.creator != "admin"'

Filter silences by silence subscription

To retrieve silences with a specific subscription (in this example, linux):

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/silenced -G \
--data-urlencode 'fieldSelector=silenced.subscription == "linux"'

Another way to make the same request is:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/silenced -G \
--data-urlencode 'fieldSelector=linux in silenced.subscription'

NOTE: For this field selector, subscription means the subscription specified for the silence. In other words, this filter retrieves silences with a particular subscription, not silenced entities or checks with a matching subscription.

Filter silenced resources by expiration

To list all silenced resources that expire only when a matching check resolves:

curl -H "Authorization: Key $SENSU_API_KEY" http://127.0.0.1:8080/api/core/v2/silenced -G \
--data-urlencode 'fieldSelector=silenced.expire_on_resolve == true'