Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 81 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,27 +146,59 @@ $client->get_news_count([

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:
allowed keys (for the v1 count endpoints it must also carry `from_date` and
`to_date`):

```php
$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:

```php
// 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 — `q`/`qInTitle`/`qInMeta`,
`country`/`excludecountry`, `category`/`excludecategory`,
`language`/`excludelanguage`, `domain`/`domainurl`/`excludedomain`;
- 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`;
- `size` is outside 1–50;
- `sentiment_score` is set without `sentiment`;
- a count endpoint is missing `from_date` or `to_date`.
- a version 1 count endpoint is missing `from_date` or `to_date`.

Booleans (`full_content`, `image`, `video`, `removeduplicate`) are coerced to
`1` / `0`.
Booleans (`full_content`, `image`, `video`, `removeduplicate`, and the version 2
`content`, `remove_duplicate`) are coerced to `1` / `0`.

## Real-time news (WebSocket)

Expand All @@ -187,8 +219,9 @@ $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. Registering an identical query twice throws
`NewsdataAPIError` with status 409; the existing id is in the response body.
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
Expand Down Expand Up @@ -223,12 +256,22 @@ rejection — bad API key or unknown
`registration_id`, exhausted API credits, or too many simultaneous devices — throws
`NewsdataWebSocketAuthError` and is **not** retried.

The server always accepts the handshake and then closes with code **1008** when
the connection is refused, carrying one of three reasons: `invalid credentials
or registration not found`, `api limit reached`, or `device limit reached` (more
than 5 devices on one `registration_id`). Every other close code — including
`1013` (`send timeout`, meaning the client read too slowly) — is transient and
reconnects.
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.**

Expand All @@ -243,7 +286,7 @@ try {
// ...
}
} catch (NewsdataWebSocketAuthError $e) {
echo 'rejected: ', $e->getMessage(), PHP_EOL;
echo 'rejected (', $e->getErrorCode(), '): ', $e->getMessage(), PHP_EOL;
} catch (NewsdataWebSocketError $e) {
echo 'stream error: ', $e->getMessage(), PHP_EOL;
}
Expand All @@ -257,22 +300,24 @@ $ws = new NewsdataWebSocket($api, [
'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
'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()` requires [`phrity/websocket`](https://packagist.org/packages/phrity/websocket)
> (PHP 8.1+):
> version 4 (PHP 8.1+; tested with 4.1):
>
> ```bash
> composer require phrity/websocket
> composer require phrity/websocket:^4.1
> ```
>
> It 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 a `NewsdataWebSocketError` telling
> you to install it if it is missing.
> supported PHP version. `stream()` throws a `NewsdataWebSocketError` at once,
> telling you to install it, if it is missing.

Runnable example: [`examples/websocket.php`](examples/websocket.php).

Expand Down Expand Up @@ -314,10 +359,18 @@ NewsdataException (catch-all base)
│ │ real-time registration slots, not credits)
│ └── NewsdataServerError (5xx)
├── NewsdataNetworkError (cURL / connectivity)
└── NewsdataWebSocketError (real-time stream)
└── 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

```php
Expand All @@ -333,10 +386,12 @@ $client->setProxy([
$client->setLogger($psr3Logger); // API key is redacted from logged URLs
```

Retries cover network errors, HTTP 429, and 5xx responses. 429 honors the
`Retry-After` header (integer seconds or HTTP-date); otherwise backoff is
exponential (`2s → 4s → 8s …`, capped). Auth and other 4xx errors are never
retried.
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
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
},
"suggest": {
"psr/log": "Allows attaching a PSR-3 logger via NewsdataApi::setLogger()",
"phrity/websocket": "Required for real-time streaming via NewsdataWebSocket::stream() (PHP 8.1+)"
"phrity/websocket": "Required for real-time streaming via NewsdataWebSocket::stream(): version ^4.1 (PHP 8.1+), the range this SDK is tested with"
},
"autoload": {
"psr-4": {
Expand Down
8 changes: 5 additions & 3 deletions examples/websocket.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
*
* NEWSDATA_API_KEY=<your key> php examples/websocket.php
*
* Streaming needs the optional phrity/websocket package (PHP 8.1+):
* Streaming needs the optional phrity/websocket package, version 4 (PHP 8.1+):
*
* composer require phrity/websocket
* composer require phrity/websocket:^4.1
*
* Articles are matched by a registered query. If NEWSDATA_REGISTRATION_ID is
* set, that query is streamed directly; otherwise this registers a demo query
Expand Down Expand Up @@ -70,7 +70,9 @@ function registerDemoQuery(NewsdataWebSocket $ws): string
}
}
} catch (NewsdataWebSocketAuthError $e) {
fwrite(STDERR, 'rejected: ' . $e->getMessage() . PHP_EOL);
// A refusal is never yielded as news: the server's explanation arrives
// here, with its code (Unauthorized, ApiLimitExceeded, DeviceLimitExceeded, ...).
fwrite(STDERR, 'rejected (' . $e->getErrorCode() . '): ' . $e->getMessage() . PHP_EOL);
exit(1);
} catch (NewsdataWebSocketError $e) {
fwrite(STDERR, 'stream error: ' . $e->getMessage() . PHP_EOL);
Expand Down
52 changes: 45 additions & 7 deletions src/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
* Static configuration for the Newsdata.io client: base URL, endpoint paths,
* HTTP defaults, and the per-endpoint accepted-parameter sets.
*
* The parameter sets mirror the server-side filter mapping and the official
* Python client surface. All parameter names are lowercase here; user-supplied
* keys are lowercased before validation (the API itself is case-insensitive,
* so `qInTitle` and `qintitle` are equivalent).
* The parameter sets mirror the server-side filter mapping. All parameter
* names are lowercase here; user-supplied keys are lowercased before
* validation (the API itself is case-insensitive, so `qInTitle` and
* `qintitle` are equivalent).
*/
final class Constants
{
Expand Down Expand Up @@ -52,6 +52,19 @@ final class Constants
/** Cap on any single backoff sleep, in seconds. */
public const DEFAULT_RETRY_BACKOFF_MAX = 60.0;

/** Seconds slept between pages in scroll / paginate mode. */
public const DEFAULT_PAGINATION_DELAY = 1.0;

/**
* Endpoints that page through results with a `page` cursor, and so accept
* the `scroll` / `paginate` control keys. The version 1 count endpoints
* end with their aggregate as an object in `results`.
*/
public const PAGEABLE_ENDPOINTS = [
'latest', 'archive', 'crypto', 'market', 'count', 'crypto_count', 'market_count',
'news_v2', 'market_v2', 'crypto_v2', 'count_news_v2', 'count_market_v2', 'count_crypto_v2',
];

/** Allowed response size bounds (a single account cannot exceed 50). */
public const SIZE_MIN = 1;
public const SIZE_MAX = 50;
Expand Down Expand Up @@ -117,6 +130,30 @@ final class Constants
/** Bound on the opening handshake, in seconds. */
public const WS_HANDSHAKE_TIMEOUT = 10;

/**
* Keepalive: after this many seconds without a
* message the client sends a ping...
*/
public const WS_PING_INTERVAL = 20.0;

/** ...and treats the connection as dead if nothing arrives within this many more. */
public const WS_PING_TIMEOUT = 20.0;

/** How long one read waits when keepalive is off (pingInterval null); a timeout just waits again. */
public const WS_IDLE_READ_TIMEOUT = 300.0;

/**
* Error codes the stream server sends (in its error frame, and as the
* close reason of close 1008) for a permanent rejection.
*/
public const WS_PERMANENT_CODES = [
'Unauthorized',
'InvalidRequest',
'ApiLimitExceeded',
'ApiKeyLimitExceeded',
'DeviceLimitExceeded',
];

/**
* Error codes on a 429 that waiting cannot fix, so they are never retried.
* `ApiLimitExceeded` and `ApiKeyLimitExceeded` mean the API credits are
Expand Down Expand Up @@ -303,15 +340,16 @@ final class Constants
],
// Real-time query registration. The real-time service is v2 only, so
// these are the v2 filter names. No date or paging filters apply — a
// registered query matches news as it is published. `news_type` is set
// by get_websocket_register(), not by the caller.
// registered query matches news as it is published. `news_type` is not
// accepted from the caller: get_websocket_register() adds it after
// validation (so it also works with raw_query).
'websocket_register' => [
'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country',
'category', 'exclude_category', 'language', 'exclude_language',
'source_url', 'exclude_source_url', 'source_priority', 'timezone',
'content', 'image', 'video', 'remove_duplicate', 'tag', 'sentiment',
'sentiment_score', 'region', 'organization', 'creator', 'datatype',
'exclude_field', 'news_type',
'exclude_field',
],
'websocket_fetch' => [],
'websocket_delete' => ['registration_id'],
Expand Down
41 changes: 41 additions & 0 deletions src/Exception/NewsdataWebSocketError.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,49 @@
/**
* A real-time WebSocket stream failure.
*
* When the server explained the failure in an error response before closing
* (`{"status":"error","results":{"message":...,"code":...}}`), the message is
* the server's explanation, {@see getErrorCode()} its code (for example
* `Unauthorized` or `ServerError`) and {@see getResponseBody()} the whole
* response.
*
* @see \NewsdataIO\NewsdataWebSocket
*/
class NewsdataWebSocketError extends NewsdataException
{
/** @var array|null */
private $responseBody;

/** @var string|null */
private $errorCode;

public function __construct(
string $message = '',
?array $responseBody = null,
?string $errorCode = null,
?\Throwable $previous = null
) {
parent::__construct($message, 0, $previous);
$this->responseBody = $responseBody;
$this->errorCode = $errorCode;
}

/**
* The error response the server sent before closing, decoded to an
* array regardless of the client's setDecodeJsonAsArray() setting, or
* null when there was none.
*/
public function getResponseBody(): ?array
{
return $this->responseBody;
}

/**
* The server's error code (`Unauthorized`, `ApiLimitExceeded`,
* `DeviceLimitExceeded`, `ServerError`, ...), or null when unknown.
*/
public function getErrorCode(): ?string
{
return $this->errorCode;
}
}
22 changes: 20 additions & 2 deletions src/NewsdataApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
*
* $client = new NewsdataApi(NEWSDATA_API_KEY);
* $response = $client->get_latest_news(['q' => 'bitcoin', 'country' => 'us']);
*
* The news and count methods (not the sources ones) also page for you:
* `'scroll' => true` (with an optional `'max_result' => N`)
* follows the page cursor and returns one merged response, and
* `'paginate' => true` (with an optional `'max_pages' => N`) returns a
* generator yielding one response per page.
*
* $merged = $client->get_news(['q' => 'bitcoin', 'scroll' => true, 'max_result' => 200]);
* foreach ($client->get_news(['q' => 'bitcoin', 'paginate' => true, 'max_pages' => 5]) as $page) { ... }
*/
class NewsdataApi extends NewsdataApiBase
{
Expand Down Expand Up @@ -60,6 +69,14 @@ public function setRetryBackoffMax(float $seconds): void
$this->retryBackoffMax = $seconds;
}

/**
* Seconds to sleep between pages in scroll / paginate mode (default 1).
*/
public function setPaginationDelay(float $seconds): void
{
$this->paginationDelay = max(0.0, $seconds);
}

/**
* Decode JSON responses as associative arrays instead of objects.
*/
Expand Down Expand Up @@ -304,8 +321,9 @@ public function get_count_crypto(array $data = [])
*/
public function get_websocket_register(array $data = [])
{
$data['news_type'] = Constants::WS_NEWS_TYPE;
return $this->request('websocket_register', $data);
// news_type names the feed; the client adds it after validation, so a
// raw_query (which must be the only caller parameter) works too.
return $this->request('websocket_register', $data, ['news_type' => Constants::WS_NEWS_TYPE]);
}

/**
Expand Down
Loading
Loading