Rest API First Example in Salesforce- CoderinMe

In the Previous Post, we have learned about Webservice and Callout using REST and SOAP API for Salesforce . Continue with that we are giving you one example using REST API.

REST API First Example

First of all, we will learn how to get an address from Google API if we will pass latitude and longitude using APEX callout.

First of all please check the code below you can execute it into your org anonymous window of developer console.

Http ht = new Http();
HttpRequest  req = new HttpRequest ();

String key ='AIzaSyDCJfSJhXuKJlffbFfB57yOO_iQK4kAmio';
String url ='https://maps.googleapis.com/maps/api/geocode/json?key='+key+'&latlng=28.5810215,77.3152004&sensor=true';
req.setEndpoint(url);

req.setMethod('GRT');
//req.setBody('body');
HttpResponse res = ht.send(req);

if(res.getStatusCode()==200){
            string str= res.getBody().split('"formatted_address" : "')[1].split('",')[0];
            system.debug(str);
}

Before that please add this URL to your remote site setting.

https://maps.googleapis.com/

If in execution it says API key or exceeds the limit of api, then please get api key and paste new key in the code. You can get the key from here GET Google Map API Key.

Open the debug log you can see this in the log.

Vyapar Marg, D Block, Sector 2, Noida, Uttar Pradesh 201301, India

REST API Salesforce Google Map - coderinme

Explain The code

3 Class call, Http HttpRequest, HttpResponse I have used and have made instances of them. then we have setEndpoint URL where we want to communicate or share/access data. Then I set the method GET/POST/PUT/ DELETE, then I have requested it via send method. Then I fetch the status code of response and body as you can see in the above code.

The response was so much big like this

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Vyapar Marg",
               "short_name" : "Vyapar Marg",
               "types" : [ "route" ]
            },
            {
               "long_name" : "D Block",
               "short_name" : "D Block",
               "types" : [ "political", "sublocality", "sublocality_level_2" ]
            },
            {
               "long_name" : "Sector 2",
               "short_name" : "Sector 2",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Noida",
               "short_name" : "Noida",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Gautam Buddh Nagar",
               "short_name" : "Gautam Buddh Nagar",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Uttar Pradesh",
               "short_name" : "UP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "201301",
               "short_name" : "201301",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Vyapar Marg, D Block, Sector 2, Noida, Uttar Pradesh 201301, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.5809963,
                  "lng" : 77.31529739999999
               },
               "southwest" : {
                  "lat" : 28.5809739,
                  "lng" : 77.3152017
               }
            },
            "location" : {
               "lat" : 28.5809851,
               "lng" : 77.31524949999999
            },
            "location_type" : "GEOMETRIC_CENTER",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.58233408029151,
                  "lng" : 77.31659853029151
               },
               "southwest" : {
                  "lat" : 28.5796361197085,
                  "lng" : 77.31390056970849
               }
            }
         },
         "place_id" : "ChIJcyb6_1vkDDkRiJpRGRM0HwQ",
         "types" : [ "route" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "D Block",
               "short_name" : "D Block",
               "types" : [ "political", "sublocality", "sublocality_level_2" ]
            },
            {
               "long_name" : "Sector 2",
               "short_name" : "Sector 2",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Noida",
               "short_name" : "Noida",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Gautam Buddh Nagar",
               "short_name" : "Gautam Buddh Nagar",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Uttar Pradesh",
               "short_name" : "UP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "201301",
               "short_name" : "201301",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "D Block, Sector 2, Noida, Uttar Pradesh 201301, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.5854751,
                  "lng" : 77.31941689999999
               },
               "southwest" : {
                  "lat" : 28.580813,
                  "lng" : 77.31379799999999
               }
            },
            "location" : {
               "lat" : 28.5829964,
               "lng" : 77.3170066
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.5854751,
                  "lng" : 77.31941689999999
               },
               "southwest" : {
                  "lat" : 28.580813,
                  "lng" : 77.31379799999999
               }
            }
         },
         "place_id" : "ChIJpei4F1nkDDkRfP1L5kfNU6w",
         "types" : [ "political", "sublocality", "sublocality_level_2" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "Sector 2",
               "short_name" : "Sector 2",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Noida",
               "short_name" : "Noida",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Gautam Buddh Nagar",
               "short_name" : "Gautam Buddh Nagar",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Uttar Pradesh",
               "short_name" : "UP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "201301",
               "short_name" : "201301",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Sector 2, Noida, Uttar Pradesh 201301, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.589036,
                  "lng" : 77.31941689999999
               },
               "southwest" : {
                  "lat" : 28.580813,
                  "lng" : 77.31082889999999
               }
            },
            "location" : {
               "lat" : 28.5846875,
               "lng" : 77.31592959999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.589036,
                  "lng" : 77.31941689999999
               },
               "southwest" : {
                  "lat" : 28.580813,
                  "lng" : 77.31082889999999
               }
            }
         },
         "place_id" : "ChIJpa-wzFjkDDkRKR6DHMI9am8",
         "types" : [ "political", "sublocality", "sublocality_level_1" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "Noida",
               "short_name" : "Noida",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Gautam Buddh Nagar",
               "short_name" : "Gautam Buddh Nagar",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Uttar Pradesh",
               "short_name" : "UP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Noida, Uttar Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.6363011,
                  "lng" : 77.50256329999999
               },
               "southwest" : {
                  "lat" : 28.397206,
                  "lng" : 77.2936967
               }
            },
            "location" : {
               "lat" : 28.5355161,
               "lng" : 77.3910265
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.6363011,
                  "lng" : 77.50256329999999
               },
               "southwest" : {
                  "lat" : 28.397206,
                  "lng" : 77.2936967
               }
            }
         },
         "place_id" : "ChIJezVzMaTlDDkRP8B8yDDO_zc",
         "types" : [ "locality", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "201301",
               "short_name" : "201301",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "Uttar Pradesh",
               "short_name" : "UP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Uttar Pradesh 201301, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.6332055,
                  "lng" : 77.39301139999999
               },
               "southwest" : {
                  "lat" : 28.5453752,
                  "lng" : 77.296797
               }
            },
            "location" : {
               "lat" : 28.5821195,
               "lng" : 77.3266991
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.6332055,
                  "lng" : 77.39301139999999
               },
               "southwest" : {
                  "lat" : 28.5453752,
                  "lng" : 77.296797
               }
            }
         },
         "place_id" : "ChIJKQa0eU7kDDkRuol-quF6nFs",
         "types" : [ "postal_code" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "Gautam Buddh Nagar",
               "short_name" : "Gautam Buddh Nagar",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Uttar Pradesh",
               "short_name" : "UP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Gautam Buddh Nagar, Uttar Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 28.65431,
                  "lng" : 77.73837
               },
               "southwest" : {
                  "lat" : 28.08489,
                  "lng" : 77.2992701
               }
            },
            "location" : {
               "lat" : 28.338333,
               "lng" : 77.6077865
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 28.65431,
                  "lng" : 77.73837
               },
               "southwest" : {
                  "lat" : 28.08489,
                  "lng" : 77.2992701
               }
            }
         },
         "place_id" : "ChIJZc0VBFPkDDkRaCE3BhJhWPQ",
         "types" : [ "administrative_area_level_2", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "Uttar Pradesh",
               "short_name" : "UP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Uttar Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 30.411635,
                  "lng" : 84.6743269
               },
               "southwest" : {
                  "lat" : 23.870839,
                  "lng" : 77.0924369
               }
            },
            "location" : {
               "lat" : 26.8467088,
               "lng" : 80.9461592
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 30.411635,
                  "lng" : 84.6743269
               },
               "southwest" : {
                  "lat" : 23.870839,
                  "lng" : 77.0924369
               }
            }
         },
         "place_id" : "ChIJ0wlKe59OmTkRnSQXNm1HpfY",
         "types" : [ "administrative_area_level_1", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 35.5087008,
                  "lng" : 97.39535869999999
               },
               "southwest" : {
                  "lat" : 6.4626999,
                  "lng" : 68.1097
               }
            },
            "location" : {
               "lat" : 20.593684,
               "lng" : 78.96288
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 35.5087008,
                  "lng" : 97.39535869999999
               },
               "southwest" : {
                  "lat" : 6.4626999,
                  "lng" : 68.1097
               }
            }
         },
         "place_id" : "ChIJkbeSa_BfYzARphNChaFPjNc",
         "types" : [ "country", "political" ]
      }
   ],
   "status" : "OK"
}

So I decide to split it and get only the address using split method. In the first Split, I got 2 strings because split(‘”formatted_address” : “‘) as you can find words BOLD in above response then i split it again for the address.

Contact Location and address

Now what I want to add, suppose we have 3 fields in contact Longitude, Latitude & Address , after the insertion or updation of contact if we will input latitude and longitude a trigger will hit the Google API and update the address of the contact.

REST API Salesforce Contact- coderinme

We create a trigger and API class used using future method.

trigger updateMap on Contact (after insert, after update) {
    
    for(Contact c: Trigger.new){
        if(trigger.isUpdate){
   // for update if location change we will call apiMap Class
            if(c.Latitude__c != Trigger.oldMap.get(c.id).Latitude__c || c.Longitude__c != Trigger.oldMap.get(c.id).Longitude__c)
       		apiMap.chckMap(String.valueOf(c.Latitude__c), string.valueOf(c.Longitude__c), c.id);
        }
        if(trigger.isInsert)
            apiMap.chckMap(String.valueOf(c.Latitude__c), string.valueOf(c.Longitude__c), c.id);
        // we are passing three args longitude, latitude and contact Id.
    }

}
public class apiMap {

/* if we are using api call we will use future callout then trigger will support API Callout * /
 
    @future (callout=true)
    public static void chckMap(string lat, string lon, string conId){
// we will use these lat and lon on api url
        Http h = new Http();
        //28.5810215,77.3152004
        HttpRequest  req = new HttpRequest ();
        String url ='https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyDCJfSJhXuKJlffbFfB57yOO_iQK4kAmio&latlng='+lat+','+lon+'&sensor=true';
        req.setEndpoint(url);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
       
        if(res.getStatusCode()==200){
            string str= res.getBody().split('"formatted_address" : "')[1].split('",')[0];
            system.debug(str);
            
// update contact with address from API response
            contact c= new Contact();
            c.id=conId;
            c.address__c=str;
            update c;
         }

// making a log for every API Hit for best practice.
            
            httpRequest__c log1= new httpRequest__c();
            log1.Request__c='MapAPI';
            log1.response__c=str;
            log1.status__c=String.valueOf(res.getStatusCode());
            insert log1;

        
    }
    
}

you can see our video tutorial for the same.

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

 

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.