Rest API in Salesforce
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. 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"
}
2. Update a record in Salesforce
Method :- Patch
URL:- /services/data/v36.0/sobjects/Account/0019000001hE8apAAC
Request Body :-
{
"Name" : "Account from Rest API",
"phone" : "2333333"
}
3. Delete a record in Salesforce
Method :- Delete
URL:- /services/data/v36.0/sobjects/Account/0019000001hE8apAAC
4. Get a Record
Method :- Get
URL:- /services/data/v36.0/sobjects/Account/0019000001hE8af
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.
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 |
Here is 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<Account> ListAcct = [SELECT Id FROM Account WHERE Id=:acc.id]; System.assert(ListAcct.size() ==0 ); } }
Execute Your Apex REST Class In Workbench
We can use Workbench REST Explorer to test all the above APIs.
Step 1:- Open and log in.
Step 2:- Select Environment as Production and select the checkbox to agree on the terms and conditions then select log in with SalesforceStep 3:- In the Workbench tool select Utilities > REST Explorer
Step 4:- In the REST Explorer window paste the following URL in the box
Method:- Get
URL:- /services/apexrest/api/Account/12345Postman Tool
Force.com platform supports powerful web services API for interaction with external apps and salesforce.com. For secured interaction with third-party apps, Salesforce enforces the authentication process.
So far we learned about how to execute Salesforce REST API from an external system. Let’s see how to call external API in Salesforce
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 Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody()); List<Object> lstObj = (List<Object>) 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()); }