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]

Comments
  • 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
  • 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
  • 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
  • Update pythonpackage.yml

    Update pythonpackage.yml

    • Add Githhub actions
    • Temporarily comment out flake8 until PR

    GitHub action workflow syntax:

    https://help.github.com/en/articles/workflow-syntax-for-github-actions

    opened by mattlisiv 3
  • Added Python 2 unicode support

    Added Python 2 unicode support

    As per #23, this adds support for unicode query strings in Python 2.x.

    Similar support would be easy for other parameters (source, country, etc.) if necessary. That may necessitate making a helper function for the conversion, though, since it'd be a fair bit of code.

    Tested on Python 2.7.16

    opened by AetherBreeze 3
  • Wrong example for python

    Wrong example for python

    I follow this document https://newsapi.org/docs/client-libraries/python and test python api.

    Seems like the follow code will get error I paste. sources = newsapi.get_sources()

    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "crawler.py", line 93, in <module>
        crawler.crawl()
      File "crawler.py", line 84, in crawl
        sources = newsapi.get_sources()
      File "/Users/mabodx/anaconda/lib/python3.6/site-packages/newsapi/newsapi_client.py", line 311,
     in get_sources
        r = requests.get(const.SOURCES_URL, auth=self.auth, timeout=30, params=payload)
      File "/Users/mabodx/anaconda/lib/python3.6/site-packages/requests/api.py", line 72, in get
        return request('get', url, params=params, **kwargs)
      File "/Users/mabodx/anaconda/lib/python3.6/site-packages/requests/api.py", line 58, in request
        return session.request(method=method, url=url, **kwargs)
      File "/Users/mabodx/anaconda/lib/python3.6/site-packages/requests/sessions.py", line 513, in r
    equest
        resp = self.send(prep, **send_kwargs)
      File "/Users/mabodx/anaconda/lib/python3.6/site-packages/requests/sessions.py", line 623, in s
    end
        r = adapter.send(request, **kwargs)
      File "/Users/mabodx/anaconda/lib/python3.6/site-packages/requests/adapters.py", line 514, in s
    end
        raise SSLError(e, request=request)
    requests.exceptions.SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
    
    opened by mabodx 3
  • TypeError: super(type, obj): obj must be an instance or subtype of type

    TypeError: super(type, obj): obj must be an instance or subtype of type

    When I run: api.get_everything(q='bitcoin')

    I get api.get_everything(q='bitcoin') Traceback (most recent call last):

    File "", line 1, in api.get_everything(q='bitcoin')

    File "C:\Users\LapLap\Anaconda3\envs\fluffy\lib\site-packages\newsapi\newsapi_client.py", line 248, in get_everything r = requests.get(const.EVERYTHING_URL, auth=self.auth, timeout=30, params=payload)

    File "C:\Users\LapLap\Anaconda3\envs\fluffy\lib\site-packages\requests\api.py", line 72, in get return request('get', url, params=params, **kwargs)

    File "C:\Users\LapLap\Anaconda3\envs\fluffy\lib\site-packages\requests\api.py", line 57, in request with sessions.Session() as session:

    File "C:\Users\LapLap\Anaconda3\envs\fluffy\lib\site-packages\requests\sessions.py", line 386, in init self.mount('https://', HTTPAdapter())

    File "C:\Users\LapLap\Anaconda3\envs\fluffy\lib\site-packages\requests\adapters.py", line 120, in init super(HTTPAdapter, self).init()

    TypeError: super(type, obj): obj must be an instance or subtype of type

    opened by ghaith99 3
  • Correct Error Message and Add Unit Tests

    Correct Error Message and Add Unit Tests

    I understand the pytest module has been added, and you expect tests to be written using it but I just couldn't get it to work.

    I don't know what the issue is, but I noticed that I can't pass a decorated '@pytest.fixture' function as a parameter into another function.

    ie

    @pytest.fixture def foo(): return Object()

    def test_bar(foo): foo.do_something()

    opened by TobiAlbert 3
  • I already imported newsapi and i got sucessfully package installed but i am getting no module error for NewsApiClient

    I already imported newsapi and i got sucessfully package installed but i am getting no module error for NewsApiClient

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

    To Reproduce Steps to reproduce the behavior. For instance:

    1. Go to '...'
    2. Click on '....'
    3. Scroll down to '....'
    4. See error

    Expected behavior A clear and concise description of what you expected to happen.

    Screenshots If applicable, add screenshots to help explain your problem.

    Desktop (please complete the following information):

    • OS: [e.g. iOS]
    • Browser [e.g. chrome, safari]
    • Version [e.g. 22]

    Additional context Add any other context about the problem here.

    opened by keerthanatammina 1
  • Add search_in parameters

    Add search_in parameters

    Is your feature request related to a problem? Please describe. Please consider adding the search_in parameter.

    Describe the solution you'd like I would like to use the search_in parameter for niche lookups.

    Describe alternatives you've considered I could just filter myself after I get the results

    opened by wernerkotze 0
  • 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 1
  • 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
  • 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 2
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 147 Sep 18, 2022
NewpaperNews-API - Json data of the news with python

NewsAPI API Documentation BASE_URL = "https://saurav.tech/NewsAPI/" top_headline

Aryaman Prakash 2 Sep 23, 2022
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 6 Oct 6, 2022
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 11 Nov 22, 2022
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 46 Sep 1, 2022
Python API Client for Twitter API v2

?? Python Client For Twitter API v2 ?? Why Twitter Stream ? Twitter-Stream.py a python API client for Twitter API v2 now supports FilteredStream, Samp

Twitivity 31 Nov 19, 2022
Dns-Client-Server - Dns Client Server For Python

Dns-client-server DNS Server: supporting all types of queries and replies. Shoul

Nishant Badgujar 1 Feb 15, 2022
Raphtory-client - The python client for the Raphtory project

Raphtory Client This is the python client for the Raphtory project Install via p

Raphtory 5 Apr 28, 2022
Drcom-pt-client - Drcom Pt version client with refresh timer

drcom-pt-client Drcom Pt version client with refresh timer Dr.com Pt版本客户端 可用于网页认

null 4 Nov 16, 2022
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.6k Jan 6, 2023
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
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 157 Nov 22, 2022
🖥️ Python - P1 Monitor API Asynchronous Python Client

??️ Asynchronous Python client for the P1 Monitor

Klaas Schoute 9 Dec 12, 2022
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 5 Oct 31, 2022
A module to get data about anime characters, news, info, lyrics and more.

Animec A module to get data about anime characters, news, info, lyrics and more. The module scrapes myanimelist to parse requested data. If you wish t

DriftAsimov 31 Aug 31, 2022
The Sue Gray Alert System was a 5 minute project that just beeps every time a new article is updated or published on Gov.UK's news pages.

The Sue Gray Alert System was a 5 minute project that just beeps every time a new article is updated or published on Gov.UK's news pages.

Dafydd 1 Jan 31, 2022
This bot plays the most recent video from the Daily Silksong News Youtube Channel whenever a specific user enters voice chat once a day.

Do you have that one friend that really likes Hollow Knight. Are they waiting for Silksong to come out? Heckle them with this Discord bot.

Tommy Rousey 2 Feb 9, 2022
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 56 Nov 30, 2022