NewsAPI Python Client
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
-
ImportError: cannot import name 'NewsApiClient' from 'newsapi'
cause Attempting to import `NewsApiClient` from the top-level `newsapi` module, which is incorrect.fixThe correct import path is `from newsapi import NewsApiClient`. The package is `newsapi-python`, but the module name within the package is `newsapi` and the class is `NewsApiClient`. -
KeyError: 'articles'
cause The API response did not contain the 'articles' key, often indicating an underlying API error (e.g., invalid API key, no results for the query, or incorrect parameters) rather than a successful data retrieval.fixCheck the `status` and `code`/`message` fields in the returned JSON object before attempting to access `['articles']`. If `response['status'] == 'error'`, then `response['message']` will contain details. Ensure your API key is valid and parameters are correct. -
401 Unauthorized / {'status': 'error', 'code': 'apiKeyMissing', 'message': 'Your API key is missing...'} or {'status': 'error', 'code': 'apiKeyInvalid', 'message': 'Your API key hasn\'t been entered correctly...'}cause The API key provided is either missing, incorrect, expired, or disabled.fixDouble-check your API key for typos. Ensure it's active in your NewsAPI dashboard. Pass the key correctly during client initialization: `NewsApiClient(api_key='YOUR_API_KEY')`. For production, use environment variables.
Warnings
- gotcha The official News API documentation uses camelCase for parameters (e.g., 'pageSize'), while `newsapi-python` generally converts these to snake_case (e.g., 'page_size'). Always refer to the library's method signatures for correct parameter names.
- breaking The News API itself underwent a significant update from V1 to V2, changing endpoint URLs and parameter structures. `newsapi-python` primarily targets V2. If migrating from older custom implementations, be aware of these API-level changes.
- gotcha NewsAPI enforces usage limits (rate limits, daily request quotas) and may cap `totalResults` based on your subscription plan. Exceeding these limits will result in API errors (e.g., 429 Too Many Requests, apiKeyExhausted).
- gotcha When printing JSON responses to the Windows command prompt (cmd or PowerShell), you might encounter `UnicodeEncodeError`. This is due to default console encoding limitations.
Install
-
pip install newsapi-python
Imports
- NewsApiClient
import newsapi
from newsapi import NewsApiClient
Quickstart
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')}")