Channel Enumeration using the REST API

Ably’s global platform organizes all message traffic within an application into named channels. Clients attach to the channels they are interested in. They can then publish messages to those channels or subscribe to receive messages from them.

Often, its useful for developers to be able to access channel metadata. Ably provides two APIs for this:

  • The Channel Status API enables you to query the status of a specific channel or perform channel enumeration: that is, to list all active channels within an application that are associated with a particular API key and optionally retrieve the status of each channel at the same time.

In this tutorial, you will learn how to implement channel enumeration.

Channel enumeration is part of the Channel Status API, and is currently only available via the REST API. Ably provides a REST client library to make it straightforward to access the REST API and you will be using the client library in this tutorial.

Step 1 – Create your Ably app and API key

To follow this tutorial, you will need an Ably account. Sign up for a free account if you don’t already have one.

Access to the Ably global messaging platform requires an API key for authentication. API keys exist within the context of an Ably application and each application can have multiple API keys so that you can assign different capabilities and manage access to channels and queues.

You can either create a new application for this tutorial, or use an existing one.

To create a new application and generate an API key:

  1. Log in to your Ably account dashboard
  2. Click the “Create New App” button
  3. Give it a name and click “Create app”
  4. Copy your private API key and store it somewhere. You will need it for this tutorial.

To use an existing application and API key:

  1. Select an application from “Your apps” in the dashboard
  2. In the API keys tab, choose an API key to use for this tutorial. The default “Root” API key has full access to capabilities and channels.
  3. Copy the Root API key and store it somewhere. You will need it for this tutorial.

    Copy API Key screenshot

Step 2 – Configuring the required capabilities on your API key

To be able to enumerate channels, your API key must have the Channel Metadata capability. Capabilities specify which operations your API key is allowed to perform. For example: Publish and Subscribe or Publish only. You configure these capabilities in the account dashboard:

  1. Navigate to the API Keys tab within your chosen application.
  2. Click the Settings button
  3. Ensure that Channel Metadata is selected in the list of capabilities
  4. Ensure that Resource restrictions (channels & queues) is set to None
  5. Click the Save button


Channel metadata capabilities

For simplicity, this tutorial will use basic authentication. In production, Ably advises that you use token authentication in client-side applications to protect your API key.

To enumerate channels in an application that uses token authentication, your token capabilities must include channel-metadata for all channels and queues by using the '*' wildcard. For example, the following token capabilities permit channel enumeration and subscribe operations on all channels:

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

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

Your JavaScript code will display your enumerated channels in a web page. Create a file called index.html and paste in the following HTML markup:

<html>
<head>
    <title>Channel Enumeration</title>
    <script src="https://cdn.ably.io/lib/ably-1.js"></script>
</head>

<body style="padding: 60px; font-family:Arial, Helvetica, sans-serif">
    Ably Channel Enumeration 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 JavaScript files, one is the Ably Library, referenced via the CDN, while the other is the main.js file that will include the application logic which you will work on next.

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

Channel enumeration is not currently integrated into Ably’s REST client libraries as a dedicated method. However, you can still use the REST client libraries to access the REST API it via the request() method, which can perform arbitrary requests to Ably’s REST API endpoints.

Note: Ably recommends that you use this approach rather than querying the REST API directly yourself: see Should I use the REST API directly? for an explanation.

In order to receive channel enumeration information, you need to query the /channels endpoint. You will use the client library’s request() method to perform a GET request and the result of this request will be an HTTPPaginatedResponse object. This enables the results to be returned in pages, instead of all at once.

Begin by instantiating the Ably REST client library. Create a new file called main.js and add the following code to it, replacing <YOUR-API-KEY> with your own API key:

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

Then, code the REST API request using the library’s request() method as follows:

const resultArea = document.getElementById('result');

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

let 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);
  };
}

The enumerateChannels() function is invoked when the user clicks the Enumerate Channels button in the web page. Inside this function, you make a GET request to the REST API /channels endpoint, using the REST client library’s request() method. You can optionally limit the number of results returned using the limit parameter: see the API reference to learn more.

Because the results are returned as an HTTPPaginatedResponse object, you must process them page by page. Each page has an items array that lists active channels within an Ably application. The by: 'id' parameter tells the API to return only a list of names. If you want more detailed information about each channel (such as occupancy data), you can remove this parameter. See the documentation for all supported parameters.

Step 5 – Live Demo

Click the button below to see a list of active channels within a sample application.


See the full code in GitHub

Next Steps

1. Find out more about channels and how to publish or subscribe to messages.
2. Discover other tutorials about working with channel metadata: Subscribing to Channel Lifecycle Events and Subscribing to Inband Channel Occupancy Events.
3. See other tutorials to learn more about Ably’s features.
4. Gain a good technical overview of how the Ably realtime platform works
5. Get in touch if you need help