Things are always changing in the world, and it can be very useful for all of us to be able to keep up with those changes. But there’s so much news out there, on so many different topics, that we need ways to filter all of it down to only what’s relevant and useful to us. Making apps and websites, using algorithms, and writing software components can be a great way to achieve this for many people, with only a little effort.
Using News and Media APIs can improve your app in several ways:
Tip: Not sure what an API is? Check out What is an API?
If you check out the News & Media category on RapidAPI, you’ll see a very interesting list of APIs that already do a lot of this legwork for us. There are aggregation APIs, search APIs, APIs produced by using AI, and many more.
One that sticks out as particularly interesting is an API from Microsoft Azure, called Bing News Search API, because it uses AI to ensure the most relevant possible search results.
Before we can test out the API endpoints, we need to subscribe to them. This API is Freemium, which means it has a basic free plan, which comes with a hard limit of 1000 requests / month.
For the amount of benefit this API gives, the costs of the higher tiers are well worth it. But for our purposes, we’re just going to stick to the Basic plan, which is plenty for our little React News app.
Tip: For more information about API requests, check out the article What is an API Request?
To start using this API:
You may need to fill in payment information, but don’t worry, none of it will be used here, since there’s a hard limit on this plan. Since you won’t be able to go over the limit, your payment method will not be charged. Besides, if you decide to upgrade to a higher plan, you’ll have already done this step!
Note: For these steps to work, make sure you have a RapidAPI account! It’s free, and you instantly get access to many APIs.
The API endpoint we’re interested here is “News Search”. We give it a query string, and we get back a list of articles. Perfect for our needs! So select that particular endpoint on the left sidebar.
Tip: Not sure how API Endpoints fit into all this? Check out the article What is an API Endpoint?
The only required parameter is the query string. Let’s fill it out right now with “react.js” as a sample parameter. This should give us back some data that will help us to understand the structure of this API’s response data.
Click “Test Endpoint”, and you’ll see something like this:
After inspecting this data in RapidAPI’s “Results” tab, we see a few interesting details:
value
.name
, description
, category
, and datePublished
.image
key for the article’s thumbnail.provider
key, and some have their own thumbnail too.Great, this will work perfectly to help us make the React Component.
React, also called React.js, is a front-end JavaScript framework, used by increasingly more software professionals around the world. As websites and apps become more complex, the front-end code needs to adapt to that complexity. But older frameworks haven’t always kept up. That’s why React was created, to make writing front-end code simpler and quicker, especially for bigger apps and sites.
In React, you describe what your view should look like, given your React Component’s state and props. In other words, you describe what your JavaScript component should do and look like, without having to spend a ton of effort on describing how it should happen. React takes care of all the rest for you.
In this blog post, we’re going to make a simple React Component that uses News APIs to show search results for any given query. At the end, this is what we’ll have:
Setting up a React app used to be more complicated, but thanks to Create React App, now it’s a breeze. Let’s use that utility to make our lives simpler:
npx create-react-app react-news-app --use-npm
cd react-news-app
npm start
On the Big News Search API page, grab the JavaScript code needed for React:
For now, just pay attention to the steps you would take. But for your convenience, I’ve improved on this code snippet with the following steps:
This resulted in what has become the searchNews
function in the code below (in Step 3).
In the React project we created in Step 1, replace the contents of src/App.js
with the following React code:
import React from 'react'; import './App.css'; async function searchNews(q) { q = encodeURIComponent(q); const response = await fetch(`https://bing-news-search1.p.rapidapi.com/news/search?freshness=Day&textFormat=Raw&safeSearch=Strict&q=${q}`, { "method": "GET", "headers": { "x-rapidapi-host": "bing-news-search1.p.rapidapi.com", "x-rapidapi-key": /* paste your RapidAPI key here */, "x-bingapis-sdk": "true" } }); const body = await response.json(); return body.value; } function App() { const [query, setQuery] = React.useState("docker"); const [list, setList] = React.useState(null); const search = (e) => { e.preventDefault(); searchNews(query).then(setList); }; return ( <div className="app"> <form onSubmit={search}> <input autoFocus value={query} onChange={e => setQuery(e.target.value)} /> <button>Search</button> </form> {!list ? null : list.length === 0 ? <p><i>No results</i></p> : <ul> {list.map((item, i) => ( <Item key={i} item={item} /> ))} </ul> } </div> ); } function Item({ item }) { const separateWords = s => s.replace(/[A-Z][a-z]+/g, '$& ').trim(); const formatDate = s => new Date(s).toLocaleDateString(undefined, { dateStyle: 'long' }); return ( <li className="item"> {item.image && <img className="thumbnail" alt="" src={item.image?.thumbnail?.contentUrl} /> } <h2 className="title"> <a href={item.url}>{item.name}</a> </h2> <p className="description"> {item.description} </p> <div className="meta"> <span>{formatDate(item.datePublished)}</span> <span className="provider"> {item.provider[0].image?.thumbnail && <img className="provider-thumbnail" alt="" src={item.provider[0].image.thumbnail.contentUrl + '&w=16&h=16'} /> } {item.provider[0].name} </span> {item.category && <span>{separateWords(item.category)}</span> } </div> </li> ); } export default App;
Note: You’ll need to paste your RapidAPI key into this code, within the searchNews
function. You can find this in the original code snippet you copied earlier.
In this code, we did three simple things:
searchNews
async function, which calls the News API and gets the news articles JSON back.App
component, with a search field and a button that calls searchNews
, and displays each news item using Item
.Item
component which shows each news item in a compact, organized, and aesthetic way.In our App
component:
query
in state using React Hooks, using a default value of "docker"
.list
variable.null
list, to differentiate between “not yet searched” and “got empty results”.input
field.Our Item
component may be longer, but it’s actually simpler:
Right now our app works. But it’s ugly. With just a little bit of modern CSS, we can make it look much more professional with almost no effort.
So paste the following code into your src/App.css
file:
body { background: #f7f7f7; } * { margin: 0; padding: 0; } .app { width: 45em; display: grid; gap: 1em; margin: 3em; } form { display: grid; grid-template-columns: 1fr auto; gap: 1em; } button { background: #17f; color: #fff; font: inherit; border: none; border-radius: 3px; outline: none; padding: 0.5em 1.5em; } button:active { background-color: #05b; } input { border: 1px solid #999; border-radius: 3px; font: inherit; padding: 0.5em; outline: none; } input:focus { outline: auto #17f; } .item { padding: 1em; list-style-type: none; border-radius: 6px; margin-bottom: 1em; background: #fff; box-shadow: 0px 2px 6px 2px #0002; } .item .title { font-size: 100%; } .item .description { margin: 1em 0; } .item .thumbnail { float: right; box-shadow: 0px 1px 1px 1px #0002; border-radius: 12px; margin-left: 1em; margin-bottom: 1em; } .item .meta { font-size: 80%; font-weight: bold; color: #555; } .item .provider-thumbnail { margin-right: 0.5em; } .item .meta > *:not(:last-child) { margin-right: 2em; }
Now we have a professional, respectable little React News app!
Try searching for phrases like “Docker”, “Kubernetes”, “GitHub” or “Linux”.
Using News APIs is not hard, and can be a great data source for your news apps and sites. Or, if your app isn’t centered on news, adding a little news on the side can keep your users up-to-date in their particular field of interest. By using React, we can make our news apps even more quickly and easily, and add News APIs with almost no effort!
Things are always changing in the world, and it can be very useful for all of us to be able to keep up with those changes. But there’s so much news out there, on so many different topics, that we need ways to filter all of it down to only what’s relevant and useful to us. Making apps and websites, using algorithms, and writing software components can be a great way to achieve this for many people, with only a little effort. Using News and Media APIs can improve your app in several ways:
1. Subscribe to the API. 2. Find the Search API endpoint. 3. Fill out the required parameters. 4. Test the API Endpoint.
1. Setup our React app. 2. Find our JavaScript code snippet. 3. Add our React Component's code. 4. Add our CSS styling code. 5. Try it out!
We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…
Are you curious about what your API consumers are searching for? Is your Hub effectively…
The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…
This January's release brings exciting features and improvements designed to empower you and your developers.…
Rapid API is committed to providing its users with the best possible experience, and the…
In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…
View Comments
I built a News App with React. I want to improve on search with ElasticSearch but I wouldn't know. I'll be glad if you can help me.
Getting error on line no:14
as
Cannot read property 'json' of undefined
it is due to your "Item "tag is not used