A Python Client for News API

Overview

newsapi-python

A Python client for the News API.

License PyPI Status Python

License

Provided under MIT License by Matt Lisivick.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

General

This is a Python client library for News API V2. The functions and methods for this library should mirror the endpoints specified by the News API documentation.

Installation

Installation for the package can be done via pip:

$ python -m pip install newsapi-python

Usage

After installation, import the client class into your project:

from newsapi import NewsApiClient

Initialize the client with your API key:

api = NewsApiClient(api_key='XXXXXXXXXXXXXXXXXXXXXXX')

Endpoints

An instance of NewsApiClient has three instance methods corresponding to three News API endpoints.

Top Headlines

Use .get_top_headlines() to pull from the /top-headlines endpoint:

api.get_top_headlines(sources='bbc-news')

Everything

Use .get_everything() to pull from the /everything endpoint:

api.get_everything(q='bitcoin')

Sources

Use .get_sources() to pull from the /sources endpoint:

api.get_sources()

For Windows users printing to cmd or powershell

You will encounter an error if you attempt to print the .json() object to the command line. This is because the '{', '}' curly braces to be printed to the console. This becomes especially annoying if developers wish to get 'under the hood'.

Here is the error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u2019' in position 1444: character maps to <undefined>

This can be fixed by: - installing 'win-unicode-console' py -mpip install win-unicode-console - then running it while calling your python script... py -mrun myPythonScript.py

Another option is hardcoding your console to only print in utf-8. This is a bad idea, as it could ruin many other scripts and/or make errors MUCH more difficult to track. More information.

Support

Feel free to make suggestions or provide feedback regarding the library. Thanks. Reach out at [email protected]

