Build Salesforce.com REST API

  1. Write global Apex class with URL Mapping
  2. Authentication process with OAuth2.0

Step#1: Write global Apex class with Rest Resource

Understand the annotations provided by Salesforce.com

@RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.

@HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP GET request is sent, and returns the specified resource

@HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP POST request is sent, and creates a new resource.

@HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PUT request is sent, and creates or updates the specified resource.

@HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PATCH request is sent, and updates the specified resource.

@HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP DELETE request is sent, and deletes the specified resource.

Check this example

/**
  * This Apex Class is REST API
**/
@RestResource(urlMapping='/CustomObjectUpdate/*')
global class SampleRESTAPIClass {
/**
    * This method is post method in this REST API. 
    * Request:
    * [{  "Email":"test@test.com","Business":"Business One" ,"Connect ID":"AXWO7899"}]    
    * Response:
    * [{  "Email":"test@test.com","Status":"Success"}] -- Status can be Success/Fail
    * 
  **/
 @HttpPost
    global static String updateCustomObject() {
         //Fetching request
         RestRequest  req     = RestContext.request;   
         //Getting JSON String from request body
         String     jsonInput  = req.requestBody.toString();
         JSONParser   parser     = JSON.createParser(jsonInput);

         //Iterate through parser and get values updated on Custom Object
         //------
         
         //Below JSON Generator create response string
         JSONGenerator jsonGenerator = JSON.createGenerator(true);
      
    jsonGenerator.writeStartArray();
      jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField('Email',emailFromJSONInput);
        jsonGenerator.writeStringField('Status', 'Success/Fail');
      jsonGenerator.writeEndObject();
    jsonGenerator.writeEndArray();
    
    String responseJSONString = jsonGenerator.getAsString();
         
        return responseJSONString;
    }// method
}// class

									

In the above code, @RestResource(urlMapping=’/CustomObjectUpdate/*’)  represents URL mapping. In this case end point URL you need to share should be like this

https://instance.salesforce.com/services/apexrest/CustomObjectUpdate

@HttpPostannotation is used at the method level.

 

Step#2: Authentication process with OAuth2.0

For security reason, Salesforce.com REST APIs’ can only be accessed by consumer through proper authentication. OAuth (Open Authorization) is an open protocol to allow secure API authorization in a simple and standardized way from desktop and web applications. The Force.com platform implements the OAuth 2.0 Authorization Framework, so users can authorize applications to access Force.com resources.

You can suggest client to use OAuth 2.0 via one of six authentication flows:

Web Server, User-Agent, JWT Bearer Token Flow, SAML Bearer Assertion Flow, SAML Assertion Flow, Username and Password Flows.

In this section we are using Username and Password flow, please check in online help for more details regarding other flows

 

 

OAuth 2.0 Username-Password Flow:

The username-password authentication flow can be used to authenticate when the consumer already has the user’s credentials.

  1. Connected App
  2. OAuth call to get Session ID
  3. Calling Salesforce.com REST API

Create Connected App:

To make OAuth call, Consumer Key and Consumer Secret needed from Salesforce.com. Follow below steps to generate Consumer Key and Consumer Secret

  • From Setup, click Create | Apps
  • In the Connected Apps section, click New
  • Under API (Enable OAuth Settings) section, check Enable OAuth Settings and enter Callback URL as https://instance.salesforce.com/services/oauth2/token and here Full Access provided
  • After saving you will get Consumer Key, Consumer Secret value
Build Salesforce.com REST API

Build Salesforce.com REST API | CYUKT.COM

OAuth call to get Session ID:

To invoke Salesforce.com REST API, first OAuth call required to get Session ID. Below mentioned are production OAuth URLs’

For authorization https://login.salesforce.com/services/oauth2/authorize
For token requests https://login.salesforce.com/services/oauth2/token
For revoking OAuth tokens https://login.salesforce.com/services/oauth2/revoke

 

The consumer should make an out-of-band POST request to the token endpoint, with the following parameters:

Parameter Value
grant_type must be ‘password’ for this flow
client_id key from the connected app definition
client_secret Consumer secret from the connected app definition
Username End-user username
Password End-user password
Format Expected return format. This parameter is optional. The default is JSON. Valid Values are: urlencoded, json, xml

 

After the request is verified, Salesforce sends a response to the client. The following parameters are in the body of the response:

Parameter Value
access_token Salesforce session ID that can be used with the Web services API
token_type Value is ‘Bearer’ for all responses
instance_url URL indicating the instance of the user’s organization. This should be used when you are making REST API call
Id Identity URL
Signature Base64-encoded HMAC-SHA256 signature signed with the consumer’s private key containing the concatenated ID and issued_at. This can be used to verify the identity URL was not modified since it was sent by the server
issued_at When the signature was created

 

Calling Salesforce.com REST API:

After the above call consumer will get access_token(Session ID), instance_url in response. Put access_token in header and use the instance_url in endpoint URL and make call to rest resource.

Note: Use https://workbench.developerforce.com to test Salesforce.com REST API

This post was written by , posted on August 1, 2014 Friday at 12:40 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Visit Us On FacebookVisit Us On Twitter