function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ravi Dutt SharmaRavi Dutt Sharma 

Webservice callout in lightning component

I am trying to build a lightning component which will display the weather condition of a particular area. For getting the weather details, I am making a webservice callout. In Weather.cmp component, I have defined a handler for the init event. So as soon as the page is loaded, the init handler gets executed, and calls a method which is present in my Apex controller named WeatherCtrl which makes a webservice callout and returns the response. I have debug statments in my Apex controller and I see that the response is coming in the Apex controller. But when I return the response from my JS helper - WeatherHelper.js, the response.getReturnValue() seems to be null. 
Any ideas what I may be doing wrong here. Here is the code:

Weather.cmp
 
<aura:component controller="WeatherCtrl">
	
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <aura:attribute name="response" type="WeatherResponse"/>
    
    Longitude : <ui:outputText value="{!v.response.coord.lon}"/>
    
</aura:component>

WeatherController.js
 
({
	doInit : function(component, event, helper) {
		helper.getResponse(component);
	}
})

WeatherHelper.js
 
({
	getResponse : function(component) {
		var action = component.get("c.getCalloutResponseContents");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=12.971599&lon=77.594563&appid=9b2719bd93477d05ad2575ccb81cb666'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                console.log(response.getReturnValue());
                component.set("v.response", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
	}
})

WeatherCtrl.apxc
 
public class WeatherCtrl {
    
    // Pass in the endpoint to be used using the string url
    @AuraEnabled
    public static WeatherResponse getCalloutResponseContents(String url) {
        
        // Instantiate a new http object
        Http h = new Http();
        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug('*****response: '+WeatherResponse.parse(res.getBody()));
        return WeatherResponse.parse(res.getBody());
    }
    
}

WeatherResponse.apxc
 
//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class WeatherResponse{
    public static void consumeObject(JSONParser parser) {
        Integer depth = 0;
        do {
            JSONToken curr = parser.getCurrentToken();
            if (curr == JSONToken.START_OBJECT || 
                curr == JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == JSONToken.END_OBJECT ||
                curr == JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }

    public class Weather {
        public Integer id {get;set;} 
        public String main {get;set;} 
        public String description {get;set;} 
        public String icon {get;set;} 

        public Weather(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'id') {
                            id = parser.getIntegerValue();
                        } else if (text == 'main') {
                            main = parser.getText();
                        } else if (text == 'description') {
                            description = parser.getText();
                        } else if (text == 'icon') {
                            icon = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Weather consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Coord {
        public Integer lon {get;set;} 
        public Integer lat {get;set;} 

        public Coord(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'lon') {
                            lon = parser.getIntegerValue();
                        } else if (text == 'lat') {
                            lat = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Coord consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Wind {
        public Double speed {get;set;} 
        public Double deg {get;set;} 

        public Wind(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'speed') {
                            speed = parser.getDoubleValue();
                        } else if (text == 'deg') {
                            deg = parser.getDoubleValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Wind consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Rain {
        public Integer h3 {get;set;} 

        public Rain(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'h3') {
                            h3 = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Rain consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Clouds {
        public Integer all {get;set;} 

        public Clouds(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'all') {
                            all = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Clouds consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public Coord coord {get;set;} 
    public Sys sys {get;set;} 
    public List<Weather> weather {get;set;} 
    public Main main {get;set;} 
    public Wind wind {get;set;} 
    public Rain rain {get;set;} 
    public Clouds clouds {get;set;} 
    public Integer dt {get;set;} 
    public Integer id {get;set;} 
    public String name {get;set;} 
    public Integer cod {get;set;} 

    public WeatherResponse(JSONParser parser) {
        while (parser.nextToken() != JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != JSONToken.VALUE_NULL) {
                    if (text == 'coord') {
                        coord = new Coord(parser);
                    } else if (text == 'sys') {
                        sys = new Sys(parser);
                    } else if (text == 'weather') {
                        weather = new List<Weather>();
                        while (parser.nextToken() != JSONToken.END_ARRAY) {
                            weather.add(new Weather(parser));
                        }
                    } else if (text == 'main') {
                        main = new Main(parser);
                    } else if (text == 'wind') {
                        wind = new Wind(parser);
                    } else if (text == 'rain') {
                        rain = new Rain(parser);
                    } else if (text == 'clouds') {
                        clouds = new Clouds(parser);
                    } else if (text == 'dt') {
                        dt = parser.getIntegerValue();
                    } else if (text == 'id') {
                        id = parser.getIntegerValue();
                    } else if (text == 'name') {
                        name = parser.getText();
                    } else if (text == 'cod') {
                        cod = parser.getIntegerValue();
                    } else {
                        System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
    
    public class Sys {
        public String country {get;set;} 
        public Integer sunrise {get;set;} 
        public Integer sunset {get;set;} 

        public Sys(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'country') {
                            country = parser.getText();
                        } else if (text == 'sunrise') {
                            sunrise = parser.getIntegerValue();
                        } else if (text == 'sunset') {
                            sunset = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Sys consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Main {
        public Double temp {get;set;} 
        public Integer humidity {get;set;} 
        public Integer pressure {get;set;} 
        public Double temp_min {get;set;} 
        public Double temp_max {get;set;} 

        public Main(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'temp') {
                            temp = parser.getDoubleValue();
                        } else if (text == 'humidity') {
                            humidity = parser.getIntegerValue();
                        } else if (text == 'pressure') {
                            pressure = parser.getIntegerValue();
                        } else if (text == 'temp_min') {
                            temp_min = parser.getDoubleValue();
                        } else if (text == 'temp_max') {
                            temp_max = parser.getDoubleValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Main consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    
    public static WeatherResponse parse(String json) {
        return new WeatherResponse(System.JSON.createParser(json));
    }
}


 
Best Answer chosen by Ravi Dutt Sharma
sfdcMonkey.comsfdcMonkey.com
hi Ravi Dutt Sharma
use below class and helper code
WeatherCtr
public class WeatherCtrl {
    
    // Pass in the endpoint to be used using the string url
    @AuraEnabled
    public static String getCalloutResponseContents(String url) {
        
        // Instantiate a new http object
        Http h = new Http();
        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        WeatherResponse obj = WeatherResponse.parse(res.getBody());
        String s = json.serialize(obj);
        System.debug('*****response: ' + WeatherResponse.parse(res.getBody()));
        return s;
    }
    
}
helper.js
({
	getResponse : function(component) {
		var action = component.get("c.getCalloutResponseContents");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=26.9124&lon=75.7873&appid=9b2719bd93477d05ad2575ccb81cb666'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            alert(state);
            if (component.isValid() && state === "SUCCESS") {
                console.log('res---->' + response.getReturnValue());
                var x = JSON.parse(response.getReturnValue()) 
                component.set("v.response", x);
            }
        });
        $A.enqueueAction(action);
	}
})
and your output comes :)
let me inform if it helps you and mark it best answer so it make proper solutions for others
thanks
sfdcmonkey.com


 

All Answers

sfdcMonkey.comsfdcMonkey.com
hi Ravi Dutt Sharma
use below class and helper code
WeatherCtr
public class WeatherCtrl {
    
    // Pass in the endpoint to be used using the string url
    @AuraEnabled
    public static String getCalloutResponseContents(String url) {
        
        // Instantiate a new http object
        Http h = new Http();
        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        WeatherResponse obj = WeatherResponse.parse(res.getBody());
        String s = json.serialize(obj);
        System.debug('*****response: ' + WeatherResponse.parse(res.getBody()));
        return s;
    }
    
}
helper.js
({
	getResponse : function(component) {
		var action = component.get("c.getCalloutResponseContents");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=26.9124&lon=75.7873&appid=9b2719bd93477d05ad2575ccb81cb666'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            alert(state);
            if (component.isValid() && state === "SUCCESS") {
                console.log('res---->' + response.getReturnValue());
                var x = JSON.parse(response.getReturnValue()) 
                component.set("v.response", x);
            }
        });
        $A.enqueueAction(action);
	}
})
and your output comes :)
let me inform if it helps you and mark it best answer so it make proper solutions for others
thanks
sfdcmonkey.com


 
This was selected as the best answer
Ravi Dutt SharmaRavi Dutt Sharma
Hi Piyush,

Thanks for the reply. After making the changes suggested by you, I am getting below error:

This page has an error. You might just need to refresh it. Error during init [Cannot read property 'apply' of undefined]

Not sure where it is breaking now. Here are the updated JS helper and Apex controller:

WeatherHelper.js
 
({
	getResponse : function(component) {
		var action = component.get("c.getCalloutResponseContents");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=12.971599&lon=77.594563&appid=9b2719bd93477d05ad2575ccb81cb666'
        });
        console.log('Setting callback');
        action.setCallback(this, function(response){
            var state = response.getState();
            alert(state);
            if (component.isValid() && state === "SUCCESS") {
                console.log(response.getReturnValue());
                component.set("v.response", JSON.parse(response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
	}
})

WeatherCtrl.apxc
 
public class WeatherCtrl {
    
    // Pass in the endpoint to be used using the string url
    @AuraEnabled
    public static String getCalloutResponseContents(String url) {
        
        // Instantiate a new http object
        Http h = new Http();
        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug('*****response: '+WeatherResponse.parse(res.getBody()));
        return JSON.serialize(WeatherResponse.parse(res.getBody()));
    }
    
}

 
sfdcMonkey.comsfdcMonkey.com
hi you miss i ')' in line number 17 on js controller
use below line
component.set("v.response", JSON.parse(response.getReturnValue()));
thanks
let me inform if it helps you
 
Ravi Dutt SharmaRavi Dutt Sharma
Awesome, that was really quick. Thanks for your help. Btw, how did you find this error? Do you use some editor for writing JS code which tells these errors?
sfdcMonkey.comsfdcMonkey.com
haha no buddy i just look and find it :)
and you can follow my blog and like page (https://www.facebook.com/SFDC-Monkeycom-1312920085424955/)for update new post related to lightning and salesforce :)