When you perform an API query using the Cisco NX-API REST interface, you have the option to create a subscription to any future changes in the results of a given query. When any management object (MO) is created, changed, or deleted, because of a user-initiated or system-initiated action, an event is generated. If the received event changes the results of a subscribed query, the switch generates a push notification to the API client that created the subscription.
Opening a WebSocket
The API subscription feature uses the WebSocket protocol (RFC 6455) to implement a two-way connection with the API client. This way, the API can send unsolicited notification messages to the client itself. To establish the notification channel, you must first open a WebSocket connection with the respective API. Only a single WebSocket connection is needed to support multiple query subscriptions within each switch. The WebSocket connection is dependent on your API session connection, and closes when your API session ends.
Creating a Subscription
To create a subscription to a query, perform the query with the option ?subscription=yes. This example creates a subscription to a query of the fv:Tenant class in the JSON format:
GET https://n9k-sw-1/api/class/l1PhysIf.json?subscription=yes
The query response contains a subscription identifier, subscriptionId, that you can use to refresh the subscription and identify future notifications from the given subscription.
Receiving Notifications
An event notification from the subscription delivers a data structure that contains the subscription ID and the MO description. In this JSON example, a new user has been created with the name "sysadmin5":
As multiple active subscriptions can exist for a given query, a notification can contain multiple subscription IDs; similar as shown in the example above. Notifications are supported in either JSON or XML format.
Refreshing the Subscription
In order to continue receiving event notifications, you must periodically refresh each subscription during your API session. To refresh a subscription, send an HTTP GET message to the API method subscriptionRefresh
with the parameter id
, equal to the subscriptionId
shown in the example:
GET https://n9k-sw-1/api/subscriptionRefresh.json?id=72057611234574337
The API will return an empty response to the refresh message unless the subscription has expired.
Note: The timeout period for a subscription is one minute per default. To prevent loss of notifications, you must send a subscription refresh message at least once every 60 seconds.
In summary, WebSocket provides a powerful tool for allowing publisher-subscriber communication for event subscription within the Open NX-OS REST API.