Skip to content

Repository files navigation

Newsdata.io logo

Newsdata.io Node.js Client

npm versionnpm downloadsCINodeLicenseOpenAPI

Official Node.js client for the Newsdata.io News API. It wraps every endpoint (latest, archive, sources, crypto, market, count, crypto/count, market/count) with client-side parameter validation, automatic retries with exponential backoff, scroll/paginate helpers, and a typed error hierarchy.

Zero runtime dependencies — uses the built-in fetch (Node 18+).

Installation

npm install newsdata-nodejs-client

Quickstart

import{NewsDataApiClient,NewsdataError}from'newsdata-nodejs-client';constclient=newNewsDataApiClient(process.env.NEWSDATA_API_KEY);try{constres=awaitclient.latestApi({q: 'bitcoin',country: ['us','gb'],// string or array of stringslanguage: 'en',});for(constarticleofres.results){console.log(article.title,'-',article.link);}}catch(err){if(errinstanceofNewsdataError)console.error(err.message);}

CommonJS:

const{ NewsDataApiClient }=awaitimport('newsdata-nodejs-client');

Endpoints

MethodEndpointNotes
latestApi(params)/1/latestReal-time news
archiveApi(params)/1/archiveHistorical news
sourcesApi(params)/1/sourcesAvailable sources (single page)
cryptoApi(params)/1/cryptoCryptocurrency news
marketApi(params)/1/marketMarket / financial news
countApi(params)/1/countAggregate counts (requires from_date, to_date)
cryptoCountApi(params)/1/crypto/countAggregate crypto counts (requires dates)
marketCountApi(params)/1/market/countAggregate market counts (requires dates)

Each params value may be a single value or an array (arrays are sent comma-separated). Parameter names are case-insensitive. See the Newsdata.io documentation — or the OpenAPI 3.1 spec — for the full parameter reference per endpoint.

Pagination

Endpoint methods return a Promise by default. Two opt-in modes:

// scroll: follow nextPage cursors, resolve to one merged response.constmerged=awaitclient.latestApi({q: 'news',scroll: true,maxResult: 200});// paginate: async generator, one response per page.forawait(constpageofclient.latestApi({q: 'news',paginate: true,maxPages: 5})){process(page.results);}

scroll and paginate are mutually exclusive. With paginate: true the method returns an AsyncGenerator; otherwise it returns a Promise.

Raw query

awaitclient.latestApi({rawQuery: 'q=bitcoin&country=us&language=en'});

rawQuery is mutually exclusive with all other parameters and is validated against the endpoint's allowed keys.

Client-side validation

Before any request is sent, parameters are validated and normalized. A NewsdataValidationError is thrown (without spending API quota) when:

  • a parameter is not accepted by that endpoint;
  • mutually-exclusive parameters are set together — q/qInTitle/qInMeta, country/excludecountry, category/excludecategory, language/excludelanguage, domain/domainurl/excludedomain;
  • size is outside 1–50;
  • sentiment_score is set without sentiment;
  • a count endpoint is missing from_date or to_date.

Booleans (full_content, image, video, removeduplicate) are coerced to 1 / 0.

Error handling

import{NewsdataValidationError,NewsdataAuthError,NewsdataRateLimitError,NewsdataApiError,NewsdataNetworkError,}from'newsdata-nodejs-client';try{awaitclient.latestApi({q: 'news'});}catch(err){if(errinstanceofNewsdataValidationError){/* err.param */}elseif(errinstanceofNewsdataAuthError){/* 401 / 403 */}elseif(errinstanceofNewsdataRateLimitError){/* err.retryAfter */}elseif(errinstanceofNewsdataApiError){/* err.statusCode, err.responseBody */}elseif(errinstanceofNewsdataNetworkError){/* err.cause */}}

Hierarchy:

NewsdataError (catch-all base)
├── NewsdataValidationError (.param)
├── NewsdataApiError (.statusCode, .responseBody)
│ ├── NewsdataAuthError (401 / 403)
│ ├── NewsdataRateLimitError (429; .retryAfter)
│ └── NewsdataServerError (5xx)
└── NewsdataNetworkError (.cause)

Configuration

constclient=newNewsDataApiClient(apiKey,{timeout: 30_000,// per-request, msmaxRetries: 5,// total attempts (1 = no retry)retryBackoff: 2_000,// base backoff, ms (exponential)retryBackoffMax: 60_000,// cap on a single backoff, mspaginationDelay: 1_000,// delay between pages, msmaxResult: null,// default cap for scroll modemaxPages: null,// default cap for paginate modeincludeHeaders: false,// attach responseHeaders to resultsbaseUrl: undefined,// override for staging/proxyfetch: undefined,// inject a custom fetchlogger: console,// optional { debug, info, warn }; API key is redacted});

Retries cover network errors, HTTP 429, and 5xx. 429 honors the Retry-After header (integer seconds or HTTP-date); otherwise backoff is exponential. Auth and other 4xx errors are never retried.

Development

npm test# node --test, runs offline (no API key required)

Related libraries

Official Newsdata.io clients across languages and runtimes:

Also see free news datasets for ML / NLP work.

License

MIT

About

Official Node.js client (SDK) for the Newsdata.io News API — fetch real-time, historical, crypto, and stock-market news via REST with validation, retries, pagination, and typed errors

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages