Fetching top news using news API in Python

The News API is a popular service for searching and fetching news articles from various websites. Using this API, you can retrieve top headlines from news sources like BBC, CNN, and others. To use the News API, you need to register for a free API key at newsapi.org.

Setting Up News API

First, install the required library and get your API key ?

pip install requests

Register at newsapi.org to get your free API key. Replace "your_api_key_here" with your actual key.

Fetching Top Headlines

Here's how to fetch top news headlines from BBC News ?

import requests

def fetch_top_news():
    # Replace with your actual API key
    api_key = "your_api_key_here"
    url = f"https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey={api_key}"
    
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raises an HTTPError for bad responses
        
        news_data = response.json()
        articles = news_data["articles"]
        
        print(f"Top {len(articles)} Headlines from BBC News:\n")
        
        for i, article in enumerate(articles, 1):
            print(f"{i}. {article['title']}")
            print(f"   Source: {article['source']['name']}")
            print(f"   Published: {article['publishedAt'][:10]}\n")
            
    except requests.exceptions.RequestException as e:
        print(f"Error fetching news: {e}")
    except KeyError as e:
        print(f"Error parsing response: {e}")

# Driver Code
if __name__ == '__main__':
    fetch_top_news()

Using Pandas for Better Data Handling

Converting the JSON response to a Pandas DataFrame makes data manipulation easier ?

import requests
import pandas as pd

def fetch_news_dataframe():
    api_key = "your_api_key_here"
    url = f"https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey={api_key}"
    
    try:
        response = requests.get(url)
        response.raise_for_status()
        
        news_data = response.json()
        articles = news_data["articles"]
        
        # Create DataFrame from articles
        df = pd.DataFrame(articles)
        
        # Select relevant columns
        news_df = df[['title', 'author', 'publishedAt', 'url']].copy()
        news_df['publishedAt'] = pd.to_datetime(news_df['publishedAt'])
        
        print("Top News Headlines:")
        print(news_df[['title', 'author', 'publishedAt']])
        
        return news_df
        
    except Exception as e:
        print(f"Error: {e}")
        return None

# Usage
if __name__ == '__main__':
    news_dataframe = fetch_news_dataframe()

Fetching News from Multiple Sources

You can also fetch news from multiple sources at once ?

import requests

def fetch_multiple_sources():
    api_key = "your_api_key_here"
    sources = "bbc-news,cnn,reuters"  # Multiple sources
    url = f"https://newsapi.org/v2/top-headlines?sources={sources}&apiKey={api_key}"
    
    try:
        response = requests.get(url)
        news_data = response.json()
        
        for i, article in enumerate(news_data["articles"][:10], 1):
            print(f"{i}. {article['title']}")
            print(f"   Source: {article['source']['name']}\n")
            
    except Exception as e:
        print(f"Error: {e}")

# Usage
fetch_multiple_sources()

Key Features

Feature Description Usage
Top Headlines Latest breaking news /v2/top-headlines
Search Articles Search by keywords /v2/everything
Sources Available news sources /v2/sources

Conclusion

The News API provides a simple way to fetch current news headlines programmatically. Use Pandas DataFrames for better data manipulation and analysis. Remember to handle API errors gracefully and respect rate limits.

Updated on: 2026-03-25T05:01:43+05:30

784 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements