REST API Integration Salesforce apex

In this post we will see a working example for REST API integration. Generally when we use webservice or rest api we use it to integrate our salesforce instance with other systems. For a fresh salesforce developer having little or no knowledge about other programming languages like java, .net or other systems it becomes little difficult to get the real feel of integration specially if you haven't had the opportunity to work on real projects related to integration. Considering the dilemma of such fresh developers, i am writing this article which will demo REST api integration between two salesforce orgs. 

Rest api salesforce

In the example, we will be writing a apex class exposed as REST api in one org and in the second org we will consume that particular class. This will help us in learning both exposing and consuming REST API. Before we write the code let us see what pre-requisites are needed. 

First you will need two different salesforce developer orgs. Secondly, create a remote site setting with the url '' in the source org. Let us write our REST api class that we want to expose in the target org.

global with sharing class RESTCreateNewAccount{


    global static string createAccountRecord(String name) {
     string succError;
     account acc = new account(); = name;      
     insert acc;
     acc.accountsource = 'Other';
     update acc;
     succError = 'New account has been created. Account Record id is:';
     return succError;
    global static string updateAccountRecord(String name) {
       string returnmessage = 'Account are updated successfully';
       List<account> accupdateList = [select name,id,AccountSource from account where name =: name];
       for(account acc : accupdateList){
           acc.AccountSource = 'Web' ;
           returnmessage = returnmessage;
         update accupdateList;
       catch(exception ex){
         returnmessage = ex.getmessage();
       return returnmessage ;

Let us try to understand above class, specifically alien things(if you see closely theres only annotations that we need to understand rest of the things we use normally in our classes or controllers). Class has first line as @RestResource(urlMapping='/createNewAccountUsingRestAPI/*')

annotation '@RestResource' means you are exposing the class as REST api so that methods from this class can be called from outer systems. Secondly we have
--> urlMapping='/createNewAccountUsingRestAPI/*  this specifies the url that outer system needs to use to call that particular class.

Other annotations that we have used include @HttpPost and @HttpPut now this are being used against each method. @HttpPost is used to indicate that the method will have code to a dml that will create/insert new records on the other hand @HttpPut specifies that the code in that method will update the records (While writing the methods you have to make sure you follow these things other wise the code will give run time exception so make sure you only do update in @HttpPut method and so on). Apart from these method annotations we also have @Httpdelete and @HttpPatch annotations. Apart from annotations we also have to make sure the class is global for obvious reasons, class will be called by outside world.

In our @HttpPost method if you see closely we have written the code to do only a single and simple transactions of inserting one record which actually can be also be done by simply passing the information over a single url by outside system, but for sake for simplicity and understanding have used a REST exposed class in target org. Once we have the REST exposed class in target org its time to write a class in other org that would call above class. If you see the two methods above they create a new record and update an existing record, so when we will call 'post' method from our other org it will actually create the new account record in our target org.

Lets write a class in other org that will create a new account record in target org (by calling the exposed REST api class),

public class RestAPIcalloutExample{

   Public void loginToOtherOrgAndCreaetNewAccount(){

        /*Login to Other Salesforce Org to grab session id - begin*/
        HTTP h1 = new HTTP();
        HttpRequest request = new HttpRequest();      
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        request.setBody('<Envelope xmlns=""><Header/><Body><login xmlns=""><username>' + ''+ '</username><password>' +'my_password1234'+ '</password></login></Body></Envelope>');
        String SERVER_URL;
        String SESSION_ID;
        HTTPResponse loginResponse = h1.send(request);     
        Dom.Document doc = loginResponse.getBodyDocument();
        Dom.XMLNode receivedXml= doc.getRootElement();
        SESSION_ID = receivedXml.getChildElement('Body', '').getChildElement('loginResponse', '').getChildElement('result','').getChildElement('sessionId','') .getText();      
        /*Login to Other salesforce Org to grab session id - finish*/
        /* Send https request to the custom REST API defined in other org that has urlmapping as 'createNewAccountUsingRestAPI' -begin*/
        HTTP h2 = new HTTP();
        HttpRequest request2CreateAccount = new HttpRequest();
        request2CreateAccount.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request2CreateAccount.setHeader('Accept', 'application/json');
        request2CreateAccount.setHeader('SOAPAction', '""');
        request2CreateAccount.setbody('{"name":"Cloudforce4u Technologies Ltd"}');
        request2CreateAccount.setHeader('Authorization', 'OAuth '+SESSION_ID);             
        HTTPResponse resppnceFromOtherSFOrg = h2.send(request2CreateAccount);
        /* Send https request to the custom REST API defined in other org that hass urlmapping as updateaccountrec - finish*/

Before we decode each line of above class lets write point wise what we we need to do so as to call the target org exposed REST api class. It is obviously not the way (create instance of the class and then call that method)we call normal method from different classes within salesforce orgs.

1. Programatically login to the target org using login url, username and password
2. Once you are logged in try to get the session id
3. call the exposed class method using http callout

Now lets decode the whole code for each of the 3 steps separately.
1. Programatically  login to the target org using login url, username and password
You can login to salesforce org either by soap api or by REST api but since here we are discussing REST lets use REST to login and 

Subsequently get the session id. So basically in REST we will have to create a instance of http, httpresponse and then send the request over http. Now to send this http request what all things need to set? below are the details
a. End point url (this will the login url)
b. Kind of method you want to call POST,PUT etc (we have set it to POST that means we we will be calling our post method from target org)
c. Header like body content type, it could be json or xml in our case we are using xml.
d. set body of the request which will have username,password

Once our request is ready we need to send it over http and store the response in httpresponse variable.

2. Once you are logged in try to get the session id
Once we get response in httpresponse variable its time to segregate the response and get the real thing out of it. The response will have many things but we should take out the exact thing/data that we need, in this case it is the session id. When we sent the login request in step 1 it logged in and whenever you log in to slaesforce it automatically creates a session id, this session id will be needed while sending the actual request to call the POST method in target org. Now, how do we get the session id from response? To do that we need to parse the response xml. This is done by getting the body element and getting the root elements (you can go through articles which give insights above parsing xml). Once we have the session id we are ready to call the exposed REST class from target org through http callout.

3.  Call the exposed class method using http callout
This will be similar to step 2 except few changes. End point url in this case is as below
This url specifies that we are calling REST api exposed class  ( and then specifies the class name.
Now the question is how does it which method to call? It will call post method 'createAccountRecord' because we have set setmethod as 'POST'         
to call put method just change POST to PUT         

Next thing that we have set is authorisation -        
request2CreateAccount.setHeader('Authorization', 'OAuth '+SESSION_ID);
This where we need session id and this was the reason we used first http callout to login into salesforce org. We also need to set the body of the request, in this case have set to json. Make sure you are sending the target org method parameter in the body. 

Once you have both the classes saved and remote site setting created in target org just execute the method in other org using developer console.

RestAPIcalloutExample restcall = new RestAPIcalloutExample(); 

New account record would be created in target org, you can see the id of the record using debug log.

Map in apex salesforce

Map is a collection that is most useful while building complex logic in apex class or trigger, Specially while building trigger logic for bulkification. A map is basically a collection of key & value pairs where in each unique key maps to a single value. Keys and values can be any of below data type—
Primitive types like integer or string, collections, sObjects, user-defined types, and built-in Apex types.

To declare a map use keyword map as done in below example
 map<string,integer>countryCodeMap=New map<string,integer>()
above map is declared to store keys of type string and values of type integer.

Similar to lists and set you can directly populate map with key and values at the time of declaration as below,
Map<String, String> countryCodeMap = new Map<String, String>{'india' => 91, 'USA' => 1}; 
In the example above india and USA are the two keys and values 91 and 1 are their respective values.

In order to add key values we can also use map method provided by salesforce. In case of map we can use put method as below,
This adds new key china with a value 76.

Basically map has a keyset which is nothing but a set and values are nothing but a list. Key will always be unique and cannot be duplicated while values can be duplicate.

Let us see some important points on map

1. We can retrieve all the keys from map using keyset() method and it returns set hence the output of keyset() method should be stored in a set as below
Set<string> allcountiersSet = countryCodeMap.keyset()2. We can retrieve all the values from map using values() method and it return list hence the output of values() method should be stored in a list as below 
Set<integer>allCountryCodesList= countryCodeMap.values()

3. A map key can hold a null value and hence we need to take necessary care of putting null checks.

4. As discussed above key is always unique and cannot be duplicate hence if you add a key with a value wherein the key is already present in map then the existing values against the existing key is replaced.for example
This would mean key mexico has value 8 against it as 7 is overwritten by 8.

5. Multiple keys can have same value against it, as values can be duplicate.for example

6. You need to be very careful while having keys of type string, reason - string keys are case sensitive, Ignoring which can be disastrous.

7. Soql query can be stored directly in map of type (id,sobject) which gives sObject record against id of that record. example below
map<id,account> idaccountmap = map<id,account>(select id,name,accountsource from account limit 50) 
This gives account record against its id. This can be very useful  while building logic and also saves no of lines.

8. You can use get() method to get a value against a specific key in the map. for example

Using get method below
would return 91 and countryCodeMap.get('india') would return 7

Set in apex salesforce

Collection Set is similar to List but with few differences. It is important to understand these difference as otherwise it can cause failure in the logic that you have written which may not be easily visible during unit testing.

Set unlike List is a collection of elements which are unordered that means you can’t access a set element at a specific index. You can only iterate over set elements.

Second important point related to set is that it does not store duplicate elements. List on the other hand can store duplicate elements.

Set can store below types in it-
Primitive types like integer,string etc or Collections or SObject or user defined types like wrapper class or even built in apex types.

Example- Set<Integer> intSet = New Set<integer>()
Set<Id> idSet = New Set<Id>()

New elements can be added to the set by using add() method or you can add elements directly at the time of declaration as below,
Set<integer> mySet = new Set<integer>{4, 6, 9};

Sets can be nested, that is you can have set of set and this can go up to total five levels. 
Eg Set<Set<Id>> nestedSet
Simialr to List salesforce provides various system methods to manipulate data in set. Below are some of the commonly used methods for set data manipulation.

    Adds a new element to the set.
    Adds all of the elements in the provided list to the set.
    Adds all of the elements in the specified set to the set.
    deletes all of the elements from the set.
    Makes a duplicate copy of the set.

Collections in apex salesforce - List

Apex gives us three types of collections.
1. List
2. Set
3. Map

List and Set are almost similar with few differences that we will discuss in another article. Map is different from list and set but incorporates both in it. It consists of key and values. In this article lets discuss List and various points on List and how to use it while building our logic in apex.

1. Lists

A list is nothing but a collection of elements which are marked by indexes, it is similar to array that we have learned in other languages. 
List can store any of the below data types-
Primitive types like integers, strings or sObjects even user defined types like wrapper classes and also built in apex types. 

List are ordered collection of elements unlike set which is unordered.
Below are some points that needs to be considered while using lists-
1. The List collection indices begin at 0

2. Lists can be nested with one another and this can go upto total 5 levels.

3. To declare a list keyword 'List' is used for example as below,
    List<String> intlist = new List<String>();

4. there are various methods that salesforce provides to manipulate data in a list collection. As an example add() this is one of the methods that is extensively used. This method allows us to add new elements in the list. As an example below statement adds new integer to the list defined in point 3.

5. A SOQL query results needs to be collected in List. A SOQL query returns collection of sobject that needs to be stored in a list of that type, that is return type of soql is list unless limit 1 is used in which case sobject type can be sued. As an example below
 List<account> accList = [Select id,name from account where createddate =];

6. Lets see few other methods that can be used to manipulate data in list collection.
    You can use Clear() method to clear all the data present in list. for example intlist.clear();
   You can set data at any specific index by using set method. for example below set element at second position as 2

7. List can store duplicate elements in it which is not allowed in case of Sets

8. We can iterate over all the elements in list using advanced for loop wherein we need not check for last index or increase the counter. We can simply iterate over it and everything is taken care of as below.
   for(integer in : intlist){
        system.debug('integer values is'+in);

Next>> Apex Collection - Set 

Using savepoint and rollback in apex salesforce

In this post i am going to demo how to use savepoint and rollback in apex. Before we start with how to use savepoint rollback, let us see why we need to use it in first place and also see what impact we may have to face if rollback is not used.

An important thing to understand while writing apex is how and when an apex dml transaction gets committed to database. An important practice that everyone follows is to write try and catch whenever we have dml transactions happening in our code. In case of try catch important things to note-
1. Code execution transfers to catch from the point where an exception has occurred
2. All the transactions that happened before the transaction that threw exception are actually committed to the database and this could be a problem where you want either all or nothing to happen.

This is applicable only in case of multiple dml transactions in one try block. In this case we can use savepoint &  rollback to make sure nothing is committed to the database in case exception occurs and making sure system is restored as it was at the starting point where savepoint is mentioned.

In case if your code does not use try catch blocks then no matter where exception occurs nothing will be committed to the database. That is, say if you have 3 transactions and the exception is thrown at 3rd dml then all the previous transaction will not be committed to database.

In the example below we will see all the points that we have discussed above. A visualforce page below has a controller that has three dml transactions happening one after another. An account record is inserted then a contact record and finally a lead record is created. In order to demo rollback, i have placed a validation rule on lead that will not allow lead record to get created and hence throw a dml exception and then we can see rollback demo.

So as to use savepoint and rollback we have to first specify the point at which you want the transaction to get rolled back and then use rollback statement to actually roll the operation back. For example.

Savepoint mysavepointt = Database.setSavepoint();
//your code here line 1
// your code here line n
//my code here line x

In this case transaction will be rolled back to savepoint just above line 1, and then again continue from line x just as if line 1 to line n were not executed at all or as if they were not present.

I have created 2 methods in controller, both the methods do the same thing except that one method uses rollback and the other does not use it. Both the methods have try catch blocks in place.

Visualforce Page

<apex:page controller="savepointrollbackcontroller">
 <apex:pageblock tabstyle="opportunity" title="SavePoint and Rollback Demo">
    <apex:commandbutton action="{!insertNewRecordsWithRollBack}" value=" Insert New Records With Rollback ">
    <apex:commandbutton action="{!insertNewRecordsWithoutRollBack}" value=" Insert New Records Without rollback">
    <apex:outputpanel rendered="{!showresults}">
    <apex:pageblocksection title="{!typeofresult}"></apex:pageblocksection>
    No of newly created Accounts -  {!commitedAccRec.size}
    No of newly Newly created Contacts -  {!commitedConRec.size}

    No of newly Newly created Leads  - {!commitedLeadRec.size}&nbsp;</apex:outputpanel></apex:commandbutton></apex:commandbutton></apex:pageblock></apex:form></apex:page>

Controller Class

public class savepointrollbackcontroller {
Public account newAccRec;
Public Contact newConRec;
Public Lead newLeadRec;
Public List<account> commitedAccRec{get;set;}
Public List<contact> commitedConRec{get;set;}
Public List<lead> commitedLeadRec{get;set;}
Public boolean showresults{get;set;}
Public string typeofresult{get;set;}
 Public savepointrollbackcontroller(){
  showresults = false;
  Public void insertNewRecordsWithOutRollBack(){
 showresults = true;
 commitedAccRec = new List<account>();
 commitedConRec = new List<contact>();
 commitedLeadRec = new List<lead>();
  typeofresult = 'Results without savepoint and Rollback';
   newAccRec = new account(name = 'Alpha techno pvt ltd');
   insert newAccRec;
   newConRec = new contact(firstname = 'John',lastname = 'Peter');
   insert newConRec;
   newLeadRec = new Lead(firstname = 'Lawrance',lastname = 'wayne', 
   company = 'Quotient Engineering',
   status='Open - Not Contacted');
   insert newLeadRec;
  catch(exception ex){
   //No rollback used in this method
   //Query account, contact and lead record using the id that gets created through insert dml
   //although id can be seen in debug but since the code is rolled back there wont be any record actually created in org
   // hence queries wont return any records
   commitedAccRec = [select name from account where id =:];
   commitedConRec = [select name from contact where id =:];
   commitedLeadRec = [select name from lead where id =:];

 Public void insertNewRecordsWithRollBack(){

 showresults = true;
 commitedAccRec = new List<account>();
 commitedConRec = new List<contact>();
 commitedLeadRec = new List<lead>();
 typeofresult = 'Results with savepoint and Rollback';
 //define a save point upto which the code will be rolled back
 Savepoint sp = Database.setSavepoint();
   newAccRec = new account(name = 'Alpha techno pvt ltd');
   insert newAccRec;
   newConRec = new contact(firstname = 'John',lastname = 'Peter');
   insert newConRec;
   newLeadRec = new Lead(firstname = 'Lawrance',lastname = 'wayne', 
   company = 'Quotient Engineering',
   status='Open - Not Contacted');
   insert newLeadRec;
  catch(exception ex){
   //rollback all the transactions that took placed after the savepoint sp
   //Query account, contact and lead record using the id that gets created through insert dml
   //although id can be seen in debug but since the code is rolled back there wont be any record actually created in org
   // hence queries wont return any records
   commitedAccRec = [select name from account where id =:];
   commitedConRec = [select name from contact where id =:];
   commitedLeadRec = [select name from lead where id =:];

In case of first method which does not use savepoint & rollback, you can see that first two dml transactions succeed thus inserting a new account and contact record but the third dml fails with a dml exception(as i had set a validation rule to stop the lead from getting created). As a result you can see that no. of newly created account and contact equals one where as lead count is zero. This happens dispite there was exception in apex transaction, that means partiall operations were committed to the database.

In the second method that uses rollback, you can see that none of the dmls are commited to the database and hence all the counts are zeroed and thus nothing is committed to the database as there was an exception thrown during lead creation and all the dml transactions are rolled back to the savepoint.

Pre populate field values while creating new record in salesforce through UI

Sometimes while creating new records we need to have feature that allows us to have default values pre-populated in some fields. Salesforce does gives us an option to have default values pre-populated but it is not available for all the data type, like you cannot have default value for lookup field.

We can play a trick to pre-populate the values for whichever data type we want while creating a new record. For this we need to tweak the url that is getting used for creating the new record (URL that gets displayed when you click on new record and the edit page opens ). We need to make sure the modified url gets called whenever the new button is clicked. The the final url will be in addition to the original url that we get. We need to add id of the field that should be pre populated along with the value that we need, this needs to be done for all the fields you need pre-populated. Each id+value should be seperated by '&' character. For example, in the below url two fields are getting prepopulated with values 'e technologies' and 'cold'.


How do we get the id of the field?

You can get the id of the field by navigating to the field through set up or through source code/html of the edit page(Just open source code through browser and search for the label of the field)
Also as of now you cannot get the field id through apex hence you cannot make such a functionality dynamic and it should be pre-saved in your code,url.

Below is an example that pre-populates some fields while a new account record is created. Since you cannot write java script for a standard button visualforce page is used in-order to modify the original url. Just override the account new button with this visuflriec page.


Visualforce Page
Apex Class



For all the data type one can simple specify the field id followed by the value but for pre-populating lookup fields there are 2 ids that should be used. One for record id and one for name of the record. Id to be used for record id will have '_lkid' in the end and for name just use id without '_lkid'

acc3_lkid=0019000000RP2f4'+'&acc3=University of arizona

here acc3_lkid with record id is for lookup id and acc3 is for populating name. The name that you specify could be anything and it does not make a difference if you give wrong name. Name of the record could be anything and need not match the real name of the record but has to be always specified without which look field will not be populated.

Salesforce Interview Questions Part 18

Part 1 (1-15) - Part 2 (16 -30) - Part 3 (31 -45) - Part 4 (46 -55) - Part 5 (56 -66) - Part 6 (67 - 78) - Part 7 (79 - 90) - Part 8 (91 - 100) - Part 9 (101- 111) - Part 10 (112 - 120) -          Part 11 (121 - 130) - Part 12 (131 - 137) - Part 13(138 - 145) - Part 14 (146 - 152) -          Part 15 ( 153 - 159) - Part 16 ( 160 - 168)    Part 17 (169 - 177   Part 18(178 - 187)  Part 19 (188 - 201)

179. Can you use a single permission Set for multiple users?
Ans - Yes, this can be done. Permission set once created can be added to multiple users in the related list of user detail page or at once for multiple users through Set up.

180. Can analytical snapshot continue working properly if the running user is inactivated?
Ans - No, the snapshot will fail if the running is inactive.

181.Can you import User data through import wizard?
Ans - No this cannot be done.

182. Can you import Custom objects data through import wizard?
Ans - Yes, custom object data can be imported by import wizard.

183. If you have a custom object acting as detail to a master-detail relationship (standard object), what will be its organization-wide default set to?
Ans - The OWD for detail object will always be 'Controlled by Parent' and this cannot edited.

184. In the salesforce MVC architecture where will you categorize standard or custom objects?
Ans - Standard or custom objects fall under model layer of salesforce MVC.

185. View or Edit permission on document, report, or dashboard depends on whether the user has access to folder in which they are stored, TRUE or FALSE?
Ans - Yes this is TRUE.

186. What are the different types of groups that you can create in salesforce?
Ans - Two types of groups can be created in salesforce 1. Public Group and 2. Personal Group

187. What is the use of permission sets?
Ans- Permission sets can be used to extend a user's functional access without changing the assigned profile.

Part 1 (1-15) - Part 2 (16 -30) - Part 3 (31 -45) - Part 4 (46 -55) - Part 5 (56 -66) - Part 6 (67 - 78) - Part 7 (79 - 90) - Part 8 (91 - 100) - Part 9 (101- 111) - Part 10 (112 - 120) -          Part 11 (121 - 130) - Part 12 (131 - 137) - Part 13(138 - 145) - Part 14 (146 - 152) -          Part 15 ( 153 - 159) - Part 16 ( 160 - 168)    Part 17 (169 - 177   Part 18(178 - 187) Part 19 (188 - 201)

salesforce interview questions and answers 17

Part 1 (1-15) - Part 2 (16 -30) - Part 3 (31 -45) - Part 4 (46 -55) - Part 5 (56 -66) - Part 6 (67 - 78) - Part 7 (79 - 90) - Part 8 (91 - 100) - Part 9 (101- 111) - Part 10 (112 - 120) - Part 11 (121 - 130) - Part 12 (131 - 137) - Part 13(138 - 145) - Part 14 (146 - 152) - Part 15 ( 153 - 159) - Part 16 ( 160 - 168)    Part 17( 169 - 177)  Part 18(178 - 187) Part 19 (188 - 201)

169. Max how many records can be retrieved by a SOQL query?
Ans - As of today SOQL query can retrieve you upto 50,000 records

170. Max How many batch apex jobs can be concurrently in active or queued up status?
Ans- There can only be 5 batch apex concurrently in active state/Queued as of today.

171.What is the Default timeout of callouts (HTTP requests) in a transaction?
Ans - Default timeout for callouts is 10 seconds

172. When a sandbox is refreshed does the organisation ID of that sandbox remain same?
Ans - No, the organisation id changes every time the sandbox is refreshed.

173.Given a salesforce record id how can you identify the object from the 18 digit id?
Ans - First 3 characters signify the object and all the records of that object will always start with those 3 characters. For ex. account records start with 001

174.  In analytical snapshots, can the target object have trigger?
Ans - If the target object has trigger on it, the analytical snapshot will fail.

175. What are the different custom tabs that can be created in salesforce?
Ans - Three types of tabs can be created 1. Custom object tab, 2. Visualforce Tab and 3. Web Tab

176. When writing a sharing rule, whome can you can you share the records?
Ans - Records can be shared to Roles,Roles and Subordinates and Public groups.

177. Can you have assignment rules on custom objects?
Ans - No, custom objects do not have assignment rules

Part 1 (1-15) - Part 2 (16 -30) - Part 3 (31 -45) - Part 4 (46 -55) - Part 5 (56 -66) - Part 6 (67 - 78) - Part 7 (79 - 90) - Part 8 (91 - 100) - Part 9 (101- 111) - Part 10 (112 - 120) - Part 11 (121 - 130) - Part 12 (131 - 137) - Part 13(138 - 145) - Part 14 (146 - 152) - Part 15 ( 153 - 159) - Part 16 ( 160 - 168)    Part 17( 169 - 177)  Part 18(178 - 187) Part 19 (188 - 201)