{"id":9137,"library":"newsapi-python","title":"NewsAPI Python Client","description":"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.","status":"maintenance","version":"0.2.7","language":"en","source_language":"en","source_url":"https://github.com/mattlisiv/newsapi-python","tags":["news","api","client","headlines","media"],"install":[{"cmd":"pip install newsapi-python","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Used internally for making HTTP requests to the News API.","package":"requests","optional":false}],"imports":[{"note":"The primary client class is `NewsApiClient`, not the top-level `newsapi` module itself.","wrong":"import newsapi","symbol":"NewsApiClient","correct":"from newsapi import NewsApiClient"}],"quickstart":{"code":"import os\nfrom newsapi import NewsApiClient\n\n# Your API key from newsapi.org. Use environment variables for production.\napi_key = os.environ.get('NEWSAPI_API_KEY', 'YOUR_API_KEY_HERE')\n\nif api_key == 'YOUR_API_KEY_HERE':\n    print(\"WARNING: Replace 'YOUR_API_KEY_HERE' with your actual NewsAPI key or set the NEWSAPI_API_KEY environment variable.\")\n    print(\"You can get a free API key at https://newsapi.org/\")\n    # Exit or handle this case appropriately in a real application\n    exit()\n\nnewsapi = NewsApiClient(api_key=api_key)\n\n# Get top headlines in the US\ntop_headlines = newsapi.get_top_headlines(q='bitcoin', language='en', country='us')\nprint(f\"Top headlines: {len(top_headlines.get('articles', []))} articles\")\n\n# Get all articles about Tesla from BBC News\nall_articles = newsapi.get_everything(q='tesla',\n                                      sources='bbc-news,the-verge',\n                                      language='en',\n                                      sort_by='relevancy')\nprint(f\"All articles: {len(all_articles.get('articles', []))} articles\")\n\n# Get available news sources\nsources = newsapi.get_sources(category='technology', language='en', country='us')\nprint(f\"Available sources: {len(sources.get('sources', []))} sources\")\n\n# Print a sample article title (if available)\nif top_headlines.get('articles'):\n    print(f\"\\nSample top headline: {top_headlines['articles'][0].get('title')}\")","lang":"python","description":"Initializes the NewsApiClient with your API key and demonstrates how to fetch top headlines, all articles matching a query, and available news sources."},"warnings":[{"fix":"Consult the `newsapi-python` documentation or method signatures (e.g., `get_everything(page_size=...)`) for the correct parameter naming conventions.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"breaking","affected_versions":"Prior to News API V2 (newsapi-python is V2-compatible)"},{"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.","message":"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).","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"When printing JSON responses to the Windows command prompt (cmd or PowerShell), you might encounter `UnicodeEncodeError`. This is due to default console encoding limitations.","severity":"gotcha","affected_versions":"All versions on Windows"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"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`.","cause":"Attempting to import `NewsApiClient` from the top-level `newsapi` module, which is incorrect.","error":"ImportError: cannot import name 'NewsApiClient' from 'newsapi'"},{"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.","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.","error":"KeyError: 'articles'"},{"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.","cause":"The API key provided is either missing, incorrect, expired, or disabled.","error":"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...'}"}]}