Skip to main content

Rest API in Salesforce

 

REST API is a simple and powerful web service based on RESTful principles. It exposes all sorts of Salesforce functionality via REST resources and HTTP methods. For example, you can create, read, update, and delete (CRUD) records, search or query your data, retrieve object metadata, and access information about limits in your org. REST API supports both XML and JSON.

What Is REST API In Salesforce?

The Salesforce REST API lets you integrate with Salesforce applications using simple HTTP methods, in either JSON or XML formats, making this an ideal API for developing mobile applications or external clients. Salesforce also supports Apex REST, which lets you create Web services on Force.com using Apex.

HTTP Method Description
GET Retrieve data identified by a URL.
POST Create a resource or post data to the server.
DELETE Delete a resource identified by a URL.
PUT Create or replace the resource sent in the request body.
Why REST API

Because REST API has a lightweight request and response framework and is easy to use, it’s great for writing mobile and web apps.

Anatomy of a REST API CALL

Standard REST API In Salesforce

REST API is one of several web interfaces that you can use to access your Salesforce data without using the Salesforce user interface. With API access, you can perform operations and integrate Salesforce into your applications as you like. Here is Standard REST API to insert, update or delete a record by Rest API without any code.

1.Get a Record

Method :- Get
URL:- /services/data/v36.0/sobjects/Account/0019000001hE8af

2.Insert a Record in Salesforce

Method :- Post
URL:- /services/data/v36.0/sobjects/Account/
Request Body :-

{
"Name" : "Account from Rest API",
"phone" : "1111111111",
"website" : "www.salesforce1.com",
"numberOfEmployees" : "100",
"industry" : "Banking"
}

3.Delete a record in Salesforce

Method :- Delete
URL:-/services/data/v36.0/sobjects/Account/0019000001hE8apAAC

4.Update a record in Salesforce

Method :- Patch
URL:- /services/data/v36.0/sobjects/Account/0019000001hE8apAAC
Request Body :-

  {
{  
"Name" : "sample from Rest API",
"phone" : "1234567890"
}
}

5. Composite a Record

Using REST API composite resources are helpful to improve the application’s performance by minimizing the number of round-trips between the client and server.

Create Custom Rest API In Salesforce

Sometimes we need to do some customization in OOB REST API for some complex implementation.

HTTP Method Use Action
@RestResource(urlMapping=“url”) Defines the class as a custom Apex endpoint
@HttpGet Defines the function to be called via Http Get- Used to retrieve a record Read
@HttpDelete Used to delete a record Delete
@HttpPost Used to create a record Create
@HttpPatch Used to partially update a record Upsert
@HttpPut Used to fully update a record Update

Example of Custom Apex REST API in Salesforce.


@RestResource(urlMapping='/api/Account/*')
global with sharing class MyFirstRestAPIClass
{
    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String AccNumber = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE AccountNumber = :AccNumber ];
        return result;
    }

    @HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String AccNumber = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE AccountNumber = :AccNumber ];
        delete result;
    }

    @HttpPost
    global static String doPost(String name,String phone,String AccountNumber ) {
        Account acc = new Account();
        acc.name= name;
        acc.phone=phone;
        acc.AccountNumber =AccountNumber ;
        insert acc;
        
        return acc.id;
    }

}
As you can see, the class is annotated with @RestResource(urlMapping='/api/Account/*). The base endpoint for Apex REST is https://instance.salesforce.com/services/apexrest/. The URL mapping is appended to the base endpoint to form the endpoint for your REST service. For example, in the class example, the REST endpoint is

https://instance.salesforce.com/services/apexrest/api/Account/.

Test Class for REST API


@IsTest
private class MyFirstRestAPIClassTest {

    static testMethod void testGetMethod(){
        Account acc = new Account();
        acc.Name='Test';
        acc.AccountNumber ='12345';
        insert acc;
        
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/api/Account/12345';
        request.httpMethod = 'GET';
        RestContext.request = request;
        Account acct = MyFirstRestAPIClass.doGet();
        System.assert(acct != null);
        System.assertEquals('Test', acct.Name);
        
    }

    static testMethod void testPostMethod(){
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/api/Account/12345';
        request.httpMethod = 'POST';
        RestContext.request = request;
        String strId = MyFirstRestAPIClass.doPost('Amit','2345678','12345');
        System.assert(strId !=null );
    }

    static testMethod void testDeleteMethod(){
        Account acc = new Account();
        acc.Name='Test';
        acc.AccountNumber ='12345';
        insert acc;
        
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/api/Account/12345';
        request.httpMethod = 'DELETE';
        RestContext.request = request;
        MyFirstRestAPIClass.doDelete();
        
        List ListAcct = [SELECT Id FROM Account WHERE Id=:acc.id];
        System.assert(ListAcct.size() ==0 );
    }

}

Call Rest API From Apex Class

What about if we need to call REST API in Salesforce? Let see how we can call REST API from Apex class in Salesforce.



Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('EXTENRAL_REST_API_URL');
request.setMethod('GET');
HttpResponse response = http.send(request);
if(response.getStatusCode() == 200) 
{ 
// Deserialize the JSON string
results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
results.get('ELEMENT_NAME');
System.debug('Received the following ELEMENT_NAME:');
for(Object obj: lstObj) {
System.debug(obj);
}}

Send Data to a Service


Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('EXTENRAL_REST_API_URL');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody('{"ABC":"ABC"}');
HttpResponse response = http.send(request);

if(response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' + response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}