Callouts via Rest API in Salesforce

This is Part-2 of the Integration tutorial series where I’ll be sharing with you folks how we can do callout, i.e, utilise/consume an external API. By callout , I mean we are going to integrate our Salesforce org with an external system and we will be utilising some services which are not present by default in our Salesforce org but can be received by some external site/app having them.

For example: We do not have a weather information app/feature in salesforce but other external websites provide such API to utilise them like https://api.weatherapi.com/ .

Each API creator provides the complete documentation(check here) about how to utilise their API, what are the request parameters we need and what will their response looks like. To get an idea, sign up on the site to get and API key which this particular API needs for authenticating you in their systems and then just try this link to see what parameter this API needs in our request and how will its JSON response look.

Now, all which I told above is for verifying if you are correctly hitting this API via the UI. You can also make use of an API tool like Curl or Postman if you know how to use them. IF NOT, try the UI test as of now on their API Explorer page and I will later on create a separate blog on HOW TO USE POSTMAN (coming soon) for Integrations.

Before moving on further, if you don’t know the basic of Integration in Salesforce, please read my Part-1 of the blog first so that it will be easier for you to get how we are doing this via APEX now. Go to Blog.

PRE-REQUISITE

Add the external site’s URL to the Remote site settings from the Setup in Salesforce as Salesforce requires us to do this due to platform security.

Remote Site Settings

TIME TO CODE!!!

Apex Class for Callout:

public class getCurrentWeatherByCityClass {
    @AuraEnabled
    public static Decimal getCurrentWeather(string cityName){
        Decimal currentTemp = 0.0;
        //Initialize the HTTP Class
        Http h = New Http();
        
        string endpoint = 'https://api.weatherapi.com/v1/current.json?key='+ System.Label.WeatherAPIKey +'&q=' + cityName;
        
        //Create a Request
        HttpRequest req = New HttpRequest();
        req.setEndpoint(endpoint);
        req.setMethod('GET');
        req.setHeader('Content-Type','application/JSON');
        
        //Send the request and Get the response
        HttpResponse res = h.send(req);
        
        system.debug(res.getStatusCode());
        
        if(res.getStatusCode() == 200){
            //Deserializes the specified JSON string into collections of primitive data types
            Map<string,Object> returnedJSONBody = (Map<string,Object>)Json.deserializeUntyped(res.getBody());
            system.debug(returnedJSONBody);
            
            Map<string,Object> currentMap = (Map<string,Object>)returnedJSONBody.get('current');
            system.debug(currentMap);
            
            currentTemp = (Decimal)currentMap.get('temp_c');
            system.debug(currentTemp);
        }
        
        return currentTemp;
    } 
   
}

Note: I have stored my API key in a custom label named: WeatherAPIKey

How To Test?

Go to your Anonymous Window and execute:

Decimal currentTemperature = getCurrentWeatherByCityClass.getCurrentWeather('Delhi');
System.debug(currentTemperature);

And that’s it..!! Hurray!! We have fetched the current temperature of Delhi in a Jiffy..!! 😉 🙂
That’s how simple callouts are…If you want to view complete code with a lightning aura component, checkout my github repository here : My Github Callout Repo.



Comments

Leave a Reply

Discover more from Aditya Sharma | Salesforce & AI Engineer

Subscribe now to keep reading and get access to the full archive.

Continue reading