1

I have been trying to integrate Google Shortener API into my salesforce org. I wrote a class to make the call out, but am having difficulty bringing the value back into the record. I have a custom object called "referral_advocate__c" with a field called "Short_URL__c". Anytime the field "unique_ID__c" has a value, I am wanting to send this value with a static URL to google shortener and then save the response value to "referral_advocate__c.short_URL__c" on the record. This is the class to make the call out:

public class URLshort {

final string urls = 'https://www.myurl.com';
referral_advocate__c adv = new referral_advocate__c();

@future(callout = true)
public static void URLshortner() {

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();

    req.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=myapikey');
    req.setMethod('POST');
    req.setHeader('Content-Type','application/json');       
    req.setBody('{"longUrl":+urls + adv.unique_reference_number_c}');


    try {
        res = http.send(req);
        System.debug(res.getBody());
    } catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);
        System.debug(res.toString());
    }


}

}

The after insert trigger on "referral_advocate__c" I wrote is not firing correctly. How do I return the results from this class and update the field "short_URL__C" with the returned value from a trigger?

  • Create a response object that you deserialize res into, and what does System.debug(res.getBody()); say? – EricSSH May 26 '16 at 19:57
2

Your future method will need some input to act upon, so a set of referral_advocate__c Ids (for bulkification purposes; this set of Ids would be built in the trigger on any record that has unique_ID__c != null ):

    set<Id> idSet = new Set<Id>{};
    for(referral_advocate__c r : trigger.new){
        if((r.unique_ID__c != null){
            idSet.add(r.Id);
            if(idSet.size()==100) {
                urlshortner(idset);
                idSet.clear();
            }
        }       
    }
    if (!idSet.isEmpty()){
       URLShortener(idSet);
    }

then also an update action: (forgive any typos / syntax errors, didn't get a chance to try it out in my dev org): Your future method will need some input to act upon, so a set of referall_advocate__c Ids (for bulkification purposes; this set of Ids would be built in the trigger on any record that has short_URL__C != null ), then also an update action:

@future(callout = true)
public static void URLshortner(Set<Id> idSet) {
    List<referral_advocate__c> rList = new List<referral_advocate__c>();
    Http http = new Http();
    for (referral_advocate__c r : [SELECT unique_ID__c FROM referral_advocate__c WHERE Id in :idSet]){
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=myapikey');
        req.setMethod('POST');
        req.setHeader('Content-Type','application/json');       
        req.setBody(JSON.serialize(
            new Map<String, String> { 'longUrl' => urls + r.unique_ID__c}));
        try {
            HttpResponse res = http.send(req);
            //parse your json response for the value

            r.short_URL__C = retValue;
            rList.add(r);
        } catch(System.CalloutException ce){
            // handle callout error
        }
    } 
    Database.SaveResult results = Database.update(rList, false);
    // handle DML error
}

try something like this to get you started out.

  • 1
    With the bulkification, be mindful that you are limited to 100 callouts per transaction and a trigger could potentially send through 200 records. It might be easier to have a batch job process the required records (short_URL__C isn't set) and adjust the scope as required. – Daniel Ballinger May 26 '16 at 20:48
  • Dan Appleman's book Advanced Apex 3rd Edition Chapter 7 has a scalable async pattern that uses callouts to Google Translate as the example so very transferrable to the use case in OP – cropredy May 27 '16 at 1:06
  • Thank you for all the help, I am working on implementing now. Will provide an update soon! – JoshuaWS May 27 '16 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.