newsapi-python

repository·master·Indexed 19 days ago

https://github.com/mattlisiv/newsapi-python

A Python client library for the News API V2. It provides the NewsApiClient class to programmatically access news headlines via .get_top_headlines(), search articles using .get_everything(), and list news sources with .get_sources(). The library includes the newsapi.const module for valid API parameters and handles API errors through NewsAPIException.

Tokens
2K
Snippets
14
Records
14
Agent score
68%

What's inside newsapi-python

  1. Constrain results by date in get_everything

    master

    The get_everything method accepts from_param and to parameters to filter articles by publication date. You can provide these values in several formats:

    • datetime.date objects
    • datetime.datetime objects (assumed to be in UTC)
    • str formatted as %Y-%m-%d (e.g., 2019-09-07) or %Y-%m-%dT%H:%M:%S (e.g., 2019-09-07T13:04:15)
    • int or float (representing a Unix timestamp)
    • None (the default, which applies no constraint)
    import datetime as dt
    
    # Using datetime.date
    api.get_everything(
        q="hurricane",
        from_param=dt.date(2019, 9, 1),
        to=dt.date(2019, 9, 3),
    )
    
    # Using datetime.datetime
    api.get_everything(
        q="hurricane",
        from_param=dt.datetime(2019, 9, 1, hour=5),
        to=dt.datetime(2019, 9, 1, hour=15),
    )
    
    # Using ISO strings
    api.get_everything(
        q="hurricane",
        from_param="2019-08-01",
        to="2019-09-15",
    )
    
    # Using full ISO datetime strings
    api.get_everything(
        q="venezuela",
        from_param="2019-08-01T10:30:00",
        to="2019-09-15T14:00:00",
    )
  2. Initialize the NewsApiClient

    master

    To use the News API, initialize the NewsApiClient class with your API key. The api_key is the only required parameter. You can also optionally provide a persistent requests.Session object to enable connection pooling.

    import os
    from newsapi import NewsApiClient
    
    # An API key; for example: "74f9e72a4bfd4dbaa0cbac8e9a17d34a"
    key = os.environ["news_api_secret"]
    
    api = NewsApiClient(api_key=key)
  3. Use a dedicated session for multiple requests

    master

    By default, NewsApiClient creates a new TCP session for every method call. To improve performance via connection pooling and cookie persistence, pass a requests.Session object to the NewsApiClient constructor. Using a with context manager ensures the session and TCP connection are closed after use.

    import requests
    
    with requests.Session() as session:
        # Use a single session for multiple requests.
        api = NewsApiClient(api_key=key, session=session)
        data1 = api.get_top_headlines(category="technology")
        data2 = api.get_everything(q="facebook", domains="mashable.com,wired.com")
  4. Fix UnicodeEncodeError on Windows cmd or PowerShell

    master

    If you encounter a UnicodeEncodeError when printing JSON objects to the Windows command line or PowerShell (often due to characters like \u2019), you can resolve it by installing win-unicode-console and running your script through it.

    Steps:

    1. Install the package: py -mpip install win-unicode-console
    2. Run your script: py -mrun myPythonScript.py
    py -mpip install win-unicode-console
    py -mrun myPythonScript.py
  5. Access the /everything endpoint

    master

    Use the get_everything method to search through a large volume of articles. Common parameters include a search query (q), sort_by (e.g., 'relevancy'), language, and date constraints using from_param and to.

    api.get_everything("hurricane OR tornado", sort_by="relevancy", language="en")
    api.get_everything("(hurricane OR tornado) AND FEMA", sort_by="relevancy")
  6. Access the /top-headlines endpoint

    master

    Use the get_top_headlines method to retrieve current top news stories. You can filter results by query (q), category, sources, and page_size.

    api.get_top_headlines()
    api.get_top_headlines(q="hurricane")
    api.get_top_headlines(category="sports")
    api.get_top_headlines(sources="abc-news,ars-technica", page_size=50)
  7. Use the NewsApiClient class

    master

    The newsapi.NewsApiClient is the primary entry point for interacting with the News API. It provides methods to access various endpoints such as top headlines, everything, and other news-related data. You typically instantiate this client with your API key to begin making requests.

    from newsapi import NewsApiClient
    
    # Initialize the client
    newsapi = NewsApiClient(api_key='YOUR_API_KEY')
  8. Access the /sources endpoint

    master

    Use the get_sources method to retrieve a list of news sources. You can filter sources by category, country, and language.

    api.get_sources()
    api.get_sources(category="technology")
    api.get_sources(country="ru")
    api.get_sources(category="health", country="us")
    api.get_sources(language="en", country="in")