newsdataio / newsdataapi
Official PHP client (SDK) for the Newsdata.io News API — fetch real-time, historical, crypto, and stock-market news via REST with validation, retries, and error handling.
Requires
- php: ^7.3 || ^8.0
- ext-curl: *
- ext-json: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.50
- phpstan/phpstan: ^1.10 || ^2.0
- phpunit/phpunit: ^9 || ^10
Suggests
- phrity/websocket: Required for real-time streaming via NewsdataWebSocket::stream(): version ^4.1 (PHP 8.1+), the range this SDK is tested with
- psr/log: Allows attaching a PSR-3 logger via NewsdataApi::setLogger()
Provides
None
Conflicts
None
Replaces
None
README
Newsdata.io PHP Client
The official PHP client for the Newsdata.io REST 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, and a typed exception hierarchy. It
also covers the real-time WebSocket service: register, list, and delete queries,
and stream the matching news as it is published.
Requirements
PHP 7.3+ with the curl and json extensions.
Installation
With Composer:
composer require newsdataio/newsdataapi
Without Composer, include the bundled autoloader:
require_once '/path/to/php-client/autoload.php';
Quickstart
use NewsdataIO\NewsdataApi; use NewsdataIO\Exception\NewsdataException; $client = new NewsdataApi(NEWSDATA_API_KEY); try { $response = $client->get_latest_news([ 'q' => 'bitcoin', 'country' => ['us', 'gb'], // string or array of strings 'language' => 'en', ]); foreach ($response->results as $article) { echo $article->title, PHP_EOL; } } catch (NewsdataException $e) { echo 'Request failed: ', $e->getMessage(), PHP_EOL; }
Pass ['language' => ['en', 'fr']] and the array is sent comma-separated.
By default the response is decoded to objects; call
$client->setDecodeJsonAsArray(true) to get associative arrays instead.
Endpoints
The API has two versions. v2 is the current one; the v1 methods keep working unchanged.
v2
| Method | Endpoint | Notes |
|---|---|---|
get_news($data) |
/2/news |
Latest news, or historical with from_date / to_date |
get_market($data) |
/2/market |
Market / financial news |
get_crypto($data) |
/2/crypto |
Cryptocurrency news |
get_sources($data) |
/2/sources |
Available sources |
get_count_news($data) |
/2/count/news |
Aggregate news counts |
get_count_market($data) |
/2/count/market |
Aggregate market counts |
get_count_crypto($data) |
/2/count/crypto |
Aggregate crypto counts |
get_websocket_register($data) |
/2/websocket/register |
Register a real-time query |
get_websocket_fetch() |
/2/websocket/fetch |
List registered queries |
get_websocket_delete($id) |
/2/websocket/delete |
Delete a registered query |
v2 renames the filter vocabulary to snake_case and folds the four domain filters into two:
| v1 | v2 |
|---|---|
qInTitle, qInMeta |
q_in_title, q_in_meta |
excludecountry, excludecategory, excludelanguage |
exclude_country, exclude_category, exclude_language |
domain, domainurl, excludedomain, excludedomainurl |
source_url, exclude_source_url |
prioritydomain |
source_priority |
full_content |
content |
removeduplicate, excludefield |
remove_duplicate, exclude_field |
coin and market_id keep their names. v2 responses carry total_results
and next_page where v1 carries totalResults and nextPage.
$response = $client->get_news([ 'q_in_title' => 'tesla', 'source_url' => 'bbc.com', 'content' => true, ]);
There is no /2/archive — get_news() covers historical news through
from_date / to_date.
v1
| Method | Endpoint | Notes |
|---|---|---|
get_latest_news($data) |
/1/latest |
Real-time news |
news_archive($data) |
/1/archive |
Historical news |
news_sources($data) |
/1/sources |
Available sources |
get_crypto_news($data) |
/1/crypto |
Cryptocurrency news |
get_market_news($data) |
/1/market |
Market / financial news |
get_news_count($data) |
/1/count |
Aggregate counts (requires from_date, to_date) |
get_crypto_count($data) |
/1/crypto/count |
Aggregate crypto counts (requires dates) |
get_market_count($data) |
/1/market/count |
Aggregate market counts (requires dates) |
The real-time service is v2 only — there are no v1 WebSocket methods.
Each $data value may be a single string or an array of strings. Parameter
names are case-insensitive. See the
Newsdata.io documentation — or the
OpenAPI 3.1 spec — for the full
parameter reference per endpoint.
$client->get_market_news(['q' => 'apple', 'market_id' => 'AAPL']); $client->get_news_count([ 'from_date' => '2024-01-01', 'to_date' => '2024-01-31', 'interval' => 'day', ]);
Raw query
To pass a query string or full URL verbatim, use raw_query. It is mutually
exclusive with every other parameter and is validated against the endpoint's
allowed keys (for the v1 count endpoints it must also carry from_date and
to_date):
$client->get_latest_news(['raw_query' => 'q=bitcoin&country=us&language=en']);
Paging: scroll and paginate
The news and count methods (not the sources ones) can follow the page cursor for you. Add the control keys to the parameter array — they are not sent to the API:
// scroll: one merged response, at most max_result results (optional). $merged = $client->get_news(['q' => 'bitcoin', 'scroll' => true, 'max_result' => 200]); count($merged->results); // paginate: a generator yielding one response per page, at most max_pages pages (optional). foreach ($client->get_news(['q' => 'bitcoin', 'paginate' => true, 'max_pages' => 5]) as $page) { echo count($page->results), PHP_EOL; }
scroll and paginate are mutually exclusive. scroll truncates strictly to
max_result; paginate stops at max_pages or when there is no next page.
Version 2 methods follow next_page and return total_results / next_page;
version 1 methods follow nextPage and return totalResults / nextPage. A
version 1 count ends with its aggregate (an object in results): scroll
returns it under aggregate, and paginate stops there. Parameters, a
raw_query included, are validated once, before the first request. The client
sleeps one second between pages; change it with
$client->setPaginationDelay($seconds).
Client-side validation
Before any request is sent, parameters are validated and normalized. A
NewsdataValidationError is raised (without spending API quota) when:
- a parameter is not accepted by that endpoint;
- mutually-exclusive parameters are set together — version 1:
q/qInTitle/qInMeta,country/excludecountry,category/excludecategory,language/excludelanguage,domain/domainurl/excludedomain/excludedomainurl; version 2:q/q_in_title/q_in_meta,country/exclude_country,category/exclude_category,language/exclude_language,source_url/exclude_source_url; sizeis outside 1–50;sentiment_scoreis set withoutsentiment;- a version 1 count endpoint is missing
from_dateorto_date.
Booleans (full_content, image, video, removeduplicate, and the version 2
content, remove_duplicate) are coerced to 1 / 0.
Real-time news (WebSocket)
The real-time service is part of API v2. Register a query first — the returned
registration_id identifies it from then on:
use NewsdataIO\NewsdataApi; use NewsdataIO\NewsdataWebSocket; $api = new NewsdataApi('YOUR_API_KEY'); $ws = new NewsdataWebSocket($api); $registered = $ws->register(['q' => 'bitcoin', 'language' => 'en']); $registrationId = $registered->results->registration_id;
register() takes the same filter names as get_news() (q, q_in_title,
country, exclude_country, source_url, content, exclude_field,
timezone, …) — the date, paging and sorting filters, id and url don't
apply to a standing query, and news_type is set by the client. Registering an
identical query twice throws NewsdataAPIError with status 409; the existing id
is in the response body. raw_query works here too.
fetch() lists every registered query: results is a list with one entry per
query, carrying its registration_id, the filters it was registered with
(query), how many devices are streaming it now (active_clients) and when
one last connected (last_used, UTC). delete($id) removes one. Once every
registration the plan allows is in use, registering another throws a 429
NewsdataRateLimitError carrying the code RegistrationLimitExceeded; it is
not retried, since only deleting a registration frees a slot.
All three also exist directly on the API object as
get_websocket_register(), get_websocket_fetch() and
get_websocket_delete().
Then stream. Each response has status, total_results and results keys,
and its articles carry the same v2 layout as get_news() results (id, url,
published_at, …, with related fields grouped under media, source and
ai). stream() is a generator — break out of the loop to stop, and the
connection closes for you:
foreach ($ws->stream($registrationId) as $response) { foreach ($response->results as $article) { echo $article->title, ' - ', $article->url, PHP_EOL; } }
Transient drops (network errors, server restarts, abnormal closes) are
reconnected automatically with a capped exponential backoff. Pass
'reconnect' => false to stop on the first disconnect instead. A permanent
rejection — bad API key or unknown
registration_id, exhausted API credits, or too many simultaneous devices — throws
NewsdataWebSocketAuthError and is not retried.
When it refuses a connection, the server accepts the handshake, sends one error
response — {"status":"error","results":{"message":"…","code":"…"}} — and
closes. The stream never yields that response: it becomes the thrown error,
whose message is the server's explanation, getErrorCode() its code and
getResponseBody() the whole response. Close code 1008 is permanent; its
reason is the bare code: Unauthorized or InvalidRequest (bad key or unknown
registration_id), ApiLimitExceeded or ApiKeyLimitExceeded (credits used
up), DeviceLimitExceeded (more than 5 devices on one registration_id).
Every other close code — 1011 (server error) and 1013 (the client read too
slowly) included — is transient and reconnects; with 'reconnect' => false it
throws NewsdataWebSocketError carrying the server's message.
A quiet stream is not a failure: news can be minutes apart. When nothing
arrives for pingInterval seconds (default 20) the client sends a ping, and
only when nothing comes back within pingTimeout more seconds (default 20) is
the connection treated as dead and reconnected.
Each delivered article consumes 1 API credit per connected device.
Catch it like any other client error:
use NewsdataIO\Exception\NewsdataWebSocketAuthError; use NewsdataIO\Exception\NewsdataWebSocketError; try { foreach ($ws->stream($registrationId) as $response) { // ... } } catch (NewsdataWebSocketAuthError $e) { echo 'rejected (', $e->getErrorCode(), '): ', $e->getMessage(), PHP_EOL; } catch (NewsdataWebSocketError $e) { echo 'stream error: ', $e->getMessage(), PHP_EOL; }
All connection options are optional:
$ws = new NewsdataWebSocket($api, [ 'baseUrl' => 'wss://ws.newsdata.io/ws/event', // staging / self-hosted 'reconnect' => true, // auto-reconnect on transient drops; default true 'reconnectDelay' => 1.0, // seconds before the first reconnect (doubles each retry) 'reconnectDelayMax' => 30.0, // cap on the reconnect delay 'handshakeTimeout' => 10, // seconds to wait for the opening handshake (only) 'pingInterval' => 20.0, // seconds of silence before a keepalive ping; null = no keepalive 'pingTimeout' => 20.0, // seconds to wait for anything after that ping ]);
Streaming needs one extra package. PHP has no WebSocket client in core, so
stream()requiresphrity/websocketversion 4 (PHP 8.1+; tested with 4.1):composer require phrity/websocket:^4.1It is an optional dependency — everything else in this SDK, including the three
websocket/*management endpoints above, works without it on every supported PHP version.stream()throws aNewsdataWebSocketErrorat once, telling you to install it, if it is missing.
Runnable example: examples/websocket.php.
Error handling
use NewsdataIO\Exception\NewsdataValidationError; use NewsdataIO\Exception\NewsdataAuthError; use NewsdataIO\Exception\NewsdataRateLimitError; use NewsdataIO\Exception\NewsdataAPIError; use NewsdataIO\Exception\NewsdataNetworkError; try { $client->get_latest_news(['q' => 'news']); } catch (NewsdataValidationError $e) { // bad parameter — $e->getParam() } catch (NewsdataAuthError $e) { // 401 / 403 } catch (NewsdataRateLimitError $e) { // 429 — $e->getRetryAfter() } catch (NewsdataAPIError $e) { // other API error — $e->getStatusCode(), $e->getResponseBody() } catch (NewsdataNetworkError $e) { // cURL / connectivity failure }
Hierarchy (all under the NewsdataIO\Exception namespace):
NewsdataException (catch-all base)
├── NewsdataValidationError (getParam())
├── NewsdataAPIError (getStatusCode(), getResponseBody())
│ ├── NewsdataAuthError (401 / 403)
│ ├── NewsdataRateLimitError (429; getRetryAfter())
│ │ ├── NewsdataApiLimitExceededError (account credits gone)
│ │ └── NewsdataApiKeyLimitExceededError (this key's cap gone)
│ │ (RegistrationLimitExceeded stays on NewsdataRateLimitError —
│ │ real-time registration slots, not credits)
│ └── NewsdataServerError (5xx)
├── NewsdataNetworkError (cURL / connectivity)
└── NewsdataWebSocketError (real-time stream; getErrorCode(), getResponseBody())
└── NewsdataWebSocketAuthError (policy-violation close 1008)
Upgrading from 1.x
NewsdataIO\NewsdataAPIException, the single exception class of 1.x, is no longer thrown
(the class still exists, marked deprecated, so old code keeps loading). A
catch (NewsdataAPIException $e) block now silently stops catching API errors:
catch NewsdataException (everything the SDK throws) or the specific
NewsdataAPIError / NewsdataNetworkError / … subclasses above instead.
Configuration
$client->setTimeouts($connectSeconds = 10, $totalSeconds = 30); $client->setRetries($maxAttempts = 5, $backoffBaseSeconds = 2.0); $client->setRetryBackoffMax($seconds = 60.0); $client->setDecodeJsonAsArray(true); $client->setProxy([ 'CURLOPT_PROXY' => 'proxy.example.com', 'CURLOPT_PROXYPORT' => 8080, 'CURLOPT_PROXYUSERPWD' => 'user:pass', ]); $client->setLogger($psr3Logger); // API key is redacted from logged URLs
Retries cover network errors, HTTP 429, and 5xx responses. A 429 waits for its
Retry-After (integer seconds or HTTP-date) plus one second; without the
header, backoff is exponential (2s → 4s → 8s …, capped). When Retry-After
is longer than setRetryBackoffMax() (default 60 s), the call throws
NewsdataRateLimitError at once with getRetryAfter() set, leaving the wait
to you. Auth and other 4xx errors are never retried.
A 429 that waiting cannot fix is never retried.
NewsdataApiLimitExceededError means the account's whole credit pool is
exhausted, NewsdataApiKeyLimitExceededError means this one key hit its own
cap while the account may still have credits; both extend
NewsdataRateLimitError, so existing catch blocks keep working.
RegistrationLimitExceeded is also never retried, but keeps the plain
NewsdataRateLimitError class — it is about real-time registration slots, not
credits, and is fixed by deleting a registration.
Response metadata for the most recent call:
$client->getLastResponse()->getHttpCode(); $client->getLastResponse()->getHeaders();
Development
composer install composer test # or: vendor/bin/phpunit
The test suite (tests/) covers the parameter validator and runs entirely
offline — no API key required.
Related libraries
Official Newsdata.io clients across languages and runtimes:
- Python — newsdataapi/python-client (PyPI)
- Node.js — newsdataapi/newsdata-nodejs-client (npm)
- React (hooks) — newsdataapi/newsdata-reactjs-client (npm)
- Java — newsdataapi/newsdata-java-sdk (Maven Central)
- .NET — newsdataapi/newsdata-dotnet-sdk (NuGet)
- Go — newsdataapi/newsdata-go-client (pkg.go.dev)
- Dart / Flutter — newsdataapi/newsdata-flutter-client (pub.dev)
- MCP Server (AI assistants) — newsdataapi/newsdata.io-mcp (PyPI)
Also see free news datasets for ML / NLP work.
License
MIT.
