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
SFDC New learnerSFDC New learner 

how to callout the external url from trigger

Hi Everyone,

I have a requirement where I need to call the external webservice and populate the fields on insert or update of record.

Already there is a button on record built using lightning component which will pass few values to external system and in return it populates few fields based on the input fields.

the lightning button code looks like below:
Apex:

@AuraEnabled
    public static object__c updatemethod(Id objId) {
        List<Id> dlist = new List<Id>();
        List< object __c> ret;
        dlist.add(objId);
        if(dlist.size()>0){
            ret = class1.updatemethod2(getDetailsByIds(dlist));}
            return ret.get(0);
    }
Global with sharing class class1{
private static List< object __c> calculateDate(List< object __c> dList) {
                              for (object __c d : dList) {
           
            // If date is not filled in, fetch the values
            if (d.Month__c == null && d.Day__c == null &&
                d.Day_g__c != null && d.Month_g__c != null & d.Year_g__c != null) {
                    String[] hDate = getDateFromG(d.Day_g__c, d.Month_g__c,
                                                                              d.Year_g__c, d.IsChecked__c);
                    d.Year__c = hDate[0];
                    d.Month__c = hDate[1];
                    d.Day__c = hDate[2];
            }
Update dlist;
     }  

public static String[] getDateFromG (String dayg, String monthg,
                                                      String yearg, Boolean IsChecked) {
               String url = geturl(dayg, monthg, yearg, IsChecked);
                              System.debug(url);
        String json = getContent(url);

                              String[] ret = new String[3];
                              JSONParser parser = System.Json.createParser(json);
                                                          
                              while (parser.nextToken() != null) {
            system.debug('inside while');
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
               if (parser.getText() == 'hy') {
                               // Get the value.
                           parser.nextToken();
                       ret[0] = parser.getText();
                       System.debug('Year='+ret[0]);
               }
               …..
            }
        }
                              return ret;       
    }   
private static String getContent(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);
            return res.getBody();
    }
I added the below code when a new record is inserted or updated , it should fire the trigger and callout the url to retrieve and populate the fields in the record.
trigger TriggerInsertorupdate on object__c (after insert, after update) {

if(Trigger.isAfter){
         if(updation.isfutureupdate!=true)
            {
               id lst;
                for(Deceased__c e :Trigger.new)
                {
                    lst=e.Id;
                    system.debug('$$$$$$$$$$$'+lst);
                }
                if(lst!=null)
                UpdateController.updatemethod(lst);
            }
    }       
}
I am getting the following error. Please can anyone give some idea to achieve this .
TriggerInsertorupdate : execution of AfterInsert caused by: System.CalloutException: Callout from triggers are currently not supported. Class.class1.getContent: line 112, column 1 
Thanks in Advance,
Sirisha
VinayVinay (Salesforce Developers) 
Hi,

You do need to use the @future annotation in an apex method that is stored in a separate class. Then call that class and method from within your trigger.

Something like below
trigger Mytrigger on Account (after insert,after update) {
 samplecontroller.getIPGeolocation();
 }
 
public class samplecontroller {    
 @future(callout=true)
    public static void getIPGeolocation() {        
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api.ipstack.com/47.9.161.12?access_key=84cce4c3f6b699dc4');       
        req.setMethod('GET');
        HttpResponse res;
        res = h.send(req);
        System.debug('Result'+res.getbody());  
    }    
 }



Review below link which can give more information about above error.

https://help.salesforce.com/articleView?id=000330691&type=1&mode=1
https://www.infallibletechie.com/2019/12/callout-from-triggers-are-currently-not.html

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar
skyla traciskyla traci

Dollar General is an American chain of variety stores. Dollar General Corporation was founded in 1939.  It’s headquarters in Goodlettsville, Tennessee.
https://customerzsurvey.com/dollar-general-customer-satisfaction-survey/#Dollar_General_Near_Me_Locations
SFDC New learnerSFDC New learner
Hi Vinay,

Thanks for the reply. However, I want to pass day,month and year fields as input to the url and update the other fields based on these fields at the same time when insert or update the record. When I  use "GET" method to retreive data and parse the response and set the fields and update it, it is giving me error as future method failed. Is there any solution I can pass the url in future method in GET method and the result value to update at the same time. 
Can you please help to achieve on this to proceed further? 
public static String construct(String day, String month, 
                                                                 String year, Boolean IsChecked) {
        String urlPrefix = 'url';
        String retUrl = urlPrefix;
        retUrl += '&gy=' + yearG;
        retUrl += '&gm=' + monthG;
        retUrl += '&gd=' + dayG;
        retUrl += '&gs=' + (IsChecked? '1' : '0');
        return retUrl;
    }
private static String getContent(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);
            return res.getBody();
    }
Global with sharing class class1{
private static List< object __c> calculateDate(List< object __c> dList) {
                              for (object __c d : dList) {
           
            // If date is not filled in, fetch the values
            if (d.Month__c == null && d.Day__c == null &&
                d.Day_g__c != null && d.Month_g__c != null & d.Year_g__c != null) {
                    String[] hDate = getDateFromG(d.Day_g__c, d.Month_g__c,
                                                                              d.Year_g__c, d.IsChecked__c);
                    d.Year__c = hDate[0];
                    d.Month__c = hDate[1];
                    d.Day__c = hDate[2];
            }
Update dlist;
     }  

public static String[] getDateFromG (String dayg, String monthg,
                                                      String yearg, Boolean IsChecked) {
               String url = geturl(dayg, monthg, yearg, IsChecked);
                              System.debug(url);
        String json = getContent(url);

                              String[] ret = new String[3];
                              JSONParser parser = System.Json.createParser(json);
                                                          
                              while (parser.nextToken() != null) {
            system.debug('inside while');
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
               if (parser.getText() == 'hy') {
                               // Get the value.
                           parser.nextToken();
                       ret[0] = parser.getText();
                       System.debug('Year='+ret[0]);
               }
               …..
            }
        }
                              return ret;       
    }   
@future(callout = true) 
    public static void sendcallout(Id deceasedId){
        sendrequesttohebcal(deceasedId);
    }

Thanks,
Sirisha