13

REST API Part 1

What Is REST API?

REST stands for “Representational State Transfer”. The REST API in Salesforce lets you integrate applications using simple HTTP methods in either XML or JSON, making it an ideal API for developing mobile applications or external clients. 

RESTs are best suited when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface. 

In other words, we can say that REST API provides a powerful, convenient, and simple Web services API for interacting with Force.com. 

Advantages of REST API

  • REST web services are stateless. You can test this condition by restarting the server and checking if interactions survive. 
  • REST services are easy to integrate with existing websites and are exposed via XML, making them easy for HTML pages to consume.
  • REST is useful for devices with a restricted profile, such as mobile devices, for which the overhead of additional parameters (e.g., headers) is lower. 
  • REST has better performance and scalability. REST reads can be cached.
  • A REST-based implementation is simpler than a SOAP-based one. 
  • Efficient (SOAP uses XML for all messages, REST can use smaller message formats). 

Force.com REST Resource 

A REST resource is an abstraction of a piece of information or an action. 

Each resource in the REST API is identified by a named Uniform Resource Identifier (URI) and is accessed using standard HTTP methods (HEAD, GET, POST, PUT, PATCH, DELETE). 

REST API in Salesforce is based on the usage of resources, their URIs, and the links between them. 

Use a resource to interact with your Salesforce org. For example, you can: 

  • Retrieve summary information about the API versions available to you. 
  • Perform a query or search. 
  • Update or delete records. 

Authentication Mechanism

Apex REST supports these authentication mechanisms: 

  • OAuth 2.0 
  • Session ID 

Exposing Data With Apex REST Web Service Methods 

You can expose your Apex classes and methods so that external applications can access your code and your application through the REST architecture. 

Introduction to Apex REST 

You can expose your Apex class and methods so that external applications can access your code and your application through the REST architecture. This is done

by defining your Apex class with the @RestResource annotation to expose it as a REST resource. Similarly, add annotations to your methods to expose them through REST. 

For example, you can add the @HttpGet annotation to your method to expose it as a REST resource accessible via an HTTP GET request. 

APEX REST Methods 

Apex REST supports two formats for representations of resources: JSON and XML. JSON representations are sent by default in the request or response body, and the format is indicated by the Content-Type header. 

If parameters are defined in the Apex method, an attempt is made to deserialize the request body into those parameters. If the Apex method has a non-void return type, the resource representation is serialized into the response body. 

RestRequest and RestResponse objects are available by default in your Apex methods through the static RestContext object. This example shows how to access these objects through RestContext:

RestRequest req = RestContext.request;  RestResponse res = RestContext.response;
  • If the REST API methods Salesforce has no parameters, Apex REST copies the HTTP request body into the RestRequest.requestBody property. If the method has parameters, then Apex REST attempts to deserialize the data into those parameters and the data won’t be deserialized into the RestRequest.requestBody property.
  • If a login call is made from the API for a user with an expired or temporary password, subsequent API calls to custom Apex REST Web service methods aren’t supported and result in the MUTUAL_AUTHENTICATION_FAILED error. Reset the user’s password, then call with the new password to access the Apex Web service methods.
Salesforce-Admin-Training-CTA

How to Create An Apex REST Web Service And Make A Callout 

Let us take an example to create a lead in Salesforce. In this, we will define the code in the APEX class exposed as a REST web service, and then use Postman to make a call to it. 

Steps To Use the REST Service

Create an Apex class in your instance from Setup by entering Apex Classes in the Quick Find box, then selecting Apex Classes. Click New and add the following code to your new class: 

Note: Sharing and Profiles permissions are also kept in consideration 

@RestResource(urlMapping = '/getAccCont') global class AccAndContAPI { @HttpPost global static string getAccountAndContact(){ //Handle Request RestRequest req = RestContext.request; String str = req.requestBody.tostring(); Map mapObj = (Map)json.deserializeUntyped(str); String accstr = String.valueof(mapObj.get('Name')); //Processing List accList = [SELECT Name, NumberOfEmployees, (select Name from Contacts) from Account where Name=:accstr LIMIT 1]; if(accList.isEmpty()) { return 'No Account Exists with name ' + accstr; } Map conMap = new Map(); Map resMap = new Map(); Account a = accList[0]; for(integer i=0; i nameWrapper = new Map(); nameWrapper.put('Name', a.Contacts[i].Name); conMap.put('Contact'+(i+1), nameWrapper); } resMap.put('Contacts', conMap); resMap.put('Name', a.Name); resMap.put('NumberOfEmployees', a.NumberOfEmployees); //Response String finalstr = JSON.serialize(resMap); return finalstr; } } // Request JSON: {“Name” : “Edge Coomunications”} // Response : { "NumberOfEmployees": 1000, "Name": "Edge Communications", "Contacts": { "Contact2": { "Name": "Sean Forbes" }, "Contact1": { "Name": "Rose Gonzalez" } } }

This apex class inserts leads into your Salesforce account with First name, Last name, and Company name using the APEX REST API. 

Now, to call this web service from outside, we need to authenticate our calls, as Salesforce uses OAuth. Without authentication, we cannot call this web service.

Note: Find the remaining steps in the other blogs.

Salesforce Developer

Where to Use REST API 

Case 1: Developing a Public API 

REST focuses on resource-based (or data-based) operations and inherits its operations (GET, PUT, POST, and DELETE) from HTTP

It makes it easy for both developers and web browsers to consume it, which is beneficial for public APIs where you don’t have control over how consumers use them. 

Case 2: Extensive Back-and-Forth Object Information 

APIs used by apps that require a lot of back-and-forth messaging should always use REST. 

For example, mobile applications. If a user attempts to upload something to a mobile app (say, an image to Instagram) and loses reception, REST allows the process to be retried without major interruption, once the user regains cell service. 

Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Frequently Asked Questions

What are HTTP methods in REST API?

REST APIs use Standard HTTP methods to operate on resources. GET, POST, PUT, and HEAD are some major Salesforce REST APIs.

What is the format used in REST API?

JSON and XML are the two formats supported by the Salesforce REST API. JSON is the default format because it is lightweight and easy to parse.

What is the difference between REST and SOAP?

REST is a stateless, lightweight web service protocol that uses HTTP methods. SOAP is a rigid protocol using XML for built-in security and transactions.

What is @RestResource in Apex?

@RestResource is an Apex class-level annotation that marks a class as a REST web service endpoint. The urlMapping parameter defines the URL path used to access external resources.

Book Free15-Minutes Career Counselling