Registry / http-networking / newsapi-python

newsapi-python

JSON →
library0.2.7pypypi✓ verified 84d ago

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.

pip install newsapi-python
INSTALL
IMPORT
SIG · NEWSAPI-PYTHON
N
newsapi-python
http-networkingpythonv0.2.7
Install
2.1s avg
Import
580ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.2.7 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.615s · 21.3MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 2.1s · import 0.545s · 22MB
19MB installed
● package 19MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

NewsApiClient
from newsapi import NewsApiClient
import newsapi
The primary client class is `NewsApiClient`, not the top-level `newsapi` module itself.

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')}")
Debug
Known issues
gotchaThe 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.
fix
Consult the `newsapi-python` documentation or method signatures (e.g., `get_everything(page_size=...)`) for the correct parameter naming conventions.
affects: All versions
breakingThe 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.
fix
Ensure your News API key is for V2. The library `newsapi-python` uses V2 endpoints. Refer to the official News API v2 migration guide if you were previously using V1.
affects: Prior to News API V2 (newsapi-python is V2-compatible)
gotchaNewsAPI 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).
fix
Monitor your usage via the NewsAPI dashboard. Implement retry logic with exponential backoff for rate-limited errors. Consider upgrading your plan for higher limits if needed.
affects: All versions
gotchaWhen printing JSON responses to the Windows command prompt (cmd or PowerShell), you might encounter `UnicodeEncodeError`. This is due to default console encoding limitations.
fix
Install `win-unicode-console` (`pip install win-unicode-console`) and run your script using `py -mrun myPythonScript.py`. Alternatively, explicitly encode output to 'utf-8' if possible.
affects: All versions on Windows
Errors
Common errors & fixes
ImportError: cannot import name 'NewsApiClient' from 'newsapi'
Attempting to import `NewsApiClient` from the top-level `newsapi` module, which is incorrect.
fix
The 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'
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.
fix
Check 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...'}
The API key provided is either missing, incorrect, expired, or disabled.
fix
Double-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.
Upgrade
Version history
0.2.7latest on PyPI · released Mar 2, 2023
Audit
Dependencies
requestsrequiredUsed internally for making HTTP requests to the News API.
Agent activity
2 hits · last 30 days
node
2
Resources