World News

FREEMIUM
By WorldNewsAPI | Updated 2 months ago | News, Media
Popularity

8.7 / 10

Latency

3,312ms

Service Level

100%

Health Check

N/A

Back to All Tutorials (1)

Breaking News Made Easy: How to Use WorldNewsAPI and Next js

In this tutorial we’ll go through how to create a simple app using RapidAPI, Next.js and the World News API.

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.

Getting the API Keys

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:

  • Create an account on RapidAPI.
  • Navigate to World News API page on RapidAPI.
  • Subscribe to the API to test it out.
  • Find the API key in the header parameters.

Let’s have a look at the process in detail.

  1. Head to the Sign Up page of RapidAPI.

Sign Up Screen

  1. Create an account using either Google, Github, Facebook, or your Email.

  2. After your account has been created, go to the World News API page.

  3. On the World News API page, click on “Subscribe to Test”.

Click on "Subscribe to Test"

  1. In the new window, you will be offered different plans of subscription. Choose one which suits you best and click on “Subscribe”. For this tutorial, we will be subscribing to the “Basic” plan.

![Choose a plan][https://worldnewsapi.com/img/tutorial-2/subscribe_tiers.png]

  1. After choosing a plan, enter your payment details in the new window. After the procedure, you will be succesfully subscribed to the World News API!
  2. Now back to the World News API page, you will notice that you have a “X-RapidAPI-Key”, note this down somewhere for later use. Don’t share it with anyone!

API Key!

Setting up the API

Now that we have the API key, let’s have a look at how we can use the RapidAPI interface to craft custom requests.

Endpoints

Firstly, let’s have a look at the endpoints World News API offers:

  • geo-coordinates - Gets the geo coordinates for a location. The location can be an exact address but also just the name of a city or country.
  • extract-news - Extract a news article from a news site.
  • search-news - Search, filter, and sort news articles.

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.

Choose "search-news" endpoint

Custom Request Parameters

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

Setting the Parameters

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:

Custom Params

Generating the Request Code

After you we are done customizing the parameters, let’s copy the generated request in the language of our choice.

  • In the code snippet tab, click on the language drop down and choose your desired language.
  • Copy the generated code snippet.

Generate request

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));

Creating a Next.js Application

Installing Node.js

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.

Creating Next.js App

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:

Create Next.js App

Now, navigate to the newly created project directory using:

cd news-app

Goto Project Directory

Run the project by executing the following:

npm run dev

Run the Program

By default, the project is hosted at http://localhost:3000.

Creating the UI

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:

UI

Fetching the News

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:

Working!

Congratulations! You have successfully created an application which can communicate with the Real World News API. Get ready to dive into the latest headlines!