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
sheila srivatsavsheila srivatsav 

callout in lightning

I am tring to get my basics clear while making an api call from lightning application.

But when I debug the statement  var action=resposne.getState(), the state is ERROR
 
public class httpCalloutController {

    @AuraEnabled
    public static void getCalloutResponseContents()
    {
        Http h = new Http();
      
        HttpRequest req = new HttpRequest();
		req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
		req.setMethod('GET');      
        
        // Send the request, and return a response
		HttpResponse res = h.send(req);
		System.debug('response:--> ' + res.getBody());
        
        
        string jsonstring=(string)JSON.deserializeUntyped(res.getBody());
        system.debug('jsonstring-->' + jsonstring);
     }
}

CalloutComponent.cmp

<aura:component implements="flexipage:availableForAllPageTypes" 
                access="global"
                controller="httpCalloutController">
    
    <aura:attribute name="response" type="string"/>
    
	<aura:attribute name="jsonoutput" type="String[]"/>
    
    <lightning:button label="Make Callout" 
                      title="Make Callout"
                      onclick="{!c.MakeCallOut}"/>

    {!jsonoutput}
    
</aura:component>

CalloutComponentController.js

({
	MakeCallOut : function(component, event, helper) {
		
        debugger;
        var action=component.get('c.getCalloutResponseContents');
        
      // action.setParams({
        //    "URL":'https://th-apex-http-callout.herokuapp.com/animals'
        //});
        
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            
          console.log('state ='+state);
            if (component.isValid() && state === "SUCCESS") {
               component.set("v.response", response.getReturnValue());
                console.log('v.response='+v.response);
             }
        });
 
        $A.enqueueAction(action);
    },
})

thanks
sheila​​​​​​​
Best Answer chosen by sheila srivatsav
Raj VakatiRaj Vakati
Use this code
 
public class httpCalloutController {
    
    @AuraEnabled
    public static String getCalloutResponseContents()
    {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        req.setMethod('GET');      
        HttpResponse res = h.send(req);
        
        return res.getBody();
        
        
    }
}
 
<aura:component implements="flexipage:availableForAllPageTypes" 
                access="global"
                controller="httpCalloutController">
    
    <aura:attribute name="response" type="string"/>
    
    <aura:attribute name="jsonoutput" type="Object"/>
    
    <lightning:button label="Make Callout" 
                      title="Make Callout"
                      onclick="{!c.MakeCallOut}"/>
    
    {!v.jsonoutput}
    
</aura:component>
 
({
    MakeCallOut : function(component, event, helper) {
        
        debugger;
        var action=component.get('c.getCalloutResponseContents');
        action.setCallback(this, function(response) {
            var state = response.getState();
            console.log('state ='+state);
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.jsonoutput", response.getReturnValue());
                console.log('v.response='+ response.getReturnValue());
            }
        });
        
        $A.enqueueAction(action);
    },
})

 

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Sheila,

I trust you are doing very well.

First, you have to Authorize the endpoint URL For Apex Callout in remote site settings.

Secondly, if you check in debug logs you can see this error: System.TypeException: Invalid conversion from runtime type Map<String,ANY> to String
You are assigning Map < String, Object > to String, that's why you are getting ERROR state in the controller.

And you are using void return type, so you will not get any value from Apex to JS controller. if you want to show output in the lightning component you need to return the value in the Apex method. 

Also, you are using console.log('v.response='+v.response); which is wrong. You need to use console.log('v.response='+component.get('v.response'));

Please refer to the below link for more information on How to Make HTTP Callout from Lightning component:

http://sfdcmonkey.com/2017/01/02/http-callout-lightning-component/

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Raj VakatiRaj Vakati
Use this code
 
public class httpCalloutController {
    
    @AuraEnabled
    public static String getCalloutResponseContents()
    {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        req.setMethod('GET');      
        HttpResponse res = h.send(req);
        
        return res.getBody();
        
        
    }
}
 
<aura:component implements="flexipage:availableForAllPageTypes" 
                access="global"
                controller="httpCalloutController">
    
    <aura:attribute name="response" type="string"/>
    
    <aura:attribute name="jsonoutput" type="Object"/>
    
    <lightning:button label="Make Callout" 
                      title="Make Callout"
                      onclick="{!c.MakeCallOut}"/>
    
    {!v.jsonoutput}
    
</aura:component>
 
({
    MakeCallOut : function(component, event, helper) {
        
        debugger;
        var action=component.get('c.getCalloutResponseContents');
        action.setCallback(this, function(response) {
            var state = response.getState();
            console.log('state ='+state);
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.jsonoutput", response.getReturnValue());
                console.log('v.response='+ response.getReturnValue());
            }
        });
        
        $A.enqueueAction(action);
    },
})

 
This was selected as the best answer
sheila srivatsavsheila srivatsav
Hi raj
I worked on your code and its working.

I want to know how to deserialize the return from the api

Here's my code
public class httpCalloutController {

    @AuraEnabled
    public static List<String> getCalloutResponseContents(string url)
    {
        Http h = new Http();
        
        HttpRequest req = new HttpRequest();
		req.setEndpoint(url);
        
		req.setMethod('GET');      
        
     
		HttpResponse res = h.send(req);
	
       
        //I want to deserialize the response .

        List<string> resultstring = (List<string>)JSON.deserializeUntyped(res.getBody());
        
        return resultstring;
     }
}

<aura:component implements="flexipage:availableForAllPageTypes" 
                access="global"
                controller="httpCalloutController">
    
    <aura:attribute name="response" type="List"/>
    
	<aura:attribute name="jsonoutput" type="Object"/>
    
    <lightning:button label="Make Callout" 
                      title="Make Callout"
                      onclick="{!c.MakeCallOut}"/>
    <br/> <br/>
    {!v.response}
    <br/>
    {!v.jsonoutput}
 </aura:component>

({
	MakeCallOut : function(component, event, helper) {
		
        debugger;
        var action=component.get('c.getCalloutResponseContents');
        action.setParams({
           "url":'https://th-apex-http-callout.herokuapp.com/animals'
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
          
                component.set("v.response", response.getReturnValue());
          
                console.log('v.response='+response.getReturnValue());
                
             }
        });
 
        $A.enqueueAction(action);
    },
})
thanks
sheila
 
sheila srivatsavsheila srivatsav
Hi khan & raj

thanks fior the answer