News API with Python

News API with Python

API (Application Programming Interface) is a software intermediary that allows two applications to interact with each other. Using API in python is easier than any other programming language. In this post, we will use news API to get the desired news.

First, we have to register on news API and get a free API Key. We will use this API key to fetch data from various news sources.

The News API website shows all the instructions on how to use API in different ways. We have the option to choose from top-headlines, everything, and sources.

With top headlines, we can select sources, categories, languages, and countries. With everything, we have options to choose from dates, domains, sources, and relevancy.

This is the main URL of the news API we would be using here:

https://newsapi.org/v2/everything?q=bitcoin&apiKey=*************

Here q is the keyword or phrase to search for. we can change it to any desired keyword.

https://newsapi.org/v2/everything?q=apple&apiKey=*************

In the same way, we could also use a domain name, dates, sources in the link.

https://newsapi.org/v2/everything?domains=livemint.com,abc.com&apiKey=*****************

Selecting the sports category with the country India.

https://newsapi.org/v2/top-headlines?country=in&category=sports&apiKey=*****************

Let's write the program now.

import requests
mainurl = "http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=************************"

Now we need to get the data from mainurl in JSON format. And from there select articles.

openpage = requests.get(mainurl).json()
article = openpage['articles']

And looping over the article to find content.

for i in article:
    print(f""" author: {i['author']}
                title: {i['title']}
                description: {i['description']}
                url: {i['url']}
        """)

The complete code.

import requests

mainurl = "http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=*******************"

openpage = requests.get(mainurl).json()
article = openpage['articles']

for i in article:
    print(f """ author: {i['author']}
                   title: {i['title']}
                   description: {i['description']}
                   url: {i['url']}
        """)

We can print as many details as we want.

We can also build this complete project using the Python client library. Read here.

Keep learning!

Cover image by Suzy Hazelwood from Pexels