How to Integrating Google News API with Apex Class baed on Account Name in Salesforce | How to display Google News based on Account Name Using Google News API with Apex Class Method Callouts (Remote Site Settings) In Salesforce

583 views


Hey guys, today in this post we are going to learn about How to display Google News based on Account Name Using Google News API with Apex Class Method (Remote Site Settings) in Salesforce.

News API is a simple HTTP REST API for searching and retrieving live articles from all over the web. To know more details about Google New Integration API, go with below link:-

Search worldwide news to get code of Get API Key, Click Here

Note:: โ€“ You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
   

 

Final Output โ†’

display google news based on account name Using google news api with Apex Class -- w3web.net

 

You can download file directly from github by Click Here.

 

Other related post that would you like to learn in Salesforce

 

  • Find the below steps โ–พ

 

Create Lightning Component

Step 1:- Create Lightning Component : googleNewsCmp.cmp

From Developer Console >> File >> New >> Lightning Component

Note:: โ€“ You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

googleNewsCmp.cmp [Lightning Component File]

  1.     <aura:component controller="googleNewsController2" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" description="c:googleNewsCmp">
  2.     <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
  3.     <aura:attribute name="itemList" type="List"/>
  4.     <aura:attribute name="titleList" type="List"/>
  5.     <aura:attribute name="linkList" type="List"/>
  6.     <aura:attribute name="descList" type="List"/>
  7.     <aura:attribute name="jsnonStr" type="Object"/>
  8.     <aura:attribute name="accName" type="String"/>
  9.      <aura:handler name="change" value="{!v.accName}" action="{!c.doInit}"/>  
  10.     <lightning:card>
  11.         <div class="slds slds-p-around_medium">
  12.  
  13.             <h3 style="background:#eee; border:1px #ccc solid; padding:5px;"><strong style="color:#ab0000; font-size:16px;">News :- </strong> <span style="color:#0099cf; font-size:16px;"> {!v.accName}</span></h3>
  14.             <br/>
  15.             <!-- ### {!v.jsnonStr}-->
  16.  
  17.           <div style="width:100%; max-height:400px; overflow:auto;">  
  18.             <table border="1" cellspacing="0" cellpadding="10" class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered slds-table_striped" style="border-collapse:collapse; border-color:1px #666 solid;">
  19.                 <aura:iteration items="{!v.itemList}" var="row">
  20.                     <tr>
  21.                         <td >
  22.                             <div class="slds-p-bottom_small"><a href="{!row.link}" target="_blank" rel="noopener noreferrer">{!row.title}</a></div>
  23.  
  24.                         </td> 
  25.  
  26.                     </tr>
  27.                 </aura:iteration>
  28.             </table>
  29.            </div> 
  30.         </div>
  31.     </lightning:card>  
  32. </aura:component>

 

Create JavaScript Controller

Step 2:- Create Lightning Component : googleNewsCmpController.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

googleNewsCmpController.js [JavaScript Controller]

  1.    ({
  2. 	doInit:function(component,event,helper){  
  3.       helper.getGoogleNews(component);
  4.       helper.accNewsHelper(component);  
  5.     },
  6. })

 

Create JavaScript Helper

Step 3:- Create Lightning Component : googleNewsCmpHelper.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper

