newsapi Node.js Interface

repository·master·Indexed 41 days ago

https://github.com/bzarras/newsapi

A Node.js interface for the NewsAPI.org service, version 2.4.1. It provides access to top headlines, all articles, and news sources from over 70 news sites in JSON format. The library supports the v2 API and legacy v1 API, offering both Promise and callback-based methods. Features include CORS proxy support via the NewsAPI constructor and the ability to bypass caching using the noCache option.

Tokens
2.3K
Snippets
10
Records
10
Agent score
1%

What's inside newsapi

  1. Resolve CORS issues with a proxy

    master

    The library includes default headers to resolve most CORS issues. If you still encounter CORS problems, you can provide a corsProxyUrl in the NewsAPI constructor to route requests through a proxy (e.g., https://cors-anywhere.herokuapp.com/).

    const newsapi = new NewsAPI('YOUR_API_KEY', { corsProxyUrl: 'https://cors-anywhere.herokuapp.com/' });
  2. Use the v1 legacy API

    master

    The legacy v1 API provides articles() and sources() methods. These methods support both Promises and traditional Node-style callbacks.

    articles(options)

    Requires a source parameter.

    sources(options)

    All options are optional.

    const NewsAPI = require('newsapi');
    const newsapi = new NewsAPI('YOUR_API_KEY');
    
    // Query articles using Promises
    newsapi.articles({
      source: 'associated-press',
      sortBy: 'top'
    }).then(articlesResponse => {
      console.log(articlesResponse);
    });
    
    // Query articles using Node-style callbacks
    newsapi.articles({
      source: 'associated-press',
      sortBy: 'top'
    }, (err, articlesResponse) => {
      if (err) console.error(err);
      else console.log(articlesResponse);
    });
    
    // Query sources
    newsapi.sources({
      category: 'technology',
      language: 'en',
      country: 'us'
    }).then(sourcesResponse => {
      console.log(sourcesResponse);
    });
  3. Disable caching on a request

    master

    To bypass NewsAPI's default caching behavior for a specific request, pass { noCache: true } as a second argument to the method call.

    newsapi.v2.everything({
      sources: 'bbc-news'
    }, {
      noCache: true
    }).then(response => {
      ...
    });
  4. Use the NewsAPI v2 API

    master

    The v2 API provides access to top headlines, everything (all articles), and sources. All methods support Promises and Node-style callbacks. The options passed to these methods are passed directly as querystring parameters to the NewsAPI.org REST API.

    v2.topHeadlines(options)

    Queries top headlines. All options are optional, but you must include at least one parameter (e.g., q, category, language, or country).

    v2.everything(options)

    Queries all articles. You must include at least one of q, sources, or domains.

    v2.sources(options)

    Queries available news sources. All options are optional.

    const NewsAPI = require('newsapi');
    const newsapi = new NewsAPI('YOUR_API_KEY');
    
    // Query top headlines
    newsapi.v2.topHeadlines({
      q: 'trump',
      category: 'politics',
      language: 'en',
      country: 'us'
    }).then(response => {
      console.log(response);
      /*
        {
          status: "ok",
          articles: [...]
        }
      */
    });
    
    // Query everything
    newsapi.v2.everything({
      q: 'trump',
      sources: 'bbc-news,the-verge',
      domains: 'bbc.co.uk,techcrunch.com',
      from: '2017-12-01',
      to: '2017-12-12',
      language: 'en',
      sortBy: 'relevancy',
      page: 2
    }).then(response => {
      console.log(response);
    });
    
    // Query sources
    newsapi.v2.sources({
      category: 'technology',
      language: 'en',
      country: 'us'
    }).then(response => {
      console.log(response);
    });
  5. Configure request options

    master

    When calling API methods, you can pass an options object to control request behavior.

    Option Keys:

    • noCache (boolean): If true, sets the X-No-Cache: true header to bypass caching.
    • showHeaders (boolean): If true, the response will be returned as an object containing both the response headers and the body (e.g., { headers, body }).
    // Example: Fetching without cache and inspecting headers
    newsapi.v2.everything(
      { q: 'openai' }, 
      { noCache: true, showHeaders: true }
    ).then(response => {
      console.log('Headers:', response.headers);
      console.log('Data:', response.body);
    });
  6. Use NewsAPI v2 endpoints

    master

    The v2 property on the NewsAPI instance provides access to the latest version of the News API. Methods in v2 support both Promises and callbacks.

    Available Methods:

    • topHeadlines(params, options, cb): Fetches top headlines. params defaults to { language: 'en' }.
    • everything(params, options, cb): Fetches news articles based on specific parameters.
    • sources(params, options, cb): Fetches available news sources.

    Arguments:

    • params (Object): Query parameters for the endpoint.
    • options (Object): Configuration for the request (see Request Options).
    • cb (Function): Optional callback function (err, data) => {}.
    // Using Promises
    newsapi.v2.topHeadlines({ country: 'us' })
      .then(data => console.log(data))
      .catch(err => console.error(err));
    
    // Using Callbacks
    newsapi.v2.everything({ q: 'technology' }, {}, (err, data) => {
      if (err) return console.error(err);
      console.log(data);
    });
  7. Use NewsAPI v1 legacy endpoints

    master

    The NewsAPI instance provides direct access to legacy v1 endpoints. Note that v1 endpoints do not use the v2 namespace.

    Available Methods:

    • sources(params, options, cb): Fetches sources (v1).
    • articles(params, options, cb): Fetches articles (v1).

    Arguments:

    • params (Object): Query parameters.
    • options (Object): Configuration for the request.
    • cb (Function): Optional callback function.
    // Fetching v1 articles
    newsapi.articles({ q: 'bitcoin' }, {}, (err, data) => {
      if (err) console.error(err);
      else console.log(data);
    });
  8. Initialize the NewsAPI client

    master

    To use the library, instantiate the NewsAPI class with your API key. You can optionally provide a corsProxyUrl in the options object to handle CORS issues in certain environments.

    Constructor Signature: new NewsAPI(apiKey, options = {})

    Options:

    • corsProxyUrl (string): A URL to prefix to the NewsAPI host (e.g., for a CORS proxy).
    const NewsAPI = require('newsapi');
    
    // Basic initialization
    const newsapi = new NewsAPI('YOUR_API_KEY');
    
    // Initialization with a CORS proxy
    const newsapiWithProxy = new NewsAPI('YOUR_API_KEY', { 
      corsProxyUrl: 'https://your-proxy.com/' 
    });
  9. Handle NewsAPIError

    master

    The library throws a NewsAPIError when the News API returns an error status in the response body. This error object wraps the error details provided by the API.

    Properties:

    • name: Formatted as NewsAPIError: [error_code].
    • message: The error message returned by the API.
    try {
      await newsapi.v2.topHeadlines({ invalid: 'param' });
    } catch (err) {
      if (err.name.startsWith('NewsAPIError')) {
        console.error('API Error:', err.message);
      } else {
        console.error('Network/Other Error:', err);
      }
    }