Issues
  • ImportError: cannot import name 'NewsApiClient'

    ImportError: cannot import name 'NewsApiClient'

    Unresolved reference 'NewsApiClient' when attempting to import the client

    opened by fcsimon 13
  • not working

    not working

    from newsapi import NewsApiClient newsapi = NewsApiClient(api_key='e6702efb133e48418f78ea26f4620e20') top_headlines = newsapi.get_top_headlines(q='bitcoin', sources='bbc-news,the-verge', category='business', language='en', country='us') getting error in python3.x ImportError: cannot import name 'NewsApiClient'

    opened by dangerrockstar 8
  • Error using from_parameter

    Error using from_parameter

    The code below errors out:

    try:
        newsapi = NewsApiClient(api_key='my key')
        everything = newsapi.get_everything(q='bitcoin',from_parameter='2018-08-01',sources='us',language='en',page_size=100)
    except Exception as e:
        print(e)
    

    This is what the exception prints:

    get_everything() got an unexpected keyword argument 'from_parameter'

    I'm using Python3.6 on Ubuntu 16.04.

    opened by asebold 7
  • ImportError: cannot import name 'NewsApiClient' from 'newsapi'

    ImportError: cannot import name 'NewsApiClient' from 'newsapi'

    I install with newsapi with pip command but it gives an Import error. what is the solution for this?? One more::I tried to install this newsapi with anaconda promp command::"conda install -c kvedala newsapi-python" also it gives and error.

    opened by sachin2404 6
  • Syntax Error

    Syntax Error

    Hello,

    just installed the package and got the following error:

      File "<stdin>", line 1, in <module>
      File "/anaconda3/envs/ff/lib/python3.6/site-packages/newsapi/__init__.py", line 1, in <module>
        from newsapi.newsapi_client import NewsApiClient
      File "/anaconda3/envs/ff/lib/python3.6/site-packages/newsapi/newsapi_client.py", line 12
        def get_top_headlines(self, q=None: str, sources=None: str, language='en': str, country=None: str, category=None: str, page_size=20: int,
                                          ^
    SyntaxError: invalid syntax
    

    I can see the change coming in from this PR.

    Do I need a specific version of something or am I missing something else?

    Thanks in advance.

    EDIT:

    Just tested it with version 0.2.3 and I can confirm that it's working. So presumably the whole thing blowed up 2 hours ago, when the version was bumped. 👼

    opened by vpolimenov 5
  • Category missing

    Category missing

    opened by Odianosen25 4
  • Adding new countries and languages that were missing

    Adding new countries and languages that were missing

    • New countries: ["pk", "es", "is", "se", "zh"]
    • New languages:["se", "zh"])
    opened by menarguez 4
  • add joins for all options that support multiple choices

    add joins for all options that support multiple choices

    Sending an iterable of sources, for example, sends sources=bbc-news,sources=fox-news, this PR does a join on everything that supports multiple entries for a parameter.

    Also adds debug level logging for what parameters are being sent to the API.

    opened by TomFaulkner 4
  • The base example get_top_headlines() doesn't work.

    The base example get_top_headlines() doesn't work.

    raise ValueError("cannot mix country/category param with sources param.")

    opened by clone95 4
  • Set default language as en

    Set default language as en

    Hey guys, I'm using the module to create a headline display, using some dot displays, thanks for your efforts on this code, I liked it a lot!

    Now regarding my suggestion, What about setting the default language to en, this way we can use newsapi.get_top_headlines() only, without any arguments. Currently if we do so it raises an exception.

    I can send a pull request to implement it if you want.

    enhancement 
    opened by gabrieldespindula 4
  • Library Partial Import Error

    Library Partial Import Error

    Describe the bug A clear and concise description of what the bug is.

    To Reproduce Steps to reproduce the behavior. For instance:

    1. conda activate venv
    2. pip install newsapi_python
    from newsapi import NewsApiClient
    # Init
    api = NewsApiClient(api_key='xxxxxxxxxxxx')
    # /v2/everything
    all_articles = api.get_everything(q='mars')
    print(all_articles)
    
    1. (venv) C:\Users\abc\anaconda3\envs\venv\bin>C:/Users/abc/anaconda3/envs/venv/python.exe

    Expected behavior News Data

    Screenshots

    d:/Projects/advisely/advisely/API/newsapi.py
    Traceback (most recent call last):
      File "d:/Projects/newsoftoday/API/newsapi.py", line 3, in <module>
        from newsapi import NewsApiClient
      File "d:\Projects\newsoftoday\API\newsapi.py", line 3, in <module>
        from newsapi import NewsApiClient
    ImportError: cannot import name 'NewsApiClient' from partially initialized module 'newsapi' (most likely due to a circular import) (d:\Projects\newsoftoday\API\newsapi.py)
    

    Desktop (please complete the following information):

    • OS: Windows 10
    • Visual Studio Code
    • Version [1.57.1]

    Additional context

    (venv) C:\Users\abc\anaconda3\envs\venv\bin>pip install newsapi_python   
    Collecting newsapi_python
      Using cached newsapi_python-0.2.6-py2.py3-none-any.whl (7.9 kB)
    Requirement already satisfied: requests<3.0.0 in c:\users\abc\anaconda3\envs\venv\lib\site-packages (from newsapi_python) (2.25.1)
    Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\abc\anaconda3\envs\venv\lib\site-packages (from requests<3.0.0->newsapi_python) (1.26.5)
    Requirement already satisfied: certifi>=2017.4.17 in c:\users\abc\anaconda3\envs\venv\lib\site-packages (from requests<3.0.0->newsapi_python) (2021.5.30)
    Requirement already satisfied: idna<3,>=2.5 in c:\users\abc\anaconda3\envs\venv\lib\site-packages (from requests<3.0.0->newsapi_python) (2.10)
    Requirement already satisfied: chardet<5,>=3.0.2 in c:\users\abc\anaconda3\envs\venv\lib\site-packages (from requests<3.0.0->newsapi_python) (4.0.0)
    Installing collected packages: newsapi-python
    Successfully installed newsapi-python-0.2.6
    
    opened by BlueSkyTrading 0
  • Bug report

    Bug report


    TypeError Traceback (most recent call last) in ----> 1 all_bitcoin_articles=newsapi.get_everything(q='bitcoin')

    TypeError: expected string or bytes-like object

    opened by gitjuanfmunoz 0
  • The comments of param 'page_size' and 'page' in ‘newsapi_client.py’ is wrong.

    The comments of param 'page_size' and 'page' in ‘newsapi_client.py’ is wrong.

    Should swap the comments order about page_size and page.

    opened by N-index 0
  • Not able to get sources for the specific countries

    Not able to get sources for the specific countries

    Describe the bug The issue is that I'm able to get sources for countries like: ae, at, be, bg, ch, cn, co, cu, ua, ru.

    To Reproduce from newsapi import NewsApiClient

    newsapi = NewsApiClient(api_key="api_key") print(newsapi.get_sources(country="ua"))

    {'status': 'ok', 'sources': []}

    Expected behavior Should be able to get all sources for all countries

    opened by omelnik 1
  • newsapi.newsapi_exception.NewsAPIException

    newsapi.newsapi_exception.NewsAPIException

    While trying to run the following code snippet , which is actually a part of documentation :

    all_articles = newsapi.get_everything(q='bitcoin',
                                          sources='bbc-news,the-verge',
                                          domains='bbc.co.uk,techcrunch.com',
                                          from_param='2017-12-01',
                                          to='2017-12-12',
                                          language='en',
                                          sort_by='relevancy',
                                          page=2)
    

    I am getting this error again and again :

    Traceback (most recent call last):
      File "news.py", line 16, in <module>
        page=2)
      File "C:\Python27\lib\site-packages\newsapi\newsapi_client.py", line 261, in get_everything
        raise NewsAPIException(r.json())
    newsapi.newsapi_exception.NewsAPIException
    
    

    Any suggestions on why this might be happening ?

    opened by reshu-b7 1
Owner
Matt Lisivick
Mobile Engineer | Docker Nerd | Full Stack Developer
Matt Lisivick
Unofficial Python wrapper for official Hacker News API

haxor Unofficial Python wrapper for official Hacker News API. Installation pip install haxor Usage Import and initialization: from hackernews import H

null 139 Nov 16, 2021
News API consisting various sources from Tanzania

Tanzania News API News API consisting various sources from Tanzania. Fork the project Clone the project git clone https://github.com/<username>/news-a

Innocent Zenda 5 Nov 15, 2021
wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3) for Python

wyscoutapi wyscoutapi is an extremely basic API client for the Wyscout API (v2 & v3). Usage Install with pip install wyscoutapi. To connect to the Wys

Ben Torvaney 4 Oct 3, 2021
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Harun Mbaabu Mwenda 45 Nov 18, 2021
A website application running in Google app engine, deliver rss news to your kindle. generate mobi using python, multilanguages supported.

Readme of english version refers to Readme_EN.md 简介 这是一个运行在Google App Engine(GAE)上的Kindle个人推送服务应用,生成排版精美的杂志模式mobi/epub格式自动每天推送至您的Kindle或其他邮箱。 此应用目前的主要

null 2.5k Nov 25, 2021
a discord bot coded in Python which shows news based on the term searched by the user

Noah Miller v1.0 a discord bot coded in Python which shows news based on the term searched by the user Add the bot to your server About This is a disc

klevr 3 Nov 8, 2021
An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD.

uticker An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD. Features include: Twi

Tansu Şenyurt 1 Nov 28, 2021
An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD.

uticker An information scroller Twitter trends, news, weather for raspberry pi and Pimoroni Unicorn Hat Mini and Scroll Phat HD. Features include: Twi

kottuora 1 Nov 30, 2021
Official Python client for the MonkeyLearn API. Build and consume machine learning models for language processing from your Python apps.

MonkeyLearn API for Python Official Python client for the MonkeyLearn API. Build and run machine learning models for language processing from your Pyt

MonkeyLearn 147 Nov 27, 2021
🖥️ Python - P1 Monitor API Asynchronous Python Client

??️ Asynchronous Python client for the P1 Monitor

Klaas Schoute 2 Nov 29, 2021
Python API Client for Close

Close API A convenient Python wrapper for the Close API. API docs: http://developer.close.com Support: [email protected] Installation pip install clos

Close 51 Jan 30, 2021
Python client for CoinPayments API

pyCoinPayments - Python API client for CoinPayments Updates This library has now been converted to work with python3 This is an unofficial client for

James 23 Oct 23, 2021
DEPRECATED - Official Python Client for the Discogs API

⚠️ DEPRECATED This repository is no longer maintained. You can still use a REST client like Requests or other third-party Python library to access the

Discogs 486 Nov 17, 2021
The Foursquare API client for Python

foursquare Python client for the foursquare API. Philosophy: Map foursquare's endpoints one-to-one Clean, simple, Pythonic calls Only handle raw data,

Mike Lewis 390 Nov 22, 2021
Python Client for Instagram API

This project is not actively maintained. Proceed at your own risk! python-instagram A Python 2/3 client for the Instagram REST and Search APIs Install

Facebook Archive 2.9k Nov 21, 2021
SmartFile API Client (Python).

A SmartFile Open Source project. Read more about how SmartFile uses and contributes to Open Source software. Summary This library includes two API cli

SmartFile 18 Jul 12, 2019
Python client for the Socrata Open Data API

sodapy sodapy is a python client for the Socrata Open Data API. Installation You can install with pip install sodapy. If you want to install from sour

Cristina 340 Nov 15, 2021
Python client for the Echo Nest API

Pyechonest Tap into The Echo Nest's Musical Brain for the best music search, information, recommendations and remix tools on the web. Pyechonest is an

The Echo Nest 648 Nov 28, 2021
A Python Tumblr API v2 Client

PyTumblr Installation Install via pip: $ pip install pytumblr Install from source: $ git clone https://github.com/tumblr/pytumblr.git $ cd pytumblr $

Tumblr 642 Nov 17, 2021