ONE DAY SALE

Free Salesforce Developers Tutorials >

Chapter 13 - API >

REST API Part 1

REST API Part 1

What You’ll Learn


S2 Labs

What Is REST API?

REST stands for “Representational State Transfer”. The Force.com REST API lets you integrate with Force.com applications using simple HTTP methods, in either XML or JSON formats, making this 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 with XML so the HTML pages can consume the same with ease. REST is useful for restricted-profile devices, such as mobile, for which the overhead of additional parameters is less (e.g., headers). 
  • REST has better performance and scalability. REST reads can be cached. A REST-based implementation is simple compared to SOAP. 
  • 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 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 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. 
  • Obtain detailed information about a Salesforce object, such as Account, User, or custom object. 
  • 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 that can be called by an HTTP GET request. 

APEX REST Methods 

Apex REST supports two formats for representations of resources: JSON and XML. JSON representations are passed by default in the body of a request or response, and the format is indicated by the Content-Type property in the HTTP 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 RestContextobject. This example shows how to access these objects through RestContext: 

RestRequest req = RestContext.request; 

RestResponse res = RestContext.response;

  • If the Apex method 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 and make a call with an unexpired password to be able to call Apex Web service methods. 

Salesforce Developer

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 that is exposed as a REST web service and then we will use Postman to make a call to this web service. 

Steps To Use 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 = '/LeadCreate/*')
global with sharing class CreateLead {
    @HttpPost
    global static String doPost() {
        String fieldValue;
        String fieldName;
        String FName;
        String LName;
        String Comp;
        String str = 'Task Completed';
        List < String > LeadList = new String[3];
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response; // Apex REST Methods 
        System.debug('Param is ' + req.params);
        System.debug('Body is ' + req.requestBody);
        String arr = req.requestBody.toString();
        //Json-parser is used to get schema of content i:e what is the actual content// JSONParser parser =JSON.createParser(arr); 
        while (parser.nextToken() != null) {
            if (parser.getCurrentToken() != JSONToken.END_OBJECT) {
                //parser.nextToken(); 
                parser.nextValue();
                fieldName = parser.getCurrentName();
                fieldValue = parser.getText();
                if (fieldName == 'First Name') {
                    FName = parser.getText();
                    LeadList.add(1, FName);
                } else if (fieldName == 'Last Name') {
                    LName = parser.getText();
                    LeadList.add(2, LName);
                } else if (fieldName == 'Company') {
                    Comp = parser.getText();
                    LeadList.add(3, Comp);
                }
                System.debug('List Values are ' + LeadList);
            }
        }
        //Create a lead object with appropriate data 
        Lead lc = new Lead(FirstName = LeadList.get(1), LastName = LeadList.get(2), Company = LeadList.get(3));
        insert lc; //insert record in salesforce 
        String leadId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
        return str; //Return result; 
    }
}

This apex class is used to insert leads into your salesforce account with First name, Last name, and Company name using APEX REST API. 

Now to call this web service from outside we need to authenticate our call as Salesforce uses OAuth so without authentication we cannot call this web service.

Note:

Find the rest of the steps in the other blogs.

Salesforce Admin Training

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

This 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 what’s going on with the consumer. 

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. 

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

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