googleNewsCmpHelper.js [JavaScript Helper File]

  1.    ({
  2.     getGoogleNews:function(component,event,helper){
  3.  
  4.         var recId= component.get("v.recordId");     
  5.         var accNameSpace = component.get("v.accName");
  6.  
  7.         var encodeAcc =  encodeURIComponent(accNameSpace);
  8.        // console.log('encodeAcc## ' , encodeAcc);
  9.  
  10.  
  11.         var action = component.get("c.newsGrabber");
  12.         action.setParams({          
  13.             "url": 'https://news.google.com/rss/search?cf=all&hl=en-IN&pz=1&q='+encodeAcc+'&gl=IN&ceid=IN:en',
  14.             "accId":recId,
  15.             "searchTerm":encodeAcc,
  16.         });
  17.         action.setCallback(this, function(response){  
  18.             var state = response.getState();
  19.             //alert('state_1 ' + state );
  20.             if(state == "SUCCESS"){  
  21.  
  22.                 var results = response.getReturnValue();              
  23.                  //console.log('AAAA' + JSON.stringify(results));
  24.                  var getResponse = JSON.stringify(results);
  25.  
  26.  
  27.                 const myObj = JSON.parse(results);
  28.  
  29.                var itemList =  myObj.channel.item;
  30.                    //console.log('itemList##1 ' , itemList);
  31.  
  32.                 for (var i = 0; i < myObj.channel.item.length; i++) {                  
  33.  
  34.  
  35.                     component.set("v.titleList", myObj.channel.item[i].title); 
  36.                     component.set("v.linkList", myObj.channel.item[i].link);
  37.  
  38.                 }
  39.  
  40.  
  41.              component.set("v.itemList", itemList); 
  42.  
  43.  
  44.  
  45.  
  46.  
  47.             }  
  48.         });  
  49.         $A.enqueueAction(action);
  50.     },
  51.  
  52.  
  53.  
  54.  
  55.  
  56.     accNewsHelper:function(component,event,helper, acStr){
  57.  
  58.        var recId= component.get("v.recordId");      
  59.         var action = component.get("c.accNews");
  60.         action.setParams({
  61.             "accId":recId,
  62.         });
  63.         action.setCallback(this, function(response){
  64.              var state = response.getState();             
  65.              if(state == "SUCCESS"){  
  66.                  var results = response.getReturnValue();              
  67.                  //console.log('AAAA' + JSON.stringify(results));
  68.                  component.set("v.accName", results.Name);
  69.             }
  70.         });
  71.          $A.enqueueAction(action);
  72.     },
  73.  
  74.  
  75.  
  76. })

 

Create Apex Class Controller

Step 4:- Create Apex Class : googleNewsController2.apxc

From Developer Console >> File >> New >> Apex Class

googleNewsController2.apxc [Apex Class Controller]

  1.    @RestResource(urlMapping='/googleNews2/') 
  2. global class googleNewsController2 {
  3.  
  4.     @AuraEnabled
  5.     global static String newsGrabber(String url, String accId, String searchTerm) {
  6.  
  7.         Http http = NEW Http();
  8.         HttpRequest httpReq = NEW HttpRequest();
  9.         HttpResponse httpRes = NEW HttpResponse();
  10.  
  11.         httpReq.setMethod( 'GET' );
  12.  
  13.        try { 
  14.  
  15.  
  16.            httpReq.setEndpoint(url);  
  17.            httpRes = http.send( httpReq );    
  18.  
  19.  
  20.         }catch(System.CalloutException e) {
  21.             System.debug('Callout error: '+ e); 
  22.         } 
  23.          String xmlBody = httpRes.getBody();
  24.          system.debug('xmlBody### ' + xmlBody);
  25.  
  26.          Dom.Document doc = NEW Dom.Document();  
  27.          doc.load( xmlBody);  
  28.  
  29.  
  30.         //accNews(accId);
  31.          RETURN parseDocumentToJson(doc);
  32.          //RETURN xmlBody;
  33.  
  34.  
  35.     }
  36.  
  37.     static Pattern 
  38.         boolPat = Pattern.compile('^(true|false)$'),  decPat = Pattern.compile('^[-+]?\\d+(\\.\\d+)?$'), 
  39.         datePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2}$'), 
  40.         timePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2} (\\d{2}:\\d{2}:\\d{2} ([-+]\\d{2}:\\d{2})?)?$');
  41.     //  PRIMARY FUNCTION TO decode XML
  42.     static Map<Object, Object> parseNode(Dom.XmlNode node, Map<Object, Object> parent) {
  43.  
  44.         FOR(Dom.XmlNode child: node.getChildElements()) {
  45.  
  46.             String nodeText = child.getText().trim(), name = child.getName();
  47.  
  48.             Object VALUE = 
  49.  
  50.                 String.isBlank(nodeText)? NULL:
  51.  
  52.             boolPat.matcher(nodeText).find()? 
  53.                 (Object)BOOLEAN.valueOf(nodeText):
  54.  
  55.             decPat.matcher(nodeText).find()?
  56.                 (Object)DECIMAL.valueOf(nodeText):
  57.  
  58.             datePat.matcher(nodeText).find()?
  59.                 (Object)DATE.valueOf(nodeText):
  60.  
  61.             timePat.matcher(nodeText).find()? 
  62.                 (Object)DateTime.valueOf(nodeText):
  63.  
  64.             (Object)nodeText;
  65.  
  66.             IF(VALUE != NULL) {
  67.  
  68.                 IF(name.endsWith('s')) {
  69.  
  70.                     IF(!parent.containsKey(name)) {
  71.                         parent.put(name, NEW List<Object>());
  72.                     }
  73.  
  74.                     ((List<Object>)parent.get(name)).add(VALUE);
  75.                 } ELSE {
  76.  
  77.                     parent.put(name, VALUE);
  78.                 }
  79.             } ELSE IF(child.getNodeType() == Dom.XmlNodeType.ELEMENT) {
  80.  
  81.                 Map<Object, Object> temp = parseNode(child, NEW Map<Object, Object>());
  82.  
  83.                 IF(!temp.isEmpty()) {
  84.  
  85.                     IF(parent.containsKey(name)) {
  86.                         try {
  87.  
  88.                             ((List<Object>)parent.get(name)).add(temp);
  89.                         } catch(Exception e) {
  90.  
  91.                             parent.put(name, NEW List<Object> { parent.get(name), temp });
  92.                         }
  93.                     } ELSE {
  94.  
  95.                         parent.put(name, temp);
  96.                     }
  97.                 }
  98.             }
  99.         }
  100.         RETURN parent;
  101.     }
  102.  
  103.  
  104.     global static Map<Object, Object> parseDocumentToMap(Dom.Document doc) {
  105.         RETURN parseNode(doc.getRootElement(), NEW Map<Object, Object>());
  106.     }
  107.  
  108.     global static String parseDocumentToJson(Dom.Document doc) {
  109.         RETURN JSON.serializePretty(parseDocumentToMap(doc));
  110.     }
  111.  
  112.     global static Object parseDocumentToObject(Dom.Document doc, TYPE klass) {
  113.         RETURN JSON.deserialize(parseDocumentToJson(doc), klass);
  114.     }
  115.  
  116.  
  117.     @AuraEnabled
  118.     global static Account accNews(String accId) {
  119.         Account accObj = [SELECT Id, Name FROM Account WHERE Id=:accId];
  120.         system.debug('accObj## ' + accObj);
  121.          RETURN accObj;
  122.     }
  123.  
  124. }

 

Create Remote Site Settings

Setup >> Search Quick Find >> Remote Site Settings >> New Remote Site

display google news based on account -- w3web.net

 

Further post that would you like to learn in Salesforce

 

 

 

FAQ (Frequently Asked Questions)

How do I use Google API in Apex?

Select any google API which need to be integrated. Select API and enable it for use. Create Credential for API to be used. This credential will be used in Apex.

What is the difference between Apex REST API and REST API?

The REST API (Force.com REST API) is the generic API provided by Salesforce. On the other hand, the Apex REST API is an API written by yourself in apex to provide custom methods.

What API used in Apex?

Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.

Related Topics | You May Also Like

 
Note:: โ€“ You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses โ†’

๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Salesforce Administrators

๐Ÿ“Œ Salesforce Lightning Flow Builder

๐Ÿ“Œ Salesforce Record Trigger Flow Builder

๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Aura Lightning Framework

๐Ÿ“Œ Lightning Web Component (LWC)

๐Ÿ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment