LWC: Display Latest News using API

In this post we are going to see how to show latest news fetched from API in salesforce Lightning Web Components.

Key Features:

1)I have used free source api (REST Service) to get the latest news.

2)On click of article link/image, new tab will be opened showing the full article.

3)We can also change country and category of news.

  • First you need to login and subscribe to the Basic plan(no charges) in NewAPI website to get the api details.Click here to register
  • Once you subscribed to the basic plan we will get the "key",using this we will hit the service to get the latest news.
  • We need to use "GET" method and use the end point url with key which we got from the NewsAPI site.
  • Below is the endpoint url I am going to use.
  "http://newsapi.org/v2/top-headlines?country=in&apiKey=yourapikey"

  • Now url is ready,write a apex class to fetch the data and deserialize the json to custom list.


getLatestNewsClass.apxc

  • Create a New Lightning Web Component to show the news fetched from api.We will have two  components here Parent(getLatestNewsLWC) and Child(newsTileComponent).
  • In connectedCallback method I am calling apex class to fetch the data.
  • In Parent component I am using template:iteration to iterate all the articles and passing each article to the child component.

getLatestNewsLWC.html      

getLatestNewsLWC.js  

  • In Child component we get the article data from the parent component and show the articles in list.

newsTileComponent.html 

newsTileComponent.js

newsTileComponent.css

Comments

Post a Comment