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
Final Output →
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
googleNewsCmp.cmp [Lightning Component File]
|
<aura:component controller="googleNewsController2" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" description="c:googleNewsCmp">
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="itemList" type="List"/>
<aura:attribute name="titleList" type="List"/>
<aura:attribute name="linkList" type="List"/>
<aura:attribute name="descList" type="List"/>
<aura:attribute name="jsnonStr" type="Object"/>
<aura:attribute name="accName" type="String"/>
<aura:handler name="change" value="{!v.accName}" action="{!c.doInit}"/>
<lightning:card>
<div class="slds slds-p-around_medium">
<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>
<br/>
<!-- ### {!v.jsnonStr}-->
<div style="width:100%; max-height:400px; overflow:auto;">
<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;">
<aura:iteration items="{!v.itemList}" var="row">
<tr>
<td >
<div class="slds-p-bottom_small"><a href="{!row.link}" target="_blank" rel="noopener noreferrer">{!row.title}</a></div>
</td>
</tr>
</aura:iteration>
</table>
</div>
</div>
</lightning:card>
</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]
|
({
doInit:function(component,event,helper){
helper.getGoogleNews(component);
helper.accNewsHelper(component);
},
})
Create JavaScript Helper
Step 3:- Create Lightning Component : googleNewsCmpHelper.js
From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper
googleNewsCmpHelper.js [JavaScript Helper File]
|
({
getGoogleNews:function(component,event,helper){
var recId= component.get("v.recordId");
var accNameSpace = component.get("v.accName");
var encodeAcc = encodeURIComponent(accNameSpace);
// console.log('encodeAcc## ' , encodeAcc);
var action = component.get("c.newsGrabber");
action.setParams({
"url": 'https://news.google.com/rss/search?cf=all&hl=en-IN&pz=1&q='+encodeAcc+'&gl=IN&ceid=IN:en',
"accId":recId,
"searchTerm":encodeAcc,
});
action.setCallback(this, function(response){
var state = response.getState();
//alert('state_1 ' + state );
if(state == "SUCCESS"){
var results = response.getReturnValue();
//console.log('AAAA' + JSON.stringify(results));
var getResponse = JSON.stringify(results);
const myObj = JSON.parse(results);
var itemList = myObj.channel.item;
//console.log('itemList##1 ' , itemList);
for (var i = 0; i < myObj.channel.item.length; i++) {
component.set("v.titleList", myObj.channel.item[i].title);
component.set("v.linkList", myObj.channel.item[i].link);
}
component.set("v.itemList", itemList);
}
});
$A.enqueueAction(action);
},
accNewsHelper:function(component,event,helper, acStr){
var recId= component.get("v.recordId");
var action = component.get("c.accNews");
action.setParams({
"accId":recId,
});
action.setCallback(this, function(response){
var state = response.getState();
if(state == "SUCCESS"){
var results = response.getReturnValue();
//console.log('AAAA' + JSON.stringify(results));
component.set("v.accName", results.Name);
}
});
$A.enqueueAction(action);
},
})
Create Apex Class Controller
Step 4:- Create Apex Class : googleNewsController2.apxc
From Developer Console >> File >> New >> Apex Class
googleNewsController2.apxc [Apex Class Controller]
|
@RestResource(urlMapping='/googleNews2/')
global class googleNewsController2 {
@AuraEnabled
global static String newsGrabber(String url, String accId, String searchTerm) {
Http http = NEW Http();
HttpRequest httpReq = NEW HttpRequest();
HttpResponse httpRes = NEW HttpResponse();
httpReq.setMethod( 'GET' );
try {
httpReq.setEndpoint(url);
httpRes = http.send( httpReq );
}catch(System.CalloutException e) {
System.debug('Callout error: '+ e);
}
String xmlBody = httpRes.getBody();
system.debug('xmlBody### ' + xmlBody);
Dom.Document doc = NEW Dom.Document();
doc.load( xmlBody);
//accNews(accId);
RETURN parseDocumentToJson(doc);
//RETURN xmlBody;
}
static Pattern
boolPat = Pattern.compile('^(true|false)$'), decPat = Pattern.compile('^[-+]?\\d+(\\.\\d+)?$'),
datePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2}$'),
timePat = Pattern.compile('^\\d{4}.\\d{2}.\\d{2} (\\d{2}:\\d{2}:\\d{2} ([-+]\\d{2}:\\d{2})?)?$');
// PRIMARY FUNCTION TO decode XML
static Map<Object, Object> parseNode(Dom.XmlNode node, Map<Object, Object> parent) {
FOR(Dom.XmlNode child: node.getChildElements()) {
String nodeText = child.getText().trim(), name = child.getName();
Object VALUE =
String.isBlank(nodeText)? NULL:
boolPat.matcher(nodeText).find()?
(Object)BOOLEAN.valueOf(nodeText):
decPat.matcher(nodeText).find()?
(Object)DECIMAL.valueOf(nodeText):
datePat.matcher(nodeText).find()?
(Object)DATE.valueOf(nodeText):
timePat.matcher(nodeText).find()?
(Object)DateTime.valueOf(nodeText):
(Object)nodeText;
IF(VALUE != NULL) {
IF(name.endsWith('s')) {
IF(!parent.containsKey(name)) {
parent.put(name, NEW List<Object>());
}
((List<Object>)parent.get(name)).add(VALUE);
} ELSE {
parent.put(name, VALUE);
}
} ELSE IF(child.getNodeType() == Dom.XmlNodeType.ELEMENT) {
Map<Object, Object> temp = parseNode(child, NEW Map<Object, Object>());
IF(!temp.isEmpty()) {
IF(parent.containsKey(name)) {
try {
((List<Object>)parent.get(name)).add(temp);
} catch(Exception e) {
parent.put(name, NEW List<Object> { parent.get(name), temp });
}
} ELSE {
parent.put(name, temp);
}
}
}
}
RETURN parent;
}
global static Map<Object, Object> parseDocumentToMap(Dom.Document doc) {
RETURN parseNode(doc.getRootElement(), NEW Map<Object, Object>());
}
global static String parseDocumentToJson(Dom.Document doc) {
RETURN JSON.serializePretty(parseDocumentToMap(doc));
}
global static Object parseDocumentToObject(Dom.Document doc, TYPE klass) {
RETURN JSON.deserialize(parseDocumentToJson(doc), klass);
}
@AuraEnabled
global static Account accNews(String accId) {
Account accObj = [SELECT Id, Name FROM Account WHERE Id=:accId];
system.debug('accObj## ' + accObj);
RETURN accObj;
}
}
Create Remote Site Settings
Setup >> Search Quick Find >> Remote Site Settings >> New Remote Site
Further post that would you like to learn in Salesforce
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
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 |