NewsAPI Python Client

0.2.7 · maintenance · verified Thu Apr 16

An unofficial Python client for the News API. It provides a simple, object-oriented interface to access the News API V2 endpoints (/top-headlines, /everything, and /sources) for programmatically retrieving live articles from news sources and blogs. The current version is 0.2.7.

Common errors

Warnings

Install

Imports

Quickstart

Initializes the NewsApiClient with your API key and demonstrates how to fetch top headlines, all articles matching a query, and available news sources.

import os
from newsapi import NewsApiClient

# Your API key from newsapi.org. Use environment variables for production.
api_key = os.environ.get('NEWSAPI_API_KEY', 'YOUR_API_KEY_HERE')

if api_key == 'YOUR_API_KEY_HERE':
    print("WARNING: Replace 'YOUR_API_KEY_HERE' with your actual NewsAPI key or set the NEWSAPI_API_KEY environment variable.")
    print("You can get a free API key at https://newsapi.org/")
    # Exit or handle this case appropriately in a real application
    exit()

newsapi = NewsApiClient(api_key=api_key)

# Get top headlines in the US
top_headlines = newsapi.get_top_headlines(q='bitcoin', language='en', country='us')
print(f"Top headlines: {len(top_headlines.get('articles', []))} articles")

# Get all articles about Tesla from BBC News
all_articles = newsapi.get_everything(q='tesla',
                                      sources='bbc-news,the-verge',
                                      language='en',
                                      sort_by='relevancy')
print(f"All articles: {len(all_articles.get('articles', []))} articles")

# Get available news sources
sources = newsapi.get_sources(category='technology', language='en', country='us')
print(f"Available sources: {len(sources.get('sources', []))} sources")

# Print a sample article title (if available)
if top_headlines.get('articles'):
    print(f"\nSample top headline: {top_headlines['articles'][0].get('title')}")

view raw JSON →