Getting Started with the Chatter REST API

Abstract

Salesforce Chatter provides businesses with the collaboration tools consumers have become accustomed to through popular social networking sites such as Facebook. However, Chatter is designed for the enterprise, allowing private, secure, and trusted collaboration around your business data.

The Chatter REST API lets you access Chatter information via an optimized REST-based API accessible from any platform. Developers can now build social applications for mobile devices, or highly interactive websites, quickly and efficiently.

This article describes the major aspects of the Chatter REST API, key resources needed for developing apps around the API, code samples in multiple languages for common use cases, as well as a complete sample Ruby on Rails and jQuery Mobile app to help you quickly get started building Chatter REST API based applications. If you need an introduction to Chatter itself, see the Chatter resource page.

Introduction

Social networking sites and the explosive growth of mobile and tablet devices are changing the way consumers and businesses interact with, and share, data. At the heart of all of this sharing of data and collaboration is information --- information about who users are, their interests, friends, likes and dislikes, and even where they are are geographically --- information about data too. Chatter has all these data - and the API lets you target these mobile devices and other integrations using a clean and highly efficient API.

For example, once authenticated, the API can retrieve your entire newsfeed with a single call. Here is what it looks like in Java for an Android application:

OAuthTokens myTokens = globalState.getAccessTokens();
String url = myTokens.get_instance_url() + "/services/data/v23.0/chatter/feeds/news/me";
HttpGet req = new HttpGet(url);
req.setHeader("Authorization", "OAuth " + myTokens.get_access_token());
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(req);


That's it - a simple HTTP GET request. The resulting JSON payload contains everything related to the newsfeed including comments, likes, and even pagination! The rest of this article describes the API in a little more detail, and how to use it to code up some common use cases.

The Chatter REST API Resources

As the name implies, the Chatter REST API is a REST-based service. What this means is that you can interact with the service via URIs using an HTTP method (GET, POST, DELETE, HEAD). At the end of the day, you need to understand the set of URLs that you will be interacting with, which is what this section is about.

If you are unfamiliar working with the Force.com platform, your unique application instance is accessible via an instance URL. Let's assume your instance URL looks like the following:

https://na1.salesforce.com/

Now you have a reference to the application instance, you can append the service URI, which includes a reference to the version of the Force.com API, to the instance URL. Note that the Chatter REST API is only available for version 22 or greater of the API. Let's add our service URI to our instance URL:

https://na1.salesforce.com/services/data/v22.0

Finally, depending on which action you wish to perform, you can append the resource URI to access the specific service.

The following table summarizes the primary resources provided.

Name URI Description
Comments /chatter/comments/commentId Return the comments for a particular post
Feed-Items /chatter/feed-items/feedItemId Return a feed for a particular entity (person or record)
Group-Membership /chatter/group-memberships/membershipId Return details on a particular group such as the owner
Groups /chatter/groups/groupId Return detailed information about an individual group
Likes /chatter/likes/likeId Return detailed information about who liked a particular entity
News Feed /chatter/feeds/news/userId Return the news feed of a particular user.
Record Feed /chatter/feeds/record/recordId Return a feed for an entity (person, record, or group)
Subscription /chatter/subscriptions/subscriptionId Return a list of all entities (person, record, or group) following a particular entity
To Feed /chatter/feeds/to/userId Return a list of entities where a user has been @mentioned
User-Profile Feed /chatter/feeds/user-profile/userId News Feed resource by including posts, status, group and record updates.
Users /chatter/users/userId Returns a user's Chatter profile details, such as email, phone number, status, profile image, and "About Me"

Continuing with the example, if you want to retrieve a user's profile details, and the user has an ID of 0015000000Gv7qJ, then your final URL will be

https://na1.salesforce.com/services/data/v22.0/chatter/users/0015000000Gv7qJ

To retrieve the user data, you would have to issue an HTTP GET on this resource - much like the sample code in the previous section.

The Chatter REST API Developer's Guide provides more information regarding which HTTP methods are supported, relationships, and a sample of each resource.

Accessing Resources with the 'me' keyword

Many of the resources described above use the userId as the record identifier for the Chatter REST API to retrieve information for a particular user. In addition to the userId, users may query their own information using the me attribute. For example, assuming I have already authenticated against Force.com, I can retrieve my own profile details using the following resource URI:

/chatter/users/me

Or I could retrieve my news feed from:

/chatter/feeds/news/me/feed-items

This is a nice convenience, that is used in some of the following code samples.

Building Mobile apps using the Chatter REST API

Building apps, and in particular mobile apps, using the Chatter REST API typically falls into four parts:

  • Signing up for a free Force.com Developer Edition account
  • Creating the authentication logic in your app
  • Using the resources described in the previous section to issue an HTTP request
  • Working with the response

The remainder of this article will focus on some of the primary use cases you are likely to encounter when building apps. The great thing about being a REST based API is that the Chatter REST API is very language independent. The samples contained in this article will provide examples in Java, Objective C, JavaScript and Ruby On Rails. You are not limited to only these languages of course, as REST uses the HTTP protocol.

Sample Application

Sometimes samples alone are not enough to get you up and running on a new technology quickly. In addition to the samples contained in this article, a complete end-to-end sample application written in Ruby on Rails is available. Check out the sample application.

Here's a short video of the sample application in action:

Let's now look at some code.

Sign Up for a Free Force.com Developer Edition Account

If you are not already a member of the Force.com developer community, go to http://developer.force.com/join and follow the instructions for signing up for a free Developer Edition organization. Even if you already have Enterprise Edition or Unlimited Edition, use Developer Edition for developing, staging, and testing your solutions against sample data to protect your organization’s live data.

If you already have a Developer Edition organization, verify that your user profile has the “API Enabled” permission selected. This permission is enabled by default, but may have been changed by an administrator. For more information, see the help in the user interface.

Authenticating with OAuth

Before you can access the Chatter REST API, you need to be authenticated. OAuth2 is preferred approach for authentication when using the Chatter REST API, and in particular for mobile applications.

If you are not familiar with OAuth, please check out the Digging Deeper with OAuth2 article for a great overview of OAuth on the Force.com platform.

Two items in particular, which are returned as part of a successful OAuth2 authentication, are worth highlighting here.

  • First is the actual OAuth token, which you are required to set in the request header for each Chatter REST API call.
  • Second is the instance URL which points to your org. This is the base URL you need when constructing the URL of the Chatter resource in the API.

With an understanding of OAuth2, your specific implementation depends on which language you are building your app on. Here are a few guides, with code samples to get you going:

You may well be able to use other standard OAuth 2.0 libraries in your language of choice. Check out OAuth.net for a list of many of the most popular libraries.

Retrieving Information

You've got your account, and you've authenticated. Let's now look at how to retrieve information.

About Me

One of the most common use cases with the Chatter REST API is to retrieve a particular users information: their name, profile image, phone numbers, and so on. The following Ruby example encapsulates the REST call in a class creatively called Chatter. Every Chatter REST API call must include an Authorization header to pass the OAuth token you obtained when you first authenticated against Force.com. We are also using the 'me' keyword and providing a convenient get_my_info method to make working with the API even easier.

 require 'rubygems'
 require 'httparty'

 class Chatter
    include HTTParty
     headers 'Authorization' => "OAuth #{ENV['sfdc_token']}"
     format :json
  
   
   def self.root_url
     @root_url = ENV['sfdc_instance_url'] + "/services/data/v" + 
                        ENV['sfdc_api_version']+"/chatter"
   end

   def self.get_users_info(id)
     get(Chatter.root_url+"/users/"+id)
   end

   def self.get_my_info
     Chatter.get_users_info("me")
   end
 end

Note how we simple construct the URL using the instance URL and service URI and the appropriate Chatter REST API resource (in this case, /chatter/users/).

Here is what my About Me page looks like running the sample application in Safari on my local machine, with the JSON response payload looking like this:

About Me home page

Chatter profile images

The Chatter profile image returns the ["photo"] element of the JSON response. Depending on which language you are using, you may handle working with JSON differently. For example, in the Ruby on Rails sample application, where we have used HTTParty to map the response back to a hashmap. Regardless on which language you use, the JSON response will include a ["smallPhotoUrl"] and ["largePhotoUrl"] element.

The smallPhotoUrl, and largePhotoUrl elements each contain a URL pointing the image file of a photo. This URL is relative to the instance of Force.com your Remote Access provider is running on. In addition, in order to access the photo you need to provide your OAuth token for authentication. For example, here is what your image tag may look like if you have implemented your app for an Android device:

String photoURL = createdBy.getJSONObject("photo").getString("smallPhotoUrl");
String completePhotoURL = loginResult.getInstanceUrl() + photoURL + "?oauth_token="+ loginResult.getAccessToken();
iDownloader.download(completePhotoURL, thumbnail);

Current Status

The great thing with the Chatter REST API is that with a single call, we have all the information we need to display all the user details. The trick is understand the JSON response. The ["currentStatus"]["body"]["text"] element for example, includes the users current status message. We could set this into a table cell in Objective-C like so:

 cell.textLabel.text =  [currStatusBody objectForKey:@"text"];

Phone numbers

Chatter profiles allow you to specify multiple phone numbers such as work, mobile etc. We can loop through all the phone numbers and display them in our user interface. Because we expect our app to run on mobile devices, we can use the tel:// protocol which allows users using an iPhone to click on the phone number and be presented with a call dialog. Here is what our Rails code may look like when looping through the response:

<% @userInfo["phoneNumbers"].each do |ph| %>
    < div>
         Phone <%= ph["type"]%>:
         <a href='tel:<%= ph["number"] %>' rel="external"><%= ph["number"] %></a>
    < /div>
<% end %>
Making a call from my iPhone with Chatter data

Note: In order to test the tel:// support, you will need to access your app from a real iPhone. The simulator does not support 'make a call'. In my example, I deployed my app to Heroku, and logged into the app via my iPhone's Safari browser. (Oh, and no, that is not my real number in case you were wondering.)

News Feed

