LWC | HTTP Callouts from Apex Controller

In this post, I am going to show how to make callouts (REST API or HTTP) from LWC (Lightning Web Components) from Server-Side controller (Apex Controller) in Salesforce. 
Also, have shown a simple example of how to use <lightning-carousel> for the Lightning Component UI.We will create a News Widget using callouts from LWC.

LWC CALLOUTS FROM SERVER SIDE SALESFORCE

Callouts from LWC can be done in two ways.

1. Client-side controller(JS controller) Checkout my previous post for sample code & App here: https://accidentalcoder.blogspot.com/2020/06/lwc-callouts-client-side.html

2. Using the server-side controller(Apex Class) - This is discussed in this Post and we will create a sample News Widget.



HTTP Callouts from Apex Controller (Server-Side) from Lightning Web Components:

To make callouts from an Apex Controller from LWC we will use HTTP method at server side and in Lightning Component I will use @wire decorator to call this method at page load to get the data. 

Creating A News Widget using Callouts:

We are going to create a sample News Widget to understand this capability. This Widget can be used on Home Pages, Records Pages or Community Pages.

I will be using the Free API called News API Org: Here is the link to create free account and get free API Key: https://newsapi.org/

Many options and different variations are available from this API. I am using a basic one. Checkout later in the code.

Let's see the steps for creating the same:

1. Create a Remote Site Setting: We first need to create a remote site setting so that Salesforce allows us to send request to this News API endpoint and we can send requests to it. In our case the Endpoint is newsapi.org.
LWC Callouts from Apex Controller

2. Sample Query String and JSON response:
Before we move forward we need to understand how to create query for calling the News API. Also, we need to understand how the sample JSON will look like.

There are many different versions of query which will return different type of data and different formats. Checkout NewsAPI.org for these variations and types of query.


Query Example:https://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=YOUR_API_KEY'


This is an example where we get headlines from a particular country. This returns the below JSON response. Based on this JSON response we can design or object structure to parse this JSON data. 


TiP: As a best practise store API key and all the dynamic parameter in a custom label or custom setting so that query parameters can be changed without changing the code in future. In our sample, it is the country name and category that can be changed to get different results.


Sample JSON Response for the query:

{
  "status": "ok",
  "totalResults": 70,
  "articles": [
    {
      "source": {
        "id": "the-times-of-india",
        "name": "The Times of India"
      },
      "author": "PTI",
      "title": "Indians' money in Swiss banks down 6% in 2019; hits 3rd lowest in over three decades - Times of India",
      "description": "India Business News: Funds parked by Indian individuals and enterprises in Swiss banks fell nearly 6% in 2019 to Rs 6,625 crore. This marks the second consecutive year of",
      "url": "https://timesofindia.indiatimes.com/business/india-business/indians-money-in-swiss-banks-down-6-in-2019-hits-3rd-lowest-in-over-three-decades/articleshow/76627341.cms",
      "urlToImage": "https://static.toiimg.com/thumb/msid-76627318,width-1070,height-580,imgsize-361878,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
      "publishedAt": "2020-06-25T16:16:26Z",
      "content": null
    }
 ]
}
3. Create Apex Method from JSON:
After this we need to create a wrapper model/Class based on this data in our Apex Controller. We will create a wrapper list to store all this info after parsing the JSON response .We will then use this wrapper list to send data to the lightning web component.

I used this link to create the Wrapper Model directly from JSON response sample: https://json2apex.herokuapp.com/

Just copy paste any Sample JSON response to create the sample wrapper model structure.

Later, in Apex controller we will use JSON.deserialise to typecast the JSON response as per our Wrapper structure directly and we can store all the different parameters from the JSON response info in our wrapper object's list. Checkout code later for more clarity.


4. Lightning Web Component:

In the Lightning Web Component, on the html side,I am using <lightning-carousel> component to create the Widget UI. Just because it looks cooler. I could have also used <lightning-card> or any other custom UI which would have shown much more info but for this example I am using carousel only. 

Note : Since we have all these different response values and info (title, author, source, date etc.)  in the JSON response which will be stored in a wrapper list, we can show any of that info in our UI. In my case I am just using Title,Description, Image URL and Article URL. You can use much more in real scenarios.


More details about Carousel here:https://developer.salesforce.com/docs/component-library/bundle/lightning-carousel/example


4. Here's the Code:


Apex Controller


newsApp.html

newsApp.js


newsApp.css


newsApp.js-meta.xml


And we are done. You can now use this component anywhere record page or home pages and try it out.


Here's the Demo Video:

Checkout my previous post for LWC Client Side Callouts https://accidentalcoder.blogspot.com/2020/06/lwc-callouts-client-side.html

If you like this please do Share! #Learn and Share!


Enter your email address:


Delivered by FeedBurner

Checkout my other posts here:

Comments


Never Miss Latest Posts