How to create and use Apex Rest Services in Salesforce ?

The Force.com REST API lets you integrate external system with Force.com applications using simple HTTP methods, in either XML or JSON formats, making this an ideal API for developing mobile applications or third party applications.

Following are the benefits of using the REST API in your integrations:

  • Easy Access: Use standard HTTP method call-outs, available on every language and platform, to make requests and retrieve information from Force.com.
  • Flexible formats: Request and response can flow in XML or JSON format.
  • Standards-based security: Basic Authorization (Username/Password or SessionId), OAuth (Open Authorization) .
  • Data model: Standard/custom objects are accessible using REST API.
  • Very lightweight and easy to use as compared to SOAP based services.

Let’s create an Apex REST Services which can perform insert, update, delete records .  In the below example, we are querying, creating, updating and deleting Accounts by implementing a Rest-Based Service called AccountService.

Note: For updating and deleting Accounts, developer must pass the parameters while making a REST call.

Creating REST Service
@RestResource(urlMapping='/AccountService/*')
global class AccountService {

 @HttpGet
 global static List<Account> getAccounts() {
   List<Account> Accounts = [SELECT Id,Name from Account LIMIT 10];
   return Accounts;
 }

 @HttpPost 
 global static String createNewAccount(String Name) {
   Account a = new Account();
   a.Name = Name;
   insert a;

   return 'Account Created';
 }

 @HttpDelete
 global static String deleteAccountById() {
 
   RestRequest req = RestContext.request;
   String Id = req.params.get('Id');

   List<Account> a = [ Select ID from Account where Id= :Id];

   delete a;

   return 'Account Deleted';
 }

 @HttpPut
 global static String updateAccount(String Id, String NewName) {
   Account a = [ Select ID, Name from Account where Id= :Id];
   a.Name = NewName;
   update a;

   return 'Account Updated';
 }
}

In the above code,

  1. The REST service must be declared as global and static
  2. The keyword “@RestResource”  is used to signify that class should act as REST based web service.
  3. The urlMapping  property allows us to set path where the service will be available. This is how we set up the endpoint for the service. e.g.   https://.salesforce.com/services/apexrest/AccountService
  4. There are few http methods mentioned:-
    1. @HttpGet  – returning data using HTTP GET request.
    2. @HttpPut  – updating data using HTTP POST request.
    3. @HttpDelete –  deleting data using HTTP DELETE request.
    4. @HttpPost – inserting data using HTTP PUT request.
    5. @HttpPatch – upserting data using HTTP PUT request.
  5. In order to pass parameters to service,  we use RestRequest object in a method. See below sample code:
  6. RestRequest req = RestContext.request;
     String Id = req.params.get('Id');
Using REST Service

Invoke REST Service from Workbench : 

  1. login into workbench using below URL: https://workbench.developerforce.com/login.php
  2. From the menu , please choose utilities > click REST Explorer
  • GET – To get all the Accounts using @HttpGet
  1. Select HTTP GET  method from radio buttons.
  2. Enter the REST URI in the text box.
  3. We are making a HTTP GET call to retrieve all the accounts.
  4. Click on execute.
  5. Click on “Show Raw Response”.RestServiceWorkbench.png
  • Response Format: In the above screenshot, we can get response in XML or JSON by Clicking on “Headers” button and setting HTTP header with below code:
  • Content-Type: application/xml
    accept: application/xml
  • POST – To create an Account using @HttpPost
  1. Select HTTP POST method from radio buttons.
  2. Enter the REST URI in the text box.
  3. We are making POST call, so enter a body in JSON format.
  4. Click on execute, and see the raw response.

post

  • Delete an Account using @HttpDelete
  1. Select HTTP DELETE method from the radio buttons.
  2. Pass the account id as a parameter:
    /services/apexrest/AccountService?id=00141000009K7xLAAS
  3. Click on execute, and see the raw response.

Invoke REST SERVICE from APEX :

First you need to add the REST endpoint under Salesforce “Remote Site Settings”. To add the remote site settings, please follow the below steps:

  1. From Setup, enter Remote Site Settings in the Quick Find box, then select Remote Site Settings.
  2. Click New Remote Site.
  3. Enter Remote Site Name.
  4. Enter the URL for REST Service endpoint.
  5. Click Save.

remote-site-setting

Once the remote site setting is setup, now we can invoke our rest service using apex.

 

Call REST Service using OAuth

Now rest service is ready to be called from anywhere. In the following example,  we are making an external callout to our REST service using OAuth Session Id and we are using below endpoint, which is the following format: https://instance.salesforce.com/services/apexrest/Class_Name

We are hitting following end point from APEX https://na35.salesforce.com/services/apexrest/AccountService

public class RestServiceClass{
 
 @future (callout=true)
 public static void RestServiceMethod(String sessionId){

 HttpRequest req = new HttpRequest();
 req.setEndpoint('https://na35.salesforce.com/services/apexrest/AccountService');
 req.setMethod('GET'); 
 req.setHeader('Authorization', 'OAuth ' + sessionId);
 req.setHeader('Content-Type','application/json'); 
 req.setTimeout(120000);
 
  
 HttpResponse res = new HttpResponse();
 res = http.send(req);
 
 system.debug(res);
 }

 

Other Considerations:

  • We can set the Content-Type on the request header to Json or XML to get the results in respective formats.

rest_xml_header

  • If you have many records to process, consider using Bulk API, which is based on REST principles and optimized for large sets of data.
  • API Call limits to Salesforce will be enforced. Please see the link below:

https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_api.htm

For more information:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest.htm

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_code_samples.htm

 

One thought on “How to create and use Apex Rest Services in Salesforce ?

  1. Thanks, Ajomon!

    On Tue, Dec 13, 2016 at 12:13 PM, Ajomon Joseph wrote:

    > Ajomon Joseph posted: “The Force.com REST API lets you integrate > external system with Force.com applications using simple HTTP methods, in > either XML or JSON formats, making this an ideal API for developing mobile > applications or third party applications. Following are the ” >

    Like

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 )

Google+ photo

You are commenting using your Google+ 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