Another very common requirement when using the Chatter REST API is to display a news feed of a particular person, record, or even yourself. We can make a single call to the NewsFeed resource to retrieve all of the information we need including, comments, likes, and more.

The following example, written in Objective-C, uses the 'me' keyword to retrieve the current users news feed:

NSString *res_url = [NSString stringWithFormat:@"%@/services/data/v22.0/chatter/feeds/news/me/feed-items", [auth.parameters objectForKey:@"instance_url"]];  

Here's what the news feed looks like in the sample application:

My News Feed

Pagination

I started this article by mentioning that the Chatter REST API is an optimized feed for Chatter information. One such optimization is the support for pagination. Just like any social networking site, a Chatter news feed can be pretty big. It does not always make sense to return the entire feed, especially for a mobile device. The news feed, and other feeds supported by the Chatter REST API, return the first twenty results and include next, current, and previous page URLs for pagination. If you are on the first page, the previous page URL will be null, and the same will be true for next page if you were at the last page.

In order to retrieve the next, or previous page via the Chatter REST API, we append the value of the ["feedItems"]["previousPageUrl"], or ["feedItems"]["nextPageUrl"] element to the instance URL that is returned as part of a successful OAuth2 authentication request. If either the previousPageUrl or nextPageUrl elements are null, you know there is no more results to retrieve.

A typical use case when using pagination, is to check for this null value, and show or hide next and previous buttons in my UI. Here is an example in Ruby on Rails using jQuery Mobile to add my control buttons to the page footer:

< div data-role="footer">
       <% if (!@feed["feedItems"]["previousPageUrl"].nil?)%>
              <%= link_to 'Newer', 
                  {:action => "mynewsfeed", :controller => "my_chatter", 
                      :previouspageurl => @feed["feedItems"]["previousPageUrl"]}, "class" => "ui-btn-left",
                     "data-icon" => "arrow-l", "data-iconpos" => "left", "data-transition" => "slidedown"%>
             <% end %>
     <% if (!@feed["feedItems"]["nextPageUrl"].nil?)%>
           <%= link_to 'Older',
                   {:action => "mynewsfeed", :controller => "my_chatter", 
                    :nextpageurl => @feed["feedItems"]["nextPageUrl"]},  "class" => "ui-btn-right",
                    "data-icon" => "arrow-r", "data-iconpos" => "right", "data-transition" => "slideup"%>
          <% end %>
< /div>


Assuming we have retrieved the nextPageURL, or previousPageURL from our JSON response, here is how we could retrieve the next page of results using the Force.com JavaScript REST toolkit:

/* Low level utility function to call the Salesforce endpoint.
    * @param path resource path relative to /services/data
    * @param callback function to which response will be passed
*/
forcetk.Client.prototype.ajax(myPageUrl, errorCallback)

Creating Information using the REST API

The Chatter REST API supports updates via HTTP POST requests. This makes it very easy to quickly implement typical update operations such as changing your current status, leaving a comment or liking a post.

Updating your Current Status

We can update our current status by adding a new post to our feed. Don't forget, we can use the 'me' keyword to make things even easier. Here is an example in Java if you were writing an Android app:

OAuthTokens myTokens = globalState.getAccessTokens();
String url = myTokens.get_instance_url() + "/services/data/v22.0/chatter/feeds/news/me/feed-items?text=New+status+post";
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "OAuth " + myTokens.get_access_token());
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);

Adding a Comment

Adding a comment is very similar to updating your status---both of these actions require an HTTP POST---the only difference being the resource you use. Here is an example from Ruby where we are passing in the current posts (referred to as a feed item) id, and the actual comment as a class to make our code nice and neat and loosely coupled.

def self.add_comment(comment)
       post(Chatter.root_url+"/feed-items/"+comment.feeditemid+"/comments?text="+CGI::escape(comment.body))
 end

Liking a Post

The final example we will cover is how to like a post. If you have not realized by now, it is pretty easy to work with the Chatter REST API. Liking a Post is simply a matter of using the right resource. Let's use our Force.com JavaScript REST toolkit again:

forcetk.Client.prototype.ajax(/feed-items/feeditemid/likes", callback, null, "POST", null);

Summary

The Chatter REST API provides an optimized API to access Salesforce Chatter information. The API is designed specifically to allow developers on any platform, and in particular mobile devices, to build custom social applications quickly. Being a REST based API, all information is accessed via HTTP requests to particular resources such as retrieving news feeds, or adding a comment.

Throughout the article, we highlighted some of the primary use cases developers are likely to encounter when building applications with the Chatter REST API. The examples included in the article were written in different languages to highlight the open nature of the Chatter REST API, which makes it extremely easy to built social apps on any platform.

Whilst we only touched on some of the resources available to developers, this article also references a complete sample application, written in Ruby on Rails and jQuery Mobile, which provides an end-to-end example of using the Chatter REST API.

Related Links

About the Author

Quinton Wall is a Sr. Developer Evangelist at salesforce.com, and an aspiring fantasy author. He is a regular speaker at cloud conferences around the world and semi-colon switches between Java, Ruby and Objective-C believing that the difference between a good solution and a great one is knowing which technology is the best fit regardless of space, speed, or compiler.