Featured

Python To read the news

Hello Guys, in this blog we will use Python to read the news. Before this, the concepts of APIs, JSON, Python Libraries should be clear.


We are going to use 'newsdataapi' library of Python. The newsdataapi is the official Python client library for the Newsdata.io API. Its primary purpose is to simplify the process of accessing global news data directly from Newsdata.io, allowing developers to integrate news content into their applications without having to manually construct HTTP requests. It acts as a wrapper around the API, handling the complexities of authentication, request parameters, and response parsing.

So Lets Start.

Making Python to read the online news

Step 1: Get your API key

  1. Sign Up : Go to the Newsdata.io website and create a free account. The free plan typically offers a limited number of credits per day (e.g., 200 credits).
  2. Get the Key: Once you've created and verified your account, your unique API key will be available on your dashboard. Copy this key, as you will need it for every API call.
Step 2: Install the Python Client Library

Newsdata.io has its own official Python client library, which is the easiest way to interact with their API. Open your terminal or command prompt and run the following command to install it:

pip install newsdataapi

Step 3: Write your Python Script

Using the client library, you can make API calls in just a few lines of code. The library handles the request, the API key, and the JSON response for you.

Python Script
    
from newsdataapi import NewsDataApiClient

# Initialize the client with your API key
api = NewsDataApiClient(apikey="YOUR_API_KEY")

# Make a request to the 'latest_api' endpoint with a keyword query
response = api.news_api(q="Nepal", language="en")

# Print the received data
print(response)

# Example of how to iterate through the articles
if "results" in response:
    for article in response["results"]:
        print(f"Title: {article['title']}")
        print(f"Link: {article['link']}")
        print("-" * 20)
        

In this script:

  • You initialize the NewsDataApiClient with your unique API key.

  • You call the news_api() method, which corresponds to one of their API endpoints. You can pass various parameters, such as q (for a search query) or language.

  • The API returns a JSON object, which you can then access like a Python dictionary to get the article data.

We can further develop more to like GUI version of it by using tkinter, kivy , request etc. We can also use this in our web development project of flask, django python.

Comments

Popular Posts