Although PubNub offers SDKs for all popular programming languages such as TypeScript, Kotlin (Android), Swift (iOS), or C (IoT), a large proportion of our developer community chooses to integrate with PubNub through our REST API endpoints.
To help new and existing developers work with our REST API, we have recently released a Postman collection showing the PubNub platform's main features.
The new collection is available from our Postman workspace, so if you are comfortable with Postman, feel free to head straight there. However, the rest of this tutorial will walk you through getting started with the collection, sending some messages, and exercising a few of our more popular APIs.
Getting Started
Fork the PubNub Postman collection.
To use the PubNub Postman collection, from our Postman workspace, log into your Postman account and create your own copy of the collection by forking it (the three dots next to the collection name, then Fork
)
You will now have a copy of the PubNub API in your selected workspace and a copy of the demo environment if you selected this during the fork process.
Where to find help?
The collection is organized into folders, which group the API calls into PubNub features (e.g., publish a message, publish a file, read a channel history, etc.). The description of each folder will contain documentation for its contents.
Need help getting started with the collection? Start with the description of the top-level folder.
Need help with a particular feature? See the description of the folder that contains the feature. E.g., for help with PubNub Subscribe, see the Subscribe feature folder
Want something more? A curl command? Code snippets in Python or Node? Then please refer to our complete REST API documentation. Each page in our REST API documentation also features a ‘Run in Postman’ button, so you can easily test the API in Postman.
Create a PubNub Account and Pub/Sub Keyset
To get started, you will need a PubNub publish and subscribe keyset, which is required to authenticate the API and integrate with the rest of the PubNub platform to send/receive messages, load messages from storage, and access metadata about users and devices. Keysets work on the application level so you will have one keyset for every application… Well, you will likely have a Debug
, Testing
, and Production
keyset for every application, but for now, a single keyset will suffice.
If you have not already, create a PubNub account by navigating to admin.pubnub.com and clicking ‘Sign up for free’. You do not need to enter a credit card to create a free account, so you can play with the REST API without worrying about unexpected charges.
After creating a PubNub account, create a new Application and Keyset to test the REST API. I recommend enabling all the configuration settings on the keyset (Presence, Message Persistence, App Context, File Sharing), but leave Access Manager disabled for now. You will need to enable Access Manager before you deploy to production, but it is not required to experiment with the API. Also, be sure to edit your Presence Management rules to enable all events on all channels; otherwise, the Presence API may not work as expected.
Make a note of your Publish key
and Subscribe key
Define your Postman Environment
As you explore the collection, you will see that several variables are defined with curly braces, such as {{pub_key}}
or {{sub_key}}
for each API. Not all APIs require every variable, but most APIs will generally require publish and subscribe keys, along with a channel ID and user ID.
The APIs used in this article use the variables below, so I recommend you create a new environment and define these up front, replacing the pub_key
and sub_key
with your own API keys. Leave auth
blank for now since that is related to the Access Manager
setting you left unchecked in the previous step. For every API discussed in this article, ensure the auth
query parameter is unchecked when invoking it.
After creating your environment, be sure that it is the active, selected environment in Postman (top right of the UI)
Using the Postman Collection
Publish and Subscribe
You are now ready to send and receive messages.
Publish a Simple Message
Load the Simple message POST API in Postman and make sure that the uuid
parameter is selected (everything else can remain unselected).
Notice that the pub_key
, sub_key
, channel
, and uuid
are being pulled in from your environment. If these are not blue, it means there are validation errors, so make sure you have the environment selected that you created in the previous step.
Also, notice that the template’s request body json is:
To receive the published message, use the PubNub debug console and enter the publish key, subscribe key, channel, and channel settings to match your environment. Send the message in Postman, and it will be received in the debug console on the subscribed channel:
Subscribe loop
Having successfully received a published a message in the debug console, the next step is to receive that message through the Subscribe
REST API. This is done in two steps:
Invoke the initial subscribe call, found under the ‘Subscribe’ folder. There are a lot of optional parameters in this request, just like all PubNub requests, but it is sufficient to just define
tt
as 0 anduuid
, from your demo environment.
You will receive a response from this initial request that looks similar to:
Your values for tt
and tr
will differ, but make a note of these as you will need them for the subsequent subscribe request.
Invoke the continued subscribe request, found immediately below the previous request in the ‘Subscribe’ folder. Populate the query params for
tt
andtr
as received from the previous call, so in my case, this would be as follows:
When you hit ‘Send’ to invoke the API, it will wait for a new message to arrive. You can return to the Simple message API and invoke it again. After doing so, you will see the Subscribe response is similar to the following, though your values for tt
and tr
will differ:
I also modified the message body to make it slightly different from the first request.
Continue to invoke the subscribe request to receive more messages
The subscribe response included new values for tt
and tr
(17542984138681437
and 43
in the above example, respectively), so be sure to modify the request each time to ensure the latest data is read.
Message Persistence
Provided you have persistence enabled on your PubNub keyset, every message you send over PubNub will be stored and can be retrieved as needed. For example, when somebody loads your chat app, they can catch up on messages received whilst they were offline.
Fetch Messages
The fetch messages API shows how to retrieve messages from a named channel. The API supports returning up to 100 messages in a single call, after which the responses will be paged using the start
and end
parameters. Also, notice that this API does not require the pub_key
because no messages are published, though the sub_key
is still needed to read the channel contents.
Here, you can see the result of calling this API after running through the previous steps of this article: it returns two messages with their associated timetokens. The meta
and custom_message_type
fields are empty, but they can be used to add context messages such as message actions or message types, respectively.
Presence
PubNub's presence can show you the number of users currently subscribed to a channel, which can be used to determine who is ‘online’ or ‘offline’.
The easiest way to experience Presence with this collection is through the ‘Heartbeat’, ‘Leave’, and ‘Here Now’ Postman folders.
Get User Presence
Firstly, load the “Get list of UUIDs subscribed to channel” API, which can be found under the ‘Presence’ then ‘Here Now (Check present users)’ folders.
Executing this API, I get the following response:
Wait, why is there a user already present? I thought the same thing, then I realized I was still subscribed to the channel in the PubNub debug console, from when I published the simple message earlier.
Control User Presence
Now load the “Announce heartbeat” API, which can be found under the ‘Presence’ then ‘Hearbeat’ folders.
Run the ‘Announce heartbeat’ API, then re-run the ‘Here Now’ API. You will see the following output:
Notice that an additional user, darryn
, is now considered present on the channel. This user ID was associated with the ‘Announce heartbeat’ request.
The heartbeat request will time out after 300
seconds (5 minutes), so you will need to resend it before this interval for the user to continue to be considered present on the channel.
To leave the channel early, load the “Announce leave” API, which can be found under the ‘Presence’ then ‘Leave’ folder.
Run the ‘Announce leave’ API, then re-run the ‘Here Now’ API. You will see the following output:
The user associated with the ‘leave’, darryn
, is no longer present on the channel. The old user related to the debug console, darryn2
, remains associated because the debug console is continuing to issue heartbeats automatically.
App Context
PubNub app context lets you store and manage metadata for your users, channels, and the relationships between them. That data is available with the same real-time availability and scalability that customers expect from PubNub.
For example, a User object might have a name
, email
, or avatar
. A Channel object might have status
or category
properties, and the relationships (memberships) between channels and users can also have metadata such as join date
or role
.
The REST API can be used to create, modify, and delete this metadata, and the Postman collection provides examples for Users, Channels, and Memberships. I will use User metadata as an example to keep this article focused.
Get User App Context
Run the “Get All Users” API, which can be found in the ‘App Context’ then ‘APP CONTEXT (USER)’ folders. You will see the following output:
Wait? Didn’t we have two users when running the Presence API?
Yes, but technically, those were user IDs
, not User objects stored in the App Context. Currently, this app has zero App Context Users, which is why the returned array is empty.
Set User App Context
To create a user, load the “Set User Metadata” API and look at the provided Body object:
You can modify this body data as required, and add/remove any fields to the custom
object, but the default gives you a good starting point. Note that the {{user_name}}
and {{user_email}}
variables should be defined in your Postman environment if you followed the setup steps earlier in this article.
After executing the “Set User Metadata” API, return to the “Get All Users” API and rerun it, you will see the following:
Something gone wrong?
Always be sure you are running queries against your forked Postman collection and your own PubNub keyset. By default, the Postman collection uses a demo
keyset, which has a series of predefined User objects that cannot be modified.
As an aside, if you have BizOps Workspace enabled on your PubNub account, or you start a free trial, you can find or create new users in the admin portal under ‘User Management’
Other Capabilities
You should now have all the information you need to explore the remaining capabilities of our Postman collection. Remember, if you get stuck, you can find documentation in the description for each folder in the collection, and our comprehensive REST API documentation is also available.
Capabilities of our postman collection not covered in this article:
Firing a PubNub signal
Triggering a PubNub function
Presence State
Files (sending/downloading)
Message counts and message actions
Channel groups
Push Notifications
Securing your application
You may have noticed that all of the public APIs discussed in this article accepted an auth
parameter, which was always left unspecified. This is the authentication token your server provides, containing the permissions granted to the user. After enabling ‘Access Manager’ on your PubNub keyset, only requests containing this auth
parameter will be allowed.
For a full explanation, see the Access control documentation, but in summary:
Your client will request a token from your server.
Your server will create a token using either the PubNub SDK or the PubNub Access Manager REST API
The generated token is passed back to the client
The client provides the token in all API calls in the
auth
parameter.
For example, consider the earlier App Context API calls: you would not want the user to modify the metadata for any user other than themselves, so when defining the token permissions, they would be given RW access to their own data, but they could not call “Set User Metadata” for any other user.
Next Steps
Sign up for a free PubNub account at https://admin.pubnub.com/
Fork our Postman collection
Configure your Postman environment
Start sending and receiving messages through PubNub
Check out our latest release notes
If you have any questions, our support or devrel teams are happy to help.