Friday, January 17, 2020

Bootstrp + jQuery + news REST API example

Sample code snippet will help in understanding how to consume REST services using jQuery and displaying content using Bootstrap.

The directory structure:

Live : https://jsl-news.glitch.me/

newspp
   - css
         - main.css
  - js
       - news.js

  - index.html

main.css

 #subBtn{  
   margin-top: 13%;  
 }  


index.html

 <!doctype html>  
 <html lang="en">  
  <head>  
   <!-- Required meta tags -->  
   <meta charset="utf-8">  
   <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">  
   <!-- Bootstrap CSS -->  
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">  
   <link rel="stylesheet" href="css/main.css">  
   <title>News - Items</title>  
  </head>  
  <body>  
   <div class="py-3 bg-primary text-white text-center">  
     <h3>Search worldwide news with code</h3>  
     <p class="lead">Get breaking news headlines, and search for articles from over 30,000 news sources and blogs with our news API</p>  
   </div>  
   <div class="container">  
     <h5 class="text-muted text-center mt-2">Please select the details to get updated news</h5>  
     <div class="row">  
       <div class="col-md-3"></div>  
       <div class="col-md-3">  
         <label for="country">Select Country</label>  
         <select class="form-control" id="country">  
           <option value="in">India</option>  
           <option value="us">United State</option>  
           <option value="sg">Singapore</option>  
         </select>  
       </div>  
       <div class="col-md-3">  
         <label for="category">Select Category</label>  
         <select class="form-control" id="category">  
           <option value="sports">Sports</option>  
           <option value="health">Health</option>  
           <option value="business">Business</option>  
         </select>  
       </div>  
       <div class="col-md-3">  
         <button id="subBtn" class="btn btn-primary">Submit</button>  
       </div>  
     </div>  
     <!--New items-->  
     <div class="row mt-5">  
       <div class="col-md-6 offset-md-3" id="showResult">  
       </div>  
     </div>  
    </div>  
   <!-- Optional JavaScript -->  
   <!-- jQuery first, then Popper.js, then Bootstrap JS -->  
   <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>  
   <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>  
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>  
   <script src="js/news.js"></script>  
 </body>  
 </html>  


JavaScript: news.js

  const url = "https://newsapi.org/v2/top-headlines?";  
  const apikey = "5c636a468a90465aa7cab199265d7299";  // Change the key by registering with news api
 class News{  
   constructor(title,author,description,urlToImage){  
     this.title = title;  
     this.author = author;  
     this.description = description;  
     this.urlToImage = urlToImage;  
   }  
 }  
  subBtn = document.querySelector("#subBtn");  
 function showNews(news){  
   str ="";  
   count = 1;  
   for(let item of news){  
     str += `<b>#${count++}<br>  
     <div class="card mt-2 mb-2">  
     <img src="${item.urlToImage}" class="card-img-top" alt="...">  
     <div class="card-body">  
      <h5 class="card-title">${item.title}</h5>  
      <p class="card-text">  
      <b>${item.author}</b>  
      <br>  
      ${item.description}  
      </p>  
      <a href="#" class="btn btn-primary">Go somewhere</a>  
     </div>  
    </div>  
    `  
   }  
   document.querySelector("#showResult").innerHTML = str;  
 }  
 subBtn.addEventListener('click',(e)=>{  
     let countryName = document.querySelector("#country").value;  
     let categoryValue = document.querySelector("#category").value;  
     let reqURL = `${url}country=${countryName}&apiKey=${apikey}&category=${categoryValue}`;  
     fetch(reqURL).then(rawData=>{  
       return rawData.json();  
     }).then(data=>{  
       news = [];  
       articles = data["articles"];  
          for(let article of articles){  
         newsItem = new News(article.title,article.author,article.description,article.urlToImage);  
         news.push(newsItem);  
       }  
       showNews(news);  
     }).catch(error=>{  
       alert("While getting news we got ",error);  
     })  
  })  

 Sample output:





No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...