Another Salesforce blog!!!

Salesforce, Apex

Invoking HTTP Callouts – GET


I will be using this endpoint link as a test purpose its very simple nothing fancy but the point is to prove how to get connected to this end-point and get access to the data.

Step one: Add to the Remote site setting in the Salesforce as shown below.

Step two: Create Custom Labels and add the endpoint

Step three: To get the JSON data create a wrapper class, In most of the integrations, you typically use HTTP Callouts to the end points defined by various services, and the most common response format returned by these is JSON.

Now, parsing this JSON would be very time consuming if not done in the right way. One way of doing this would be manually parsing the complete JSON using the JSONParser method. But the easiest way of Parsing JSON would be to de-serialize it into an Object.

For this, first we need to create a class or an Inner class, which would contain all the variables that are to be stored from the JSON.

The JSON2Apex is a very handy tool for this. Goto

http://json2apex.herokuapp.com/

and paste the JSON String in the space provided, and click on create Apex. Read more about here

So for the above endpoints I created my class using the json2apex.herokuapp.com website the following.

My Wrapper class:

public class JSON2Apex {
    
    public class Contact {
        public String id { get; private set; }
        public String name{ get; private set; }
        public String email{ get; private set; }
        public String address{ get; private set; }
        public String gender{ get; private set; }
        public Phone phone { get; private set; }
        public Boolean isSelected {get;set;}
    }
    
    public List<Contact> contacts; 
     public class Phone {
        public String mobile { get; private set; }
        public String home { get; private set; }
        public String office { get; private set; }
    }  
    public static JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
}

After you created the Wrapper class you let’s create the controller class:

public class HttpCalloutsController {
  
    //http://api.androidhive.info/contacts/
    public List<JSON2Apex.Contact> jsonRecords {get;set;}    
    public HttpCalloutsController() {
        
        //HttpRequest class:
        HttpRequest hr = new HttpRequest();
        hr.setEndpoint(Label.EndPointContactURL);
        hr.setMethod('GET');
        
        //HttpResponse class:
        Http h = new Http();
        HttpResponse res = h.send(hr);
        String jsonString = res.getBody(); 
        
        JSON2Apex myClass = JSON2Apex.parse(jsonString);         
        jsonRecords = new List<JSON2Apex.Contact>(myClass.Contacts);
        system.debug('///' + jsonRecords[0].phone.mobile);
    } 
    
    public PageReference doSave() {
        List<JSON2Apex.Contact> tobeSaved = new List<JSON2Apex.Contact>();
        for(JSON2Apex.Contact d : jsonRecords) {
            if(d.isSelected) {
                system.debug('///selected contact is:  ' + d);
                tobeSaved.add(d);
            }
        }
        
        Web_Service_Log__c log = new Web_Service_Log__c();
        if(tobeSaved.size() > 0) {
            try {
                //do insert here to the contact object
                log.Service_Name__c = 'HttpCalloutsController';
                log.Time_Stap__c = System.now();
                //log.Error_Message__c = e.getMessage();
                log.Status__c = 'Success';
            }
            catch (Exception e) {                
                log.Service_Name__c = 'HttpCalloutsController';
                log.Time_Stap__c = System.now();
                log.Error_Message__c = e.getMessage();
                log.Status__c = 'Failure';
            }
            insert log;
        } 
        return (new PageReference('/apex/HttpCalloutsPage').setRedirect(true);
    }
}

The above code is very self explanatory so I’m not going to go line by line and now let’s create Visualforce page:

<apex:page controller="HttpCalloutsController" tabStyle="Contact" >
    <apex:form >
    	<apex:pageBlock title="REST Contacts"> 
           
        	<apex:pageBlockTable value="{!jsonRecords}" var="c">
                <apex:column headerValue="Select">
                    <apex:inputCheckbox value="{!c.isSelected}"/>
                </apex:column>    
            	<apex:column headerValue="Contact Id" value="{!c.id}"/>
                <apex:column headerValue="Contact Name" value="{!c.name}"/>
                <apex:column headerValue="Contact Email" value="{!c.email}"/>
                <apex:column headerValue="Contact Address" value="{!c.address}"/>
                <apex:column headerValue="Contact Gender" value="{!c.gender}"/>
              
                <apex:pageBlockTable value="{!c.phone}" var="p">
                    
                	<!--apex:column headerValue="Contact Phone" value="{!p.mobile}"/-->
                </apex:pageBlockTable>
            </apex:pageBlockTable>
            <apex:pageBlockButtons>
            	<apex:commandButton value="Save" action="{!doSave}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    
    </apex:form>
</apex:page>

Its always a good practice to create a Web Service Log so you know what is going when you make post a request etc..
here is the screen shot of my Web Service Log.

Leave a Reply

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

*