Salesforce.com APEX REST + oAuth

We are building an integration between Salesforce.com and a custom iPhone application.  The system has the following high level requirements:

1) Salesforce.com will stand up a custom API for communication with the iPhone.  Apex Rest web services will be used.

2) oAuth will be used for the iPhone to authenticate into Salesforce.com.

There were enough nuances in building the application that I thought this subject deserved its own post.  I use a few tools tools as a test client for the API:

1) Firefox RESTClient (https://addons.mozilla.org/en-us/firefox/addon/restclient/)  (I will illustrate this in the blog entry)

2) cURL (http://curl.haxx.se/) (this is a little finicky, especially in windows)

3) Custom Java application (perhaps a later post can be on the client side.  It is just a test harness though)

Step 1 – Building the Salesforce.com custom RESTful API

I am going to make the round-robin on this system as simple as possible.  So all this API will do is return a SOQL query of all accounts in the system.  The API is not bulkified or tested, so keep that in mind as you build your actual production application.

resttest1.cls

@RestResource(urlMapping='/resttest1/*')
global with sharing class resttest1 {
@HttpGet
global static List<Account> doGet()
{
      return Database.query('select AccountNumber from Account');
}

@RestResource – defines the endpoint that we will later use to hit the URL of the custom API.

@HttpGet – defines the function to be called when issuing an HTTP GET command from the client.

return (Database.query(….); – APEX rest will automatically handle the tokenizing of this list into JSON or XML format.

Upon saving (and successful compilation) the APEX class generates the RESTful endpoint.  That’s it!

Step 2 – Set Up Salesforce.com to be an oAuth provider

External applications could utilize a session variable or oAuth to authenticate into the API.  I am using oAuth: I can’t determine any other way to authenticate myself using solely RESTful styles.  Session based authentication would require me to use the Enterprise WSDL and a SOAP client to login first.

setupremoteaccess

After creating a remote access record, you are given your oAuth consumer key and oAuth consumer secret.  Those are required in the client application to authenticate.

consumersecret

That’s it – you are ready to connect to the web service.   Pretty easy!

Step 3 – Accessing the RESTful web service using RESTClient

I love using Firefox’s RESTClient Add-on.  It is a perfect debugging tool for issuing RESTful commands and processing the return.

RESTClient

The next step is to authenticate into SFDC.  Using RESTClient “POST” to the following URL:

https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=ABCDEF&client_secret=1234567890&username=USERNAME@CLOUDPREMISE.COM&password=SFDCPW&TOKEN
  • where ABCDEF is the consumer key from above
  • where 1234567890 is the consumer secret above
  • where USERNAME@CLOUDPREMISE.COM is the user you want to log in as
  • where SFDCPW&TOKEN is the users Salesforce.com password and security token appended together
Use the following HTTP Headers:
  • Accept: */* (Lack of this header returns the response in XML for some reason)
  • X-PrettyPrint: 1 (optional – will help you to read the response)

After POSTing this to Salesforce.com, you should receive a response such as:

oAuth-authentication-response

Take note of the following parameters in the response:

  • “instance_url” : “https://na9.salesforce.com&#8221; (all future http requests would be made to this URL location)
  • “access_token” : “00DE000……” (all subsequent http requests should include this as the oAuth authentication token)
Now you are ready to call your web service.  Because the web service annotation was @HttpGet, you need to use a GET command:
  • URL= https://na9.salesforce.com/services/apexrest/resttest1/
  • Headers:
    • Accept: */*
    • X-PrettyPrint: 1 (Optional – If you want to be able to read the response)
    • Authorization: OAuth 00DE000….
Web-Service-Response1
Wa la – you have built a RESTful integration to Salesforce.com.

Using this method you can now:

  1. Write an actual production web service
  2. Write an actual client that can easily access the methods of the web service

It is very simple and very powerful.  Have fun!

ApexRest is generally new and I have found the documentation to be sub-par.  However, here is what I used to find my way around:

http://developer.force.com/REST (Official Salesforce.com site)

http://www.salesforce.com/us/developer/docs/api_rest/index_Left.htm#StartTopic=Content/quickstart_oauth.htm (Official Salesforce.com documentation)

http://blog.cloudspokes.com/2011/07/building-apis-with-salesforcecom-apex.html (CloudSpokes has some great coverage)

http://boards.developerforce.com/t5/REST-API-Integration/bd-p/integration (Official forums)

http://www.modelmetrics.com/tomgersic/oauth-2-0-for-salesforce-com/ (Model Metrics has a good blog posting on oAuth with SFDC)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: