REST client

The Rest class is the entry point for using the Ably Pub/Sub JavaScript SDK in REST mode. It is a stateless client that interacts with the Ably REST API over HTTP, without maintaining a persistent connection, and provides access to channels, presence, push notifications, and authentication. It is well suited to server-side environments and to publishing or querying from contexts that don't need realtime updates.

JavaScript

1

const rest = new Ably.Rest({ key: 'demokey:*****' });
API key:
DEMO ONLY

This example uses basic authentication with an API key, which is appropriate for trusted, server-side environments. For browsers and other untrusted clients, use token authentication instead, by supplying an authCallback or authUrl that fetches tokens from your own server, keeping your API key off the client.

Properties

The Rest interface has the following properties:

authAuth
The Auth object for this client. Manages tokens and authentication.
channelsChannels
The Channels collection for this client. Used to obtain Channel instances.
pushPush
The Push object for this client. Used for push notification device activation and admin operations.
CryptoCrypto
Static access to the Crypto utility. Accessed on the class: Ably.Rest.Crypto.
MessageMessage
Static access to the Message class for fromEncoded() factory methods. Accessed on the class: Ably.Rest.Message.
PresenceMessagePresenceMessage
Static access to the PresenceMessage class for fromEncoded() factory methods. Accessed on the class: Ably.Rest.PresenceMessage.
AnnotationAnnotation
Static access to the Annotation type for fromEncoded() factory methods. Accessed on the class: Ably.Rest.Annotation.

Create a new Rest client

new Ably.Rest(options: ClientOptions)

Construct a client with a ClientOptions object. This is the most common form, allowing all available client options to be configured.

new Ably.Rest(keyOrToken: string)

A convenience constructor that takes a single API key or token string. Equivalent to passing { key: '<key>' } or { token: '<token>' } as ClientOptions. Useful for simple basic-authenticated or test setups.

JavaScript

1

2

3

4

5

6

7

8

9

// With ClientOptions
const rest = new Ably.Rest({
  key: 'demokey:*****',
  clientId: 'user-123',
  logLevel: 3
});

// Or with just a key string
const rest = new Ably.Rest('demokey:*****');
API key:
DEMO ONLY

Parameters

The Rest() constructor takes the following parameters:

optionsrequiredClientOptions
Configuration options for the client. All properties are optional unless noted.
keyOrTokenrequiredString
A full API key string for basic authentication, or a token string.

Get server time

rest.time(): Promise<number>

Returns the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well-maintained time source and wish to issue Ably TokenRequests with a more accurate timestamp should use the clientOptions.queryTime client option instead of this method.

JavaScript

1

const now = await rest.time();

Returns

Promise<number>

Returns a promise. The promise is fulfilled with the server time as milliseconds since the Unix epoch, or rejected with an ErrorInfo object.

Get account stats

rest.stats(params?: StatsParams): Promise<PaginatedResult<Stats>>

Retrieves usage statistics for the account, filtered by the supplied query parameters. Returns a paginated set of Stats objects, each containing usage metrics.

JavaScript

1

const page = await rest.stats({ unit: 'hour', limit: 24 });

Parameters

The stats() method takes the following parameters:

paramsoptionalStatsParams
Query parameters for the stats request.

Returns

Promise<PaginatedResult<Stats>>

Returns a promise. The promise is fulfilled with a PaginatedResult of Stats objects, or rejected with an ErrorInfo object.

Stats

Each Stats entry contains the following properties:

appIdString
The Ably application ID.
intervalIdString
The UTC time period that this stats entry refers to. If unit was requested as minute this is in the format YYYY-mm-dd:HH:MM, if hour it is YYYY-mm-dd:HH, if day it is YYYY-mm-dd:00, and if month it is YYYY-mm-01:00.
inProgressString
For entries that are still in progress, such as the current month, the last sub-interval included in this stats entry, in the format yyyy-mm-dd:hh:mm:ss.
entriesRecord<String, Number>
A map of statistics entries (for example messages.all.count, messages.inbound.rest.count) to their values. The schema property provides further information.
schemaString
A URL to the JSON Schema describing the structure of this object.

Make a REST request

rest.request(method: string, path: string, version: number, params?: any, body?: any, headers?: any): Promise<HttpPaginatedResponse>

Makes a REST request to a provided path. Useful for accessing Ably APIs that do not have a dedicated method in the SDK, without having to handle authentication, paging, fallback hosts, and MsgPack or JSON support yourself.

JavaScript

1

2

3

4

5

6

const response = await rest.request(
  'GET',
  '/channels/all-gas-ion/messages',
  3,
  { limit: 10 }
);

Parameters

The request() method takes the following parameters:

methodrequiredString
The HTTP method (GET, POST, PUT, PATCH, DELETE).
pathrequiredString
The path of the API endpoint to call.
versionrequiredNumber
The API version (e.g. 3).
paramsoptionalObject
Query parameters.
bodyoptionalAny
The request body, for POST, PUT, and PATCH methods only. Must be anything that can be serialized into JSON, such as an object or array.
headersoptionalObject
Custom HTTP headers.

Returns

Promise<HttpPaginatedResponse>

Returns a promise. The promise is fulfilled with an HttpPaginatedResponse, or rejected with an ErrorInfo object. Note that if a response is obtained, any response, even one with a non-2xx status code, resolves as an HttpPaginatedResponse rather than rejecting.

HttpPaginatedResponse

HttpPaginatedResponse contains the following properties:

statusCodeNumber
The HTTP status code of the response.
successBoolean
true if the status code is in the 200-299 range.
errorCodeNumber
The error code, derived from the X-Ably-Errorcode HTTP header, if sent in the response.
errorMessageString
The error message, derived from the X-Ably-Errormessage HTTP header, if sent in the response.
errorDetailObject or Undefined
A map of structured error metadata.
headersObject
The response headers.
itemsArray
The current page of results.

HttpPaginatedResponse also contains the following methods to handle pagination:

Check for more pages
hasNext(): boolean

Returns true if there are more pages available by calling next().

Check if last page
isLast(): boolean

Returns true if this is the last page of results.

Get next page
next(): Promise<PaginatedResult | null>

Returns a promise. The promise is fulfilled with the next page of results as a PaginatedResult, or null if there are no more pages. Rejected with an ErrorInfo object on failure.

Get first page
first(): Promise<PaginatedResult>

Returns a promise. The promise is fulfilled with the first page of results as a PaginatedResult, or rejected with an ErrorInfo object.

Get current page
current(): Promise<PaginatedResult>

Returns a promise. The promise is fulfilled with the current page of results as a PaginatedResult, or rejected with an ErrorInfo object.

Batch publish to multiple channels

rest.batchPublish(spec: BatchPublishSpec): Promise<BatchResult>

Publish using a single BatchPublishSpec, fulfilled with a single BatchResult.

rest.batchPublish(specs: BatchPublishSpec[]): Promise<BatchResult[]>

Publish using an array of BatchPublishSpec objects, fulfilled with one BatchResult per spec.

Each spec publishes one or more messages to up to 100 channels in a single batch publish request.

JavaScript

1

2

3

4

const result = await rest.batchPublish({
  channels: ['channel1', 'channel2'],
  messages: [{ name: 'event', data: 'hello' }]
});

Parameters

The batchPublish() method takes the following parameters:

specrequiredBatchPublishSpec
A single batch publish spec.
specsrequiredBatchPublishSpec[]
An array of batch publish specs.

Returns

Promise<BatchResult | BatchResult[]>

Returns a promise. For a single spec, the promise is fulfilled with a BatchResult. For an array of specs, the promise is fulfilled with an array of BatchResults. Rejected with an ErrorInfo object on failure.

successCountNumber
The number of successful operations in the request.
failureCountNumber
The number of unsuccessful operations in the request.
resultsArray of BatchPublishSuccessResult or BatchPublishFailureResult
The per-channel results, one entry per channel.

Batch presence query

rest.batchPresence(channels: string[]): Promise<BatchResult[]>

Retrieves the presence set for up to 100 channels in a single REST request. The presence state includes the clientId of members and their current presence action.

Parameters

The batchPresence() method takes the following parameters:

channelsrequiredString[]
The names of the channels to query.

Returns

Promise<BatchResult[]>

Returns a promise. The promise is fulfilled with an array of BatchResult objects, one per channel, where each results entry is a BatchPresenceSuccessResult or a BatchPresenceFailureResult. Rejected with an ErrorInfo object on failure.

successCountNumber
The number of successful operations in the request.
failureCountNumber
The number of unsuccessful operations in the request.
resultsArray of BatchPresenceSuccessResult or BatchPresenceFailureResult
The per-channel results, one entry per channel.

Get the local device

rest.getDevice(): Promise<LocalDevice>

Retrieves a LocalDevice object representing the current device as a push notification target, loading its state from persistent storage if necessary.

Returns

Promise<LocalDevice>

Returns a promise. The promise is fulfilled with the LocalDevice, or rejected with an ErrorInfo object.

PaginatedResult

A PaginatedResult represents a page of results from a paginated query such as stats(), channel.history(), presence.history(), or channel.getMessageVersions().

Properties

PaginatedResult contains the following properties:

itemsArray
The current page of results.

PaginatedResult also contains the following methods to handle pagination:

Check for more pages

hasNext(): boolean

Returns true if there are more pages available.

Check if last page

isLast(): boolean

Returns true if this is the last page of results.

Get next page

next(): Promise<PaginatedResult | null>

Returns a promise fulfilled with the next page of results, or null if there are no more pages. Rejected with an ErrorInfo object on failure.

Get first page

first(): Promise<PaginatedResult>

Returns a promise fulfilled with the first page of results, or rejected with an ErrorInfo object.

Get current page

current(): Promise<PaginatedResult>

Returns a promise fulfilled with the current page of results, or rejected with an ErrorInfo object.

ErrorInfo

A standardized, generic Ably error object that contains an Ably-specific error code, a generic HTTP status code, and a human-readable message. All errors emitted by Ably are ErrorInfo instances.

codeNumber
The Ably-specific error code.
statusCodeNumber
The HTTP status code corresponding to this error, where applicable.
messageString
A human-readable description of what went wrong.
causeErrorInfo or Undefined
The underlying error that caused this error, where applicable.
detailObject or Undefined
An optional map of string key-value pairs containing structured metadata associated with the error.
remediationString or Undefined
Actionable guidance describing how to fix the error, as distinct from message, which describes what went wrong. Present only on SDK-originating errors with meaningful remediation steps.