Interacting with our HTTP API

Pusher provides a HTTP API as the main point of interaction with your servers. Publishing events is the most important aspect of this, but there are other methods for querying the state of your Pusher applications. These are documented in our API reference.

All interactions with the Pusher HTTP API must contain an authentication signature that is generated with your secret key. Using one of our libraries means you generally don’t need to worry about this, but more information can be found here.

Many of our libraries allow requests to be made asynchronously. Please consult the individual documentation for more information.

Publishing events

Because it is such a fundamental part of the service, most of our libraries have special methods for triggering events. Behind the scenes this is just a simple call to our HTTP API. We recommend using serialised JSON to keep message sizes down.

Please bear in mind the following when publishing events:

  • Event names (and the channels they are sent to) can only contain characters which are alphanumeric, ‘-‘ or ‘_’ (see naming channels)
  • The data content (POST body) of events must be smaller than 10kB.
  • Exceeding your quota will return a 413 HTTP error code
  • An event can be published to between 1 and 10 channel names in a single request
  • Often it is useful to exclude the sender from the recipients of the event (read more)

For full details about the HTTP API including resource endpoints, allowed attributes, server responses, and error codes please consult our HTTP API reference.

require 'pusher'

pusher_client = Pusher::Client.new(
  app_id: 'APP_ID',
  key: 'APP_KEY',
  secret: 'APP_SECRET',
  cluster: 'APP_CLUSTER'
)

pusher_client.trigger(channels, event, data)

The parameters passed to the trigger function are:

  • channels - either a single channel name as a string or an array of channel names that the event is to be published on
  • event - the name of the event to be triggered
  • data - the data to be sent with the event. This will be converted to JSON by the library.
  • socket_id - Optional. The socket ID of a client to be excluded from receiving the event. See excluding recipients.

For more information see the pusher-http-ruby README.

require __DIR__ . '/vendor/autoload.php';

$pusher = new Pusher\Pusher('APP_KEY', 'APP_SECRET', 'APP_ID', array('cluster' => 'APP_CLUSTER'));

$response = $pusher->trigger($channels, $event, $data, $socket_id);

The parameters passed to the trigger function are:

  • $channels - either a single channel name as a string or an array of channel names that the event is to be published on
  • $event - the name of the event to be triggered
  • $data - the data to be sent with the event. This will be converted to JSON by the library.
  • $socket_id - Optional. The socket ID of a client to be excluded from receiving the event. See excluding recipients.

$response is true if the event was successfully triggered, otherwise false.

If debug is enabled (see the library README for more information) the $response is an associative array with the following elements:

  • status - the HTTP status code from the response
  • body - the body of the response. If an error occurs the body can provide additional information.

For more information see the pusher-http-php README.

using PusherServer;

var options = new PusherOptions();
options.Cluster = "APP_CLUSTER";
var pusher = new Pusher("APP_ID", "APP_KEY", "APP_SECRET", options);

ITriggerResult result = await pusher.TriggerAsync(
  string[] channels,
  string event,
  object data,
  ITriggerOptions options);

The parameters that can be passed to the TriggerAsync method are:

  • channels - A array of channel names to trigger the event on. There is an overload available which takes a single channel name string.
  • event - the name of the event to be triggered.
  • data - the data to be sent with the event. This will be converted to JSON by the library.
  • options - Optional via an overloaded method. Additional options when triggering an event.

You can exclude a client from receiving an event by passing in an object that implements the ITriggerOptions interface, or a TriggerObjects instance, with a SocketId value set. For more information see the excluding recipients documentation.

The result is an object which implements the ITriggerResult interface. The interface provides the following properties which expose information about the result of the call.:

  • StatusCode - An HttpStatusCode indicating the status request.
  • Body - the string body of the response. If an error occurs the body can provide additional information.
  • Response – The original response from the REST client
  • OriginalContent – If the HttpStatusCode was not 200 OK, then the content is copied into this property

For more information see the pusher-http-dotnet README.

var Pusher = require('pusher');

var pusher = new Pusher({
  appId: 'APP_ID',
  key: 'APP_KEY',
  secret: 'APP_SECRET',
  cluster: 'APP_CLUSTER'
});
pusher.trigger(channels, event, data, socketId, callback);

The parameters that can be passed to the trigger function are:

  • channels - a string identifying a single channel or an array of strings for multiple channels
  • event - the name of the event to be triggered
  • data - the data to be sent with the event. This will be converted to JSON by the library.
  • socketId - Optional. The socket ID of a client to be excluded from receiving the event. See excluding recipients.
  • callback - Optional. A callback function which is invoked when the call completes. The function have the signature function( error, request, response ).

For more information see the pusher-http-node README.

from pusher import Pusher

pusher = Pusher(app_id=u'APP_ID', key=u'APP_KEY', secret=u'APP_SECRET', cluster=u'APP_CLUSTER')
pusher.trigger(channels, event, {u'some': u'data'})
import "github.com/pusher/pusher-http-go"

client := pusher.Client{
  AppId: "APP_ID",
  Key: "APP_KEY",
  Secret: "APP_SECRET",
  Cluster: "APP_CLUSTER",
}

client.Trigger(channels, event, data)

Examples: Publish an event on a single channel

In the examples below an event called my-event is being triggered on a channel named my-channel. The message payload ultimately ends up as a simple JSON message {"message":"hello world"}.

require 'pusher'

pusher_client = Pusher::Client.new(
  app_id: 'APP_ID',
  key: 'APP_KEY',
  secret: 'APP_SECRET',
  cluster: 'APP_CLUSTER'
)

pusher_client.trigger('my-channel', 'my-event', {:message => 'hello world'})
require __DIR__ . '/vendor/autoload.php';

$pusher = new Pusher\Pusher('APP_KEY', 'APP_SECRET', 'APP_ID', array('cluster' => 'APP_CLUSTER'));
$response = $pusher->trigger('my-channel', 'my-event', array( 'message' => 'hello world'));
using PusherServer;

var options = new PusherOptions();
options.Cluster = "APP_CLUSTER";
var pusher = new Pusher("APP_ID", "APP_KEY", "APP_SECRET", options);

ITriggerResult result = await pusher.TriggerAsync(
  "my-channel",
  "my-event",
  new { message = "hello world" });
var Pusher = require('pusher');

var pusher = new Pusher({
  appId: 'APP_ID',
  key: 'APP_KEY',
  secret: 'APP_SECRET',
  cluster: 'APP_CLUSTER'
});
pusher.trigger('my-channel', 'my-event', { message: "hello world" });
from pusher import Pusher

pusher = Pusher(app_id=u'APP_ID', key=u'APP_KEY', secret=u'APP_SECRET', cluster=u'APP_CLUSTER')

pusher.trigger(u'my-channel', u'my-event', {u'some': u'data'})
import "github.com/pusher/pusher-http-go"

client := pusher.Client{
  AppId: "APP_ID",
  Key: "APP_KEY",
  Secret: "APP_SECRET",
  Cluster: "APP_CLUSTER",
}

data := map[string]string{"message": "hello world"}

client.Trigger("my-channel", "my-event", data)

Example: Publish an event on multiple channels

In the examples below an event called my-event is being triggered multiple channels; my-channel-1, my-channel-2 and my-channel-3. The message payload is converted to a simple JSON message {"message":"hello world"}.

require 'pusher'

pusher_client = Pusher::Client.new(
  app_id: 'APP_ID',
  key: 'APP_KEY',
  secret: 'APP_SECRET',
  cluster: 'APP_CLUSTER'
)

pusher_client.trigger(['my-channel-1', 'my-channel-2', 'my-channel-3'], 'my-event', {
  message: 'hello world'
})
require __DIR__ . '/vendor/autoload.php';

$pusher = new Pusher\Pusher('APP_KEY', 'APP_SECRET', 'APP_ID', array('cluster' => 'APP_CLUSTER'));
$pusher->trigger(['my-channel-1', 'my-channel-2', 'my-channel-3'],
                 'my-event',
                 array( 'message' => 'hello world'));
using PusherServer;

var options = new PusherOptions();
options.Cluster = "APP_CLUSTER";
var pusher = new Pusher("APP_ID", "APP_KEY", "APP_SECRET", options);

ITriggerResult result = await pusher.TriggerAsync(
  new string[]{"my-channel-1", "my-channel-2", "my-channel-3"},
  "my-event",
  new { message: "hello world" });
var Pusher = require('pusher');

var pusher = new Pusher({
  appId: 'APP_ID',
  key: 'APP_KEY',
  secret: 'APP_SECRET',
  cluster: 'APP_CLUSTER'
});
var channels = ['my-channel-1', 'my-channel-2', 'my-channel-3'];
pusher.trigger(channels, 'my-event', { message: "hello world" });
import "github.com/pusher/pusher-http-go"

client := pusher.Client{
  AppId: "APP_ID",
  Key: "APP_KEY",
  Secret: "APP_SECRET",
  Cluster: "APP_CLUSTER",
}

client.TriggerMulti([]string{"my-channel-1", "my-channel-2", "my-channel-3"}, "my-event", data)
from pusher import Pusher

pusher = Pusher(app_id=u'APP_ID', key=u'APP_KEY', secret=u'APP_SECRET', cluster=u'APP_CLUSTER')

pusher.trigger([u'my-channel-1', u'my-channel-2', u'my-channel-3'], u'my-event', {u'some': u'data'})

Publishing batches of events

You might also find yourself wanting to publish many non-identical events in a short space of time. To reduce the number of HTTP requests you need to make in this case, the Pusher HTTP API supports batches of up to ten events in one request. Our server libraries provide a trigger batch method that wraps this API call. In the examples below an event called my-event-1 is being triggered on channel my-channel-1, and an event called my-event-2 is being triggered on channel my-channel-2.

pusher_client.trigger_batch([
  {channel: 'my-channel-1', name: 'my-event-1', data: { foo: 'bar' }}
  {channel: 'my-channel-2', name: 'my-event-2', data: { hello: 'world' }}
])
$batch = array();
$batch[] = array('channel' => 'my-channel-1', 'name' => 'my-event-1', 'data' => array('hello' => 'world'));
$batch[] = array('channel' => 'my-channel-2', 'name' => 'my-event-2', 'data' => array('myname' => 'bob'));
$pusher->triggerBatch($batch);
var events = new List[]{
  new Event(){ EventName = "my-event-1", Channel = "my-channel-1", Data = "hello world" },
  new Event(){ EventName = "my-event-2", Channel = "my-channel-2", Data = "my name is bob" },
}

ITriggerResult result = await pusher.TriggerAsync(events);
var events = [{
  channel: "my-channel-1",
  name: "my-event-1",
  data: {message: "hello world"}
},
{
  channel: "my-channel-2",
  name: "my-event-2",
  data: {message: "hello another world"}
}];

pusher.triggerBatch(events);
pusher.trigger_batch([
  { u'channel': u'my-channel-1', u'name': u'my-event-1', u'data': {u'some': u'data'}, u'socket_id': '1234.12'},
  { u'channel': u'my-channel-2', u'name': u'my-event-2', u'data': {u'some': u'other data'}}
])
client.TriggerBatch([]pusher.Event{
  { Channel: "my-channel-1", Name: "my-event-1", Data: "hello world", nil },
  { Channel: "my-channel-2", Name: "my-event-2", Data: "hi my name is bob", nil },
})

Querying application state

Sometimes you may want to know the state of your application to determine things like which channels have active subscribers or which users are currently on a presence channel. The Pusher Server library contains a specific set of calls to query for application state. Alternatively the Pusher HTTP API exposes a way of doing that and many of the Pusher server libraries offer a generic GET method for performing such queries.

The GET method maps to a GET HTTP request to the Pusher HTTP API and as such the libraries require:

  • A resource (or path) parameter which is used to identify what you are querying.
  • Optional query parameters. These tend to be key/value pairs and vary depending on the resource being queried.
pusher_client.get(resource, params)

The parameters passed to the get function are:

  • resource - the resource endpoint to be queried.
  • params - Optional. Additional parameters to be sent as query string parameters with the request. The names and values for these depend on the resource being queried. See examples below and the HTTP API reference for more information.

For more information see the pusher-http-ruby README.

$response = $pusher->get($resource, $params)

The parameters passed to the get function are:

  • $resource - the resource endpoint to be queried.
  • $params - Optional. Additional parameters to be sent as query string parameters with the request. The names and values for these depend on the resource being queried. See examples below and the HTTP API reference for more information.

For more information see the pusher-http-php README.

IGetResult<object> result = await pusher.GetAsync<object>(string resource, object parameters);

The Pusher Server library contains a specific wrapper that allows a consuming application to make a simple call specifying the type to deserialise to when making a GET request. object has been used above because as yet there isn’t a defined class that the information can be serialized into.

For more information see the pusher-http-dotnet README.

pusher.get({ path: path, params: params }, callback);

The parameters passed to the get function are:

  • options
    • path - the path to the resource endpoint to be queried.
    • params - Optional. Additional parameters to be sent as query string parameters with the request. The names and values for these depend on the resource being queried. See examples below and the HTTP API reference for more information.
  • callback - the function to be called when the request has completed. The function signature for the callback is function( error, request, response ).

For more information see the pusher-http-node README.

Application channels

If you would like a list of the channel within an application that have active subscriptions (also referred to as being occupied) then you can query the /channels resource.

For full parameter information see the HTTP API channels reference.

response = pusher_client.get('/channels')
$response = $pusher->get( '/channels' );
if( $response[ 'status'] == 200 ) {
  // convert to associative array for easier consumption
  $channels = json_decode( $response[ 'body' ], true );
}
IGetResult<ChannelsList> result = await pusher.GetAsync<ChannelsList>("/channels");

The Pusher Server library contains a specific wrapper that allows a consuming application to make a simple call specifying the type to deserialise to when requesting Channel Information.

For more information see the pusher-http-dotnet README.

pusher.get({ path: '/channels', params: {} }, function(error, request, response) {
  if(response.statusCode === 200) {
    var result = JSON.parse( response.body );
    var channelsInfo = result.channels;
  }
});
pusher.channels_info(u"presence-", [u'user_count'])
channelsParams := map[string]string{
    "filter_by_prefix": "presence-",
    "info":             "user_count",
}

channels, err := client.Channels(channelsParams)

Channel information

You can query the state of an individual channel. This is done by querying the /channels/[channel_name] resource where channel_name is replaced with the actual name of the channel you are requesting information for.

For full parameter information see the HTTP API channel reference.

response = pusher_client.get('/channels/channel-name')
IGetResult<object> result = await pusher.FetchStateForChannelAsync<object>("my-channel-1");

The Pusher Server library contains a specific wrapper that allows a consuming application to make a simple call passing in the channel name, and a type to deserialize to when requesting the state of a channel. object has been used above because as yet there isn’t a defined class that the information can be serialized into.

For more information see the pusher-http-dotnet README.

$response = $pusher->get('/channels/channel-name');
if( $response[ 'status'] == 200 ) {
  // convert to associative array for easier consumption
  $channel_info = json_decode( $response[ 'body' ], true);
}
pusher.get({ path: '/channels/channel-name', params: {} },
  function(error, request, response) {
    if(response.statusCode === 200) {
      var result = JSON.parse(response.body);
      var channelInfo = result.channels;
    }
  });
channel = pusher.channel_info(u'presence-chatroom', [u"user_count"])
channelParams := map[string]string{
    "info": "user_count,subscription_count",
}

channel, err := client.Channel("presence-chatroom", channelParams)

Presence users

A list of users present on a presence channel can be retrieved by querying the /channels/[channel_name]/users resource where the channel_name is replaced with a valid presence channel name.

For full parameter information see the HTTP API presence users reference.

response = pusher_client.get('/channels/presence-channel-name/users')
IGetResult<object> result = await pusher.FetchUsersFromPresenceChannelAsync<object>("my-channel-1");

The Pusher Server library contains a specific wrapper that allows a consuming application to make a simple call passing in the channel name, and a type to deserialize to when requesting Presence Users. object has been used above because as yet there isn’t a defined class that the information can be serialized into.

For more information see the pusher-http-dotnet README.

$response = $pusher->get( '/channels/presence-channel-name/users' );
if( $response[ 'status'] == 200 ) {
  // convert to associative array for easier consumption
  $users = json_decode( $response[ 'body' ], true )[ 'users' ];
}
pusher.get({ path: '/channels/presence-channel-name/users', params: {} },
  function(error, request, response) {
    if(response.statusCode === 200) {
      var result = JSON.parse(response.body);
      var users = result.users;
    }
  });
pusher.users_info(u'presence-chatroom')
users, err := client.GetChannelUsers("presence-chatroom")

Have you tried using the search to find what you’re after? If you still have a question then get in touch with us and let us help you out.