In this tutorial we’ll go through how to create a simple app using RapidAPI, Next.js and the World News API.
Tired of looking through countless news websites to stay up-to-date with the latest developments around the world? Look no further than World News API. With access to thousands of news sources from over 150 countries and 50 languages, World News API makes it easy to find the news that matter to you.
But that’s not all. World News API’s unique semantic tagging system allows for more nuanced and precise news searches than ever before. Say goodbye to the endless scrolling and get the news you need with World News API.
The very first step before interacting with the World News API is to get an API key. Here is an overview of the steps required to get API keys:
Let’s have a look at the process in detail.
Create an account using either Google, Github, Facebook, or your Email.
After your account has been created, go to the World News API page.
On the World News API page, click on “Subscribe to Test”.
![Choose a plan][https://worldnewsapi.com/img/tutorial-2/subscribe_tiers.png]
Now that we have the API key, let’s have a look at how we can use the RapidAPI interface to craft custom requests.
Firstly, let’s have a look at the endpoints World News API offers:
For this example, let’s extract the 10 latest news articles from a given country or location. For this, we will be using the search-news endpoint.
After choosing the endpoint, let’s customize our request so that it matches what we are trying to achieve.
To do so, we will modify the custom-parameters. But before that, let’s have a look at the custom-parameters of search-news.
Parameter Name | Function | Type |
---|---|---|
text | The text to match in the news content. | String |
sort | The sorting criteria (relevance, publish-time, or sentiment). | String |
sort-direction | Whether to sort ascending or descending. | String |
min-sentiment | The minimal sentiment of the news in range [-1,1]. | Number |
max-sentiment | The maximal sentiment of the news in range [-1,1]. | Number |
earliest-publish-date | The news must have been published after this date. | String |
latest-publish-date | The news must have been published before this date. | String |
location-filter | Filter news by radius around a certain location. Format is “latitude,longitude,radius in kilometers”, e.g. 51.050407, 13.737262, 100 | String |
entities | Filter news by entities, e.g. ORG:Tesla. | String |
news-sources | A comma-separated list of news sources from which the news should originate, e.g. https://www.bbc.co.uk | String |
authors | A comma-separated list of author names. Only news from any of the given authors will be returned. | String |
language | The ISO 6391 language code of the news, e.g. “en” for English. | String |
source-countries | A comma-separated list of ISO 3166 country codes from which the news should originate, e.g. gb,us. | String |
offset | The number of news to skip in range [0,1000] | Number |
number | The number of news to return in range [1,100] | Number |
Keeping the above parameters in mind, we will only use latest-publish-date
, earliest-publish-date
, number
and source-countries
to get extract the 10 latest news articles from a given country.
We will add relevant values to the above parameters, for the rest we will either do not write anything in them or choose the option “Do not include in request.” It will look something like this:
After you we are done customizing the parameters, let’s copy the generated request in the language of our choice.
For our example, the code snippet is as follows:
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-api-key',
'X-RapidAPI-Host': 'world-news3.p.rapidapi.com'
}
};
fetch('https://world-news3.p.rapidapi.com/search-news?sort=publish-time&latest-publish-date=2022-05-23%2024%3A16%3A27&earliest-publish-date=2022-04-22%2016%3A12%3A35&number=10&source-countries=gb%2Cus', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
Now to demonstrate the integration of API in an application, let’s create a demo app in Next.js
Make sure you have installed Node.js and npm. If you have not installed Node.js:
If you’re using OS X or Windows:
If you’re using Linux or another operating system, use one of the following installers:
Or see this page to install npm for Linux in the way many Linux developers prefer.
Let’s create our application. To do so, execute the following command in the directory where you would like the application to be saved.
npx create-next-app news-app
Upon executing, it will look something like:
Now, navigate to the newly created project directory using:
cd news-app
Run the project by executing the following:
npm run dev
By default, the project is hosted at http://localhost:3000.
Let’s create the User Interface first. For our demo, here is the code that was used:
import Head from 'next/head'
import Image from 'next/image'
import styles from '@/styles/Home.module.css'
export default function Home() {
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<main className={styles.main}>
<div className={styles.title}>
<h1 style={{textAlign: 'center'}}>
<code className={styles.code}>World News API Demo</code>
</h1>
<p>
Your favourite outlet for all the latest news
</p>
</div>
<div className={styles.center}>
<Image
src=""
alt=""
width="0"
height="0"
sizes="100vw"
style={{ width: '100%', height: 'auto' }}
/>
</div>
<h3 style={{margin: '10px', textAlign: 'center'}}>
</h3>
<textarea
className={styles.text}
rows='20'
value=""
readOnly
>
</textarea>
<div className={styles.submit}>
<button className={styles.btn} > Prev </button>
<button className={styles.btn} >Get News!</button>
<button className={styles.btn} > Next </button>
</div>
</main>
</>
)
}
and the Home.module.css
:
.main {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
padding: 2rem 0rem 2rem 0rem;
font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono',
'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro',
'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;;
min-height: 50vh;
}
.text {
width: 70%;
font-size: 0.97rem;
padding: 1rem 1.2rem;
background: rgba(180, 185, 188, 0.038);
border: 1px solid rgba(180, 185, 188, 0.3);
border-radius: 12px;
transition: background 200ms, border 200ms;
resize: none;
}
.submit {
display: flex;
padding: 10px;
flex-direction: row;
align-items: center;
justify-content: space-between;
width: 40%;
}
.btn {
font-family: "Open Sans", sans-serif;
font-size: 16px;
letter-spacing: 2px;
text-decoration: none;
text-transform: uppercase;
color: #e8e2e2;
cursor: pointer;
border: 3px solid;
padding: 0.25em 0.5em;
box-shadow: 1px 1px 0px 0px, 2px 2px 0px 0px, 3px 3px 0px 0px, 4px 4px 0px 0px, 5px 5px 0px 0px;
position: relative;
user-select: none;
touch-action: manipulation;
}
.btn:active {
box-shadow: 0px 0px 0px 0px;
top: 5px;
left: 5px;
}
@media (min-width: 768px) {
.btn {
padding: 0.25em 0.75em;
}
}
@media (hover: hover) and (pointer: fine) {
.text:hover {
background: rgba(var(--card-rgb), 0.1);
border: 1px solid rgba(180, 185, 188, 0.15);
}
}
.code {
font-weight: 700;
}
.center {
display: flex;
justify-content: center;
align-items: center;
position: relative;
padding: 4rem 0;
}
.logo
{
position: relative;
}
Which will look something like this:
To fetch news using the World News API, let’s use the fetch request we generated using RapidAPI.
Here’s the modified code with fetching news:
import Head from 'next/head'
import Image from 'next/image'
import styles from '@/styles/Home.module.css'
import React, { useEffect, useState } from "react";
export default function Home() {
const [newsData, setNewsData] = useState([]);
const [currentNewsIndex, setCurrentNewsIndex] = useState(0);
useEffect(() => {
console.log(currentNewsIndex);
})
function getNews()
{
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-api-key',
'X-RapidAPI-Host': 'world-news3.p.rapidapi.com'
}
};
fetch('https://world-news3.p.rapidapi.com/search-news?sort=publish-time&latest-publish-date=2022-05-23%2024%3A16%3A27&earliest-publish-date=2022-04-22%2016%3A12%3A35&number=10&sort-direction=desc&source-countries=au', options)
.then(response => response.json())
.then(data => {
setNewsData(data.news);
})
.catch(err => console.error(err));
}
function switchPage(dec)
{
if (newsData == null) {
return;
}
if (dec == true && currentNewsIndex > 0) {
setCurrentNewsIndex(currentNewsIndex - 1);
return;
}
if (dec == false && currentNewsIndex < 9) {
setCurrentNewsIndex(currentNewsIndex + 1);
return;
}
}
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<main className={styles.main}>
<div className={styles.title}>
<h1 style={{textAlign: 'center'}}>
<code className={styles.code}>World News API Demo</code>
</h1>
<p>
Your favourite outlet for all the latest news
</p>
</div>
<div className={styles.center}>
<br></br>
<Image
src={newsData[currentNewsIndex]?.image}
alt=""
width="0"
height="0"
sizes="100vw"
style={{ width: '100%', height: 'auto' }}
/>
</div>
<h3 style={{margin: '10px', textAlign: 'center'}}>
{newsData[currentNewsIndex]?.title}
</h3>
<textarea
className={styles.text}
rows='20'
value={newsData[currentNewsIndex]?.text}
readOnly
>
</textarea>
<div className={styles.submit}>
<button className={styles.btn} onClick={() => switchPage(true)}> Prev </button>
<button className={styles.btn} onClick={getNews}>Get News!</button>
<button className={styles.btn} onClick={() => switchPage(false)}> Next </button>
</div>
</main>
</>
)
}
The result is something like this:
Congratulations! You have successfully created an application which can communicate with the Real World News API. Get ready to dive into the latest headlines!