Please be aware that you are viewing our bleeding edge unstable documentation. Unless you wanted to view the bleeding edge (and possibly unstable) documentation, we recommend you use our stable docs.

Go to Ably's stable canonical documentation »

I know what I'm doing, let me see the bleeding edge docs »

You are viewing our bleeding edge unstable documentation. We recommend you use our stable documentation »
Fork me on GitHub

Channel Enumeration using the REST API

Ably Realtime’s Data Stream Network organizes all of the message traffic within its applications into named channels. Channels are the “unit” of message distribution; clients attach to any number of channels to publish or subscribe to messages. Every message published to a channel is broadcasted to all subscribers.

Many times, developers find it helpful to be aware of specific metadata related to their channels. This metadata can be accessed using our Channel Metadata API. This API allows you to subscribe to the channel lifecycle events and channel occupancy events or send one off REST requests to the Channel Status API to query channel enumeration, i.e., listing all the active channels associated with a particular API key in an app or to query the status and occupancy data associated with the channel. In this tutorial, we’ll see how to implement the channel enumeration functionality.

Channel enumeration, as decribed above, is part of the Channel Status API, and can be currently implemented via our REST API only; however, you can still use our REST client library to send requests to the REST API as you’ll see further down this tutorial.

Step 1 – Set up a free account with Ably

In order to run these tutorials locally, you will need an Ably API key. If you are not already signed up, you should sign up now for a free Ably account. Once you have an Ably account:

  1. Log into your app dashboard
  2. Under “Your apps”, click on “Manage app” for any app you wish to use for this tutorial, or create a new one with the “Create New App” button
  3. Click on the “API Keys” tab
  4. Copy the secret “API Key” value from your Root key and store it so that you can use it later in this tutorial

    Copy API Key screenshot

Step 2 – Setting the right permissions on your API key

In order to be able to enumerate channels, you’ll need to ensure that the Channel Metadata permission is enabled on your API key. Privileges (sometimes referred to as capabilities or permissions) restrict your API key to specific operations such as Publish and Subscribe or Publish only. These privileges can be set on your API key via your account dashboard. Navigate to the ‘API Keys’ tab of your dashboard as shown in the image below and click on the ‘settings’ button on your existing API key that you’d like to use, or create a new one.


Channel metadata permissions

A regular Ably API key has a capability which lists resources (glob expressions that match channel names) and, for any given resource, a set of permitted operations. The wildcard resource '*' will match any regular channel name. To enable access to channel metadata, ensure the Channel Metadata privilege is enabled in your API key.

If you are using token authentication, in order to enumerate channels, your token capabilities must permit the channel-metadata a wildcard '*' resource. If you are not clear on when to use token vs basic (API key) authentication, read selecting an authentication mechanism. The following is an example of a capability for a token that would allow access to channel enumeration and subscribe operations:

{
  "*": ["channel-metadata", "subscribe"]
}

Step 3 – Creating a basic HTML page to display the results

Since we’ll be using JavaScript in this tutorial, the best way to display the results is in a browser. So, go ahead and paste the following simple HTML in a file and name it index.html

<html>
<head>
    <title>Channel Enumeration</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script lang="text/javascript" src="https://cdn.ably.io/lib/ably-1.js"></script>
</head>

<body style="padding: 60px; font-family:Arial, Helvetica, sans-serif">
    Ably Channel Enumeration using REST API - Demo
    <br/>
    <div>
        <button id='enumerate' onclick="enumerateChannels()">Enumerate channels</button>
        <br>
        <textarea id="result" rows="30" style="width: 30%; margin-top: 14px; font-family: courier, courier new; background-color: #333; color: orange;  overflow-y: scroll;" disabled autocomplete="off">
        </textarea>
    </div>
    <script src="main.js"></script>
</body>

</html>

The key thing to note in the HTML above is the inclusion of two JS files, one is the Ably Library, referenced via the CDN, while the other is the main.js file which will include our logic. We’ll work on this next.

Step 4 – Using Ably’s REST library to perform a REST API request

Channel enumeration is not currently integrated into our REST client libraries as a dedicated method. However, you can still use our REST client libraries to query it, using the request() method , which can perform arbitrary REST requests to our API. We highly recommend you do this rather than querying the REST api directly yourself; see Should I use the REST API directly?- for why.

For the simplicity of this tutorial, we’ll use Basic authentication to perform the request. However, it is highly recommended to use Token auth on client-side applications for better security and protection of your API key.

In order to receive channel enumeration information, we’ll have to make use of the /channels endpoint of Ably’s REST API. We’ll perform a GET request using the REST library, and the result of this request will be an HTTPPaginatedResponse object. This allows the results to be returned in a paginated fashion, i.e, it returns a page of results and allows you to automatically request for more pages until all of the available results are returned.

Let’s begin with instantiating the Ably REST library using the API key. Create a new file called main.js and add the following to it.

var ably = new Ably.Rest('<YOUR-API-KEY>');

Next, let’s go ahead and perform the actual REST request using the request() method as follows:

var url = '/channels';
var resultArea = document.getElementById('result');

//request a list of channels on button click
function enumerateChannels() {
  ably.request('get', url, { limit: 100, by: 'id' }, null, null, handleResultPage);
}

var channelCount = 0;
function handleResultPage(err, resultPage) {
  if(err || !resultPage.success) {
    resultArea.value += 'An error occurred; err = ' + (err || resultPage.errorMessage);
    return;
  }
  if(channelCount === 0) {
    if(resultPage.items.length == 0){
      resultArea.value += "Your app does not have any active channels\n";
      return;
    }
    resultArea.value += "Your app has the following active channels:\n";
  }

  resultPage.items.forEach(function(channel) {
    resultArea.value += (++channelCount) + ". " + channel + "\n";
  })

  if(resultPage.hasNext()) {
    resultPage.next(handleResultPage);
  };
}

Remember to replace with an actual Ably API key.

In the code above, we have set the REST endpoint to be /channels. The enumerateChannels() function is invoked on a button click from the front end. Inside this function, we have made a simple request to Ably’s REST API, using Ably’s JavaScript REST client library. We can optionally specify a limit to the results returned; you can have a look at the API reference in the docs to learn more. As mentioned before, the results are returned in the form of an HTTPPaginatedResponse; hence we are required to process them page by page. Each page contains one Channel per active channel that exists within an app. Here, all we are interested in is the name of the channel, so we used by: 'id' parameter to request only a list of names. If you want more detailed information about each channel (such as occupancy data), you can remove this parameter. See our REST API docs for documentation on all supported parameters.

Step – 5 Live Demo

Ably Channel Enumeration using REST API – Demo

Make sure that you’ve enabled the channel metadata permission on your API key.


See the full code in GitHub

Next Steps

1. If you would like to find out more about how channels and publishing or subscribing to messages work, see the realtime channels & messages documentation.
2. If you would like to check out the other related tutorials to work with channel metadata, see the Channel Lifecycle Events and Channel Occupancy Events tutorials.
3. Learn more about Ably features by going through our other Ably tutorials
4. Gain a good technical overview of how the Ably realtime platform works
5. Get in touch if you need help


Back to top