diff --git a/README.md b/README.md index eb3604e..7a8c9d6 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,52 @@ By default the response is decoded to objects; call ## 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`. + +```php +$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 | @@ -77,9 +123,8 @@ By default the response is decoded to objects; call | `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) | -| `get_websocket_register($data)` | `/1/websocket/register` | Register a real-time query | -| `get_websocket_fetch()` | `/1/websocket/fetch` | List registered queries | -| `get_websocket_delete($id)` | `/1/websocket/delete` | Delete a registered query | + +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 @@ -125,7 +170,8 @@ Booleans (`full_content`, `image`, `video`, `removeduplicate`) are coerced to ## Real-time news (WebSocket) -Register a query first — the returned `registration_id` identifies it from then on: +The real-time service is part of API v2. Register a query first — the returned +`registration_id` identifies it from then on: ```php use NewsdataIO\NewsdataApi; @@ -138,21 +184,34 @@ $registered = $ws->register(['q' => 'bitcoin', 'language' => 'en']); $registrationId = $registered->results->registration_id; ``` -`register()` takes the familiar filter names (`q`, `country`, `language`, -`domain`, …) — no date or paging filters, since a registered query matches news -as it is published. Registering an identical query twice throws +`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. -`fetch()` lists every registered query and `delete($id)` removes one. All three -also exist directly on the API object as `get_websocket_register()`, -`get_websocket_fetch()` and `get_websocket_delete()`. -Then stream. `stream()` is a generator — `break` out of the loop to stop, and -the connection closes for you: +`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: ```php foreach ($ws->stream($registrationId) as $response) { foreach ($response->results as $article) { - echo $article->title, ' - ', $article->link, PHP_EOL; + echo $article->title, ' - ', $article->url, PHP_EOL; } } ``` @@ -249,6 +308,10 @@ NewsdataException (catch-all base) ├── 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) @@ -275,6 +338,15 @@ Retries cover network errors, HTTP 429, and 5xx responses. 429 honors the exponential (`2s → 4s → 8s …`, capped). 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: ```php diff --git a/examples/websocket.php b/examples/websocket.php index dc661ce..e4b9938 100644 --- a/examples/websocket.php +++ b/examples/websocket.php @@ -66,7 +66,7 @@ function registerDemoQuery(NewsdataWebSocket $ws): string try { foreach ($ws->stream($registrationId) as $response) { foreach ($response->results as $article) { - echo $article->title, ' - ', $article->link, PHP_EOL; + echo $article->title, ' - ', $article->url, PHP_EOL; } } } catch (NewsdataWebSocketAuthError $e) { diff --git a/src/Constants.php b/src/Constants.php index c14be61..79da5e0 100644 --- a/src/Constants.php +++ b/src/Constants.php @@ -21,11 +21,19 @@ final class Constants /** API base path. */ public const API_BASE_PATH = 'api/'; - /** API version. */ + /** + * API version of the v1 endpoints. + * + * @deprecated The version now lives in the endpoint path, so that v1 and + * v2 endpoints can share one base URL. See {@see ENDPOINTS}. + */ public const API_VERSION = '1'; - /** Fully-qualified base URL, with a trailing slash. */ - public const BASE_URL = self::API_HOST . self::API_BASE_PATH . self::API_VERSION . '/'; + /** + * Fully-qualified API root, with a trailing slash. The endpoint paths in + * {@see ENDPOINTS} carry the API version. + */ + public const BASE_URL = self::API_HOST . self::API_BASE_PATH; // ---- HTTP defaults ---------------------------------------------------- @@ -52,17 +60,27 @@ final class Constants * Endpoint key => path appended to {@see BASE_URL}. */ public const ENDPOINTS = [ - 'latest' => 'latest', - 'crypto' => 'crypto', - 'archive' => 'archive', - 'sources' => 'sources', - 'market' => 'market', - 'count' => 'count', - 'crypto_count' => 'crypto/count', - 'market_count' => 'market/count', - 'websocket_register' => 'websocket/register', - 'websocket_fetch' => 'websocket/fetch', - 'websocket_delete' => 'websocket/delete', + // v1 + 'latest' => '1/latest', + 'crypto' => '1/crypto', + 'archive' => '1/archive', + 'sources' => '1/sources', + 'market' => '1/market', + 'count' => '1/count', + 'crypto_count' => '1/crypto/count', + 'market_count' => '1/market/count', + // v2 + 'news_v2' => '2/news', + 'market_v2' => '2/market', + 'crypto_v2' => '2/crypto', + 'sources_v2' => '2/sources', + 'count_news_v2' => '2/count/news', + 'count_market_v2' => '2/count/market', + 'count_crypto_v2' => '2/count/crypto', + // The real-time service is v2 only. + 'websocket_register' => '2/websocket/register', + 'websocket_fetch' => '2/websocket/fetch', + 'websocket_delete' => '2/websocket/delete', ]; /** HTTP method per endpoint; anything absent is a GET. */ @@ -84,8 +102,8 @@ final class Constants /** Real-time WebSocket endpoint. */ public const WS_BASE_URL = 'wss://ws.newsdata.io/ws/event'; - /** The feed a registered query matches against. */ - public const WS_NEWS_TYPE = 'latest'; + /** The feed a registered query matches against; only news so far. */ + public const WS_NEWS_TYPE = 'news'; /** Close code the server uses for a permanent connection rejection. */ public const WS_POLICY_VIOLATION = 1008; @@ -100,22 +118,45 @@ final class Constants public const WS_HANDSHAKE_TIMEOUT = 10; /** - * Error codes on a 429 meaning the account's API credits are exhausted - * rather than a transient rate limit. These are never retried — waiting - * out the backoff cannot conjure more credits. + * Error codes on a 429 that waiting cannot fix, so they are never retried. + * `ApiLimitExceeded` and `ApiKeyLimitExceeded` mean the API credits are + * exhausted rather than a transient rate limit — backoff cannot conjure + * more credits. `RegistrationLimitExceeded` means every real-time + * registration the plan allows is in use; only deleting one frees a slot. * * `ApiLimitExceeded` is the documented code (see the ErrorCode enum in * https://newsdata.io/openapi.json); `ApiKeyLimitExceeded` is accepted too * because the API has been observed to send it and the spec is not * exhaustive. */ - public const QUOTA_EXHAUSTED_CODES = ['ApiLimitExceeded', 'ApiKeyLimitExceeded']; + public const QUOTA_EXHAUSTED_CODES = [ + 'ApiLimitExceeded', + 'ApiKeyLimitExceeded', + 'RegistrationLimitExceeded', + ]; + + /** + * Error code on a 429 => the exception class to throw. None of them is + * worth retrying, but the remedy differs: `ApiLimitExceeded` is the + * account's whole credit pool, `ApiKeyLimitExceeded` is this one key's own + * cap, and `RegistrationLimitExceeded` is the real-time registration slots + * — it keeps the base class, since it is not about credits at all. + */ + public const QUOTA_EXHAUSTED_ERRORS = [ + 'ApiLimitExceeded' => Exception\NewsdataApiLimitExceededError::class, + 'ApiKeyLimitExceeded' => Exception\NewsdataApiKeyLimitExceededError::class, + 'RegistrationLimitExceeded' => Exception\NewsdataRateLimitError::class, + ]; /** Endpoints that require both `from_date` and `to_date`. */ public const REQUIRES_DATE_RANGE = ['count', 'crypto_count', 'market_count']; /** Parameters sent as boolean flags (coerced to `1` / `0`). */ - public const BOOL_PARAMS = ['full_content', 'image', 'video', 'removeduplicate']; + public const BOOL_PARAMS = [ + 'full_content', 'image', 'video', 'removeduplicate', + // v2 spellings + 'content', 'remove_duplicate', + ]; /** Parameters that must be integers. */ public const INT_PARAMS = ['size']; @@ -132,7 +173,13 @@ final class Constants ['country', 'excludecountry'], ['category', 'excludecategory'], ['language', 'excludelanguage'], - ['domain', 'domainurl', 'excludedomain'], + ['domain', 'domainurl', 'excludedomain', 'excludedomainurl'], + // v2 names + ['q', 'q_in_title', 'q_in_meta'], + ['country', 'exclude_country'], + ['category', 'exclude_category'], + ['language', 'exclude_language'], + ['source_url', 'exclude_source_url'], ]; /** @@ -141,69 +188,130 @@ final class Constants public const FILTERS = [ 'latest' => [ 'q', 'qintitle', 'qinmeta', 'country', 'excludecountry', 'category', - 'excludecategory', 'language', 'excludelanguage', 'domain', 'domainurl', - 'excludedomain', 'prioritydomain', 'timeframe', 'timezone', 'size', - 'full_content', 'image', 'video', 'page', 'tag', 'sentiment', 'region', - 'excludefield', 'removeduplicate', 'id', 'organization', 'url', 'sort', - 'creator', 'datatype', 'sentiment_score', + 'excludecategory', 'language', 'excludelanguage', 'domain', + 'domainurl', 'excludedomain', 'excludedomainurl', 'prioritydomain', + 'timeframe', 'timezone', 'size', 'full_content', 'image', 'video', + 'page', 'tag', 'sentiment', 'region', 'excludefield', + 'removeduplicate', 'id', 'organization', 'url', 'sort', 'creator', + 'datatype', 'sentiment_score', ], 'archive' => [ 'q', 'qintitle', 'qinmeta', 'country', 'excludecountry', 'category', - 'excludecategory', 'language', 'excludelanguage', 'domain', 'domainurl', - 'excludedomain', 'prioritydomain', 'timezone', 'size', 'full_content', - 'image', 'video', 'page', 'from_date', 'to_date', 'excludefield', 'id', - 'url', 'sort', 'tag', 'sentiment', 'sentiment_score', 'region', - 'organization', 'creator', 'datatype', 'removeduplicate', + 'excludecategory', 'language', 'excludelanguage', 'domain', + 'domainurl', 'excludedomain', 'excludedomainurl', 'prioritydomain', + 'timezone', 'size', 'full_content', 'image', 'video', 'page', + 'from_date', 'to_date', 'excludefield', 'id', 'url', 'sort', 'tag', + 'sentiment', 'sentiment_score', 'region', 'organization', 'creator', + 'datatype', 'removeduplicate', ], 'crypto' => [ 'q', 'qintitle', 'qinmeta', 'language', 'excludelanguage', 'domain', - 'domainurl', 'excludedomain', 'prioritydomain', 'timeframe', 'timezone', - 'size', 'full_content', 'image', 'video', 'page', 'tag', 'sentiment', - 'coin', 'excludefield', 'from_date', 'to_date', 'removeduplicate', 'id', - 'url', 'sort', + 'domainurl', 'excludedomain', 'excludedomainurl', 'prioritydomain', + 'timeframe', 'timezone', 'size', 'full_content', 'image', 'video', + 'page', 'tag', 'sentiment', 'coin', 'excludefield', 'from_date', + 'to_date', 'removeduplicate', 'id', 'url', 'sort', ], 'sources' => [ 'country', 'category', 'language', 'prioritydomain', 'domainurl', ], 'market' => [ 'q', 'qintitle', 'qinmeta', 'from_date', 'to_date', 'country', - 'excludecountry', 'domain', 'domainurl', 'excludedomain', 'language', - 'excludelanguage', 'prioritydomain', 'timezone', 'timeframe', 'size', - 'full_content', 'image', 'video', 'page', 'tag', 'sentiment', - 'excludefield', 'removeduplicate', 'organization', 'market_id', 'id', 'url', - 'sort', 'creator', 'datatype', 'sentiment_score', + 'excludecountry', 'domain', 'domainurl', 'excludedomain', + 'excludedomainurl', 'language', 'excludelanguage', 'prioritydomain', + 'timezone', 'timeframe', 'size', 'full_content', 'image', 'video', + 'page', 'tag', 'sentiment', 'excludefield', 'removeduplicate', + 'organization', 'market_id', 'id', 'url', 'sort', 'creator', + 'datatype', 'sentiment_score', ], 'count' => [ 'from_date', 'to_date', 'q', 'qintitle', 'qinmeta', 'country', 'excludecountry', 'category', 'excludecategory', 'language', - 'excludelanguage', 'domain', 'domainurl', 'excludedomain', 'full_content', - 'image', 'video', 'prioritydomain', 'page', 'size', 'sort', 'interval', - 'tag', 'sentiment', 'sentiment_score', 'region', 'organization', 'creator', - 'datatype', 'removeduplicate', + 'excludelanguage', 'domain', 'domainurl', 'excludedomain', + 'excludedomainurl', 'full_content', 'image', 'video', 'prioritydomain', + 'page', 'size', 'sort', 'interval', 'tag', 'sentiment', + 'sentiment_score', 'region', 'organization', 'creator', 'datatype', + 'removeduplicate', ], 'crypto_count' => [ 'from_date', 'to_date', 'q', 'qintitle', 'qinmeta', 'language', 'excludelanguage', 'coin', 'domain', 'domainurl', 'excludedomain', - 'full_content', 'image', 'video', 'prioritydomain', 'page', 'sentiment', - 'size', 'sort', 'tag', 'interval', 'removeduplicate', + 'excludedomainurl', 'full_content', 'image', 'video', 'prioritydomain', + 'page', 'sentiment', 'size', 'sort', 'tag', 'interval', + 'removeduplicate', ], 'market_count' => [ 'from_date', 'to_date', 'q', 'qintitle', 'qinmeta', 'country', - 'excludecountry', 'domain', 'domainurl', 'excludedomain', 'language', - 'excludelanguage', 'full_content', 'image', 'video', 'organization', - 'market_id', 'prioritydomain', 'page', 'sentiment', 'removeduplicate', 'size', - 'sort', 'tag', 'interval', 'creator', 'datatype', 'sentiment_score', - ], - // Real-time query registration. No date/paging filters — a registered - // query matches news as it is published. `news_type` is set by - // get_websocket_register(), not by the caller. + 'excludecountry', 'domain', 'domainurl', 'excludedomain', + 'excludedomainurl', 'language', 'excludelanguage', 'full_content', + 'image', 'video', 'organization', 'market_id', 'prioritydomain', + 'page', 'sentiment', 'removeduplicate', 'size', 'sort', 'tag', + 'interval', 'creator', 'datatype', 'sentiment_score', + ], + + // ---- v2 ---------------------------------------------------------- + // v2 renames the filter vocabulary to snake_case and folds + // domain/domainurl/excludedomain/excludedomainurl into + // source_url/exclude_source_url. + 'news_v2' => [ + 'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country', + 'category', 'exclude_category', 'language', 'exclude_language', + 'source_url', 'exclude_source_url', 'source_priority', 'from_date', + 'to_date', 'timeframe', 'timezone', 'size', 'content', 'image', + 'video', 'page', 'tag', 'sentiment', 'sentiment_score', 'region', + 'organization', 'creator', 'datatype', 'exclude_field', + 'remove_duplicate', 'id', 'url', 'sort', + ], + 'market_v2' => [ + 'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country', + 'language', 'exclude_language', 'source_url', 'exclude_source_url', + 'source_priority', 'from_date', 'to_date', 'timeframe', 'timezone', + 'size', 'content', 'image', 'video', 'page', 'tag', 'sentiment', + 'sentiment_score', 'organization', 'market_id', 'creator', 'datatype', + 'exclude_field', 'remove_duplicate', 'id', 'url', 'sort', + ], + 'crypto_v2' => [ + 'q', 'q_in_title', 'q_in_meta', 'coin', 'language', 'exclude_language', + 'source_url', 'exclude_source_url', 'source_priority', 'from_date', + 'to_date', 'timeframe', 'timezone', 'size', 'content', 'image', + 'video', 'page', 'tag', 'sentiment', 'exclude_field', + 'remove_duplicate', 'id', 'url', 'sort', + ], + 'sources_v2' => [ + 'country', 'category', 'language', 'source_priority', 'source_url', + ], + 'count_news_v2' => [ + 'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country', + 'category', 'exclude_category', 'language', 'exclude_language', + 'source_url', 'exclude_source_url', 'source_priority', 'from_date', + 'to_date', 'timeframe', 'interval', 'size', 'content', 'image', + 'video', 'page', 'tag', 'sentiment', 'sentiment_score', 'region', + 'organization', 'creator', 'datatype', 'remove_duplicate', 'sort', + ], + 'count_market_v2' => [ + 'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country', + 'language', 'exclude_language', 'source_url', 'exclude_source_url', + 'source_priority', 'from_date', 'to_date', 'timeframe', 'interval', + 'size', 'content', 'image', 'video', 'page', 'tag', 'sentiment', + 'sentiment_score', 'organization', 'market_id', 'creator', 'datatype', + 'remove_duplicate', 'sort', + ], + 'count_crypto_v2' => [ + 'q', 'q_in_title', 'q_in_meta', 'coin', 'language', 'exclude_language', + 'source_url', 'exclude_source_url', 'source_priority', 'from_date', + 'to_date', 'timeframe', 'interval', 'size', 'content', 'image', + 'video', 'page', 'tag', 'sentiment', 'remove_duplicate', 'sort', + ], + // 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. 'websocket_register' => [ - 'q', 'qintitle', 'qinmeta', 'country', 'excludecountry', 'category', - 'excludecategory', 'language', 'excludelanguage', 'domain', 'domainurl', - 'excludedomain', 'prioritydomain', 'timezone', 'full_content', 'image', - 'video', 'removeduplicate', 'tag', 'sentiment', 'sentiment_score', - 'region', 'organization', 'creator', 'datatype', 'excludefield', - 'news_type', + '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', ], 'websocket_fetch' => [], 'websocket_delete' => ['registration_id'], diff --git a/src/Exception/NewsdataApiKeyLimitExceededError.php b/src/Exception/NewsdataApiKeyLimitExceededError.php new file mode 100644 index 0000000..a27b958 --- /dev/null +++ b/src/Exception/NewsdataApiKeyLimitExceededError.php @@ -0,0 +1,15 @@ +request('market_count', $data); } + // ---- v2 endpoints ----------------------------------------------------- + // + // v2 renames the filter vocabulary to snake_case (`q_in_title`, + // `exclude_country`, `source_priority`, `content`, `remove_duplicate`, …) + // and folds domain/domainurl/excludedomain/excludedomainurl into + // `source_url` / `exclude_source_url`. Responses carry `total_results` + // and `next_page` where v1 carries `totalResults` and `nextPage`. + + /** + * Latest news, or historical news with `from_date` / `to_date`. + * GET /2/news + * + * There is no /2/archive; this endpoint covers both. + * + * @param array $data + * + * @return array|object + */ + public function get_news(array $data = []) + { + return $this->request('news_v2', $data); + } + + /** + * Market / financial news. GET /2/market + * + * @param array $data + * + * @return array|object + */ + public function get_market(array $data = []) + { + return $this->request('market_v2', $data); + } + + /** + * Cryptocurrency news. GET /2/crypto + * + * @param array $data + * + * @return array|object + */ + public function get_crypto(array $data = []) + { + return $this->request('crypto_v2', $data); + } + + /** + * Available news sources. GET /2/sources + * + * @param array $data + * + * @return array|object + */ + public function get_sources(array $data = []) + { + return $this->request('sources_v2', $data); + } + + /** + * Aggregate news counts. GET /2/count/news + * + * @param array $data + * + * @return array|object + */ + public function get_count_news(array $data = []) + { + return $this->request('count_news_v2', $data); + } + + /** + * Aggregate market news counts. GET /2/count/market + * + * @param array $data + * + * @return array|object + */ + public function get_count_market(array $data = []) + { + return $this->request('count_market_v2', $data); + } + + /** + * Aggregate crypto news counts. GET /2/count/crypto + * + * @param array $data + * + * @return array|object + */ + public function get_count_crypto(array $data = []) + { + return $this->request('count_crypto_v2', $data); + } + // ---- real-time query management --------------------------------------- /** - * Register a real-time WebSocket query. POST /1/websocket/register. + * Register a real-time WebSocket query. POST /2/websocket/register. * - * Takes the familiar filter names (`q`, `country`, `language`, `domain`, …); - * no date or paging filters apply, since a registered query matches news as - * it is published. The new query's id is at `results.registration_id` — + * The real-time service is v2 only, so this takes the same filter names as + * {@see NewsdataApi::get_news()} (`q`, `q_in_title`, `country`, + * `exclude_country`, `source_url`, `content`, `exclude_field`, `timezone`, + * …); the date, paging and sorting filters, `id` and `url` do not apply to + * a standing query. The new query's id is at `results.registration_id` — * pass it to {@see NewsdataWebSocket::stream()}. * * Registering an identical query twice throws @@ -213,7 +310,10 @@ public function get_websocket_register(array $data = []) /** * List the account's registered real-time queries. - * GET /1/websocket/fetch. One entry per query at `results.queries`. + * GET /2/websocket/fetch. `results` is a list with one entry per query, + * each 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). * * @return array|object */ @@ -223,7 +323,7 @@ public function get_websocket_fetch() } /** - * Delete a registered real-time query. DELETE /1/websocket/delete. + * Delete a registered real-time query. DELETE /2/websocket/delete. * * @param string $registrationId * diff --git a/src/NewsdataApiBase.php b/src/NewsdataApiBase.php index 6477650..5cfc59e 100644 --- a/src/NewsdataApiBase.php +++ b/src/NewsdataApiBase.php @@ -149,10 +149,19 @@ private function execute(string $baseUrl, array $params, string $endpoint = '') $retryAfter = $this->parseRetryAfter( isset($headers['retry_after']) ? $headers['retry_after'] : null ); + if (isset($headers['x_apikey_limit_remaining'])) { + $this->log( + 'warning', + 'X-APIKEY-Limit-Remaining: ' . $headers['x_apikey_limit_remaining'] + ); + } // A 429 covers a burst limit, a rate limit, and exhausted API // credits. Only the first two are worth retrying. - if ($this->quotaExhausted($body) || $attempt >= $attempts) { - throw new NewsdataRateLimitError( + $quotaError = $this->quotaExhaustedError($body); + if ($quotaError !== null || $attempt >= $attempts) { + $errorClass = $quotaError !== null ? $quotaError : NewsdataRateLimitError::class; + + throw new $errorClass( $this->errorMessage($body, $status), 429, $this->toArray($body), @@ -351,12 +360,15 @@ private function toArray($body): ?array * @param int $status */ /** - * Whether a 429 body carries an error code meaning the account is out of - * API credits, as opposed to a transient rate limit. + * The exception class for a 429 whose body says the API credits are + * exhausted, or null when the 429 is a transient rate limit worth + * retrying. * * @param mixed $body + * + * @return class-string|null */ - private function quotaExhausted($body): bool + private function quotaExhaustedError($body): ?string { $results = null; if (is_array($body)) { @@ -372,7 +384,13 @@ private function quotaExhausted($body): bool $code = $results->code ?? null; } - return is_string($code) && in_array($code, Constants::QUOTA_EXHAUSTED_CODES, true); + if (!is_string($code) || !in_array($code, Constants::QUOTA_EXHAUSTED_CODES, true)) { + return null; + } + + // Every code in QUOTA_EXHAUSTED_CODES has an entry in the map; the + // QuotaExhaustedTest pins that invariant. + return Constants::QUOTA_EXHAUSTED_ERRORS[$code]; } private function errorMessage($body, int $status): string diff --git a/src/NewsdataWebSocket.php b/src/NewsdataWebSocket.php index fe523e9..4a12404 100644 --- a/src/NewsdataWebSocket.php +++ b/src/NewsdataWebSocket.php @@ -151,8 +151,9 @@ private function nextDelay(float $delay): float /** * Connect and yield each response for $registrationId as it arrives. * - * Responses have the familiar `status` / `totalResults` / `results` shape, - * decoded the same way the REST methods decode theirs. + * Responses have `status`, `total_results` and `results` keys, and their + * articles carry the same v2 layout as {@see NewsdataApi::get_news()} + * results. They are decoded the same way the REST methods decode theirs. * * @param string $registrationId * diff --git a/tests/NewsdataWebSocketTest.php b/tests/NewsdataWebSocketTest.php index 53f22b3..03d89ca 100644 --- a/tests/NewsdataWebSocketTest.php +++ b/tests/NewsdataWebSocketTest.php @@ -10,6 +10,7 @@ use NewsdataIO\Exception\NewsdataWebSocketError; use NewsdataIO\NewsdataApi; use NewsdataIO\NewsdataWebSocket; +use NewsdataIO\ParamValidator; use PHPUnit\Framework\TestCase; /** @@ -99,8 +100,8 @@ private static function articleFrame(string $id, string $title): string { return json_encode([ 'status' => 'success', - 'totalResults' => 1, - 'results' => [['article_id' => $id, 'title' => $title]], + 'total_results' => 1, + 'results' => [['id' => $id, 'title' => $title]], ]); } @@ -256,6 +257,56 @@ public function testRegisterInjectsNewsTypeIntoFilters(): void $this->assertNotContains('size', $filters); } + // ---- API version 2 ---------------------------------------------------- + // The real-time service moved to API version 2: the management endpoints + // sit under /2/, news_type names the v2 news feed, and a registration + // takes the v2 filter vocabulary only. + + public function testNewsTypeNamesTheV2NewsFeed(): void + { + $this->assertSame('news', Constants::WS_NEWS_TYPE); + } + + public function testRegisterTakesTheV2FilterNames(): void + { + $filters = Constants::FILTERS['websocket_register']; + foreach ([ + 'q_in_title', 'q_in_meta', 'exclude_country', 'exclude_category', + 'exclude_language', 'source_url', 'exclude_source_url', + 'source_priority', 'content', 'remove_duplicate', 'exclude_field', + ] as $name) { + $this->assertContains($name, $filters, $name); + } + } + + public function testRegisterNoLongerTakesTheV1FilterNames(): void + { + $filters = Constants::FILTERS['websocket_register']; + foreach ([ + 'qintitle', 'qinmeta', 'excludecountry', 'excludecategory', + 'excludelanguage', 'domain', 'domainurl', 'excludedomain', + 'excludedomainurl', 'prioritydomain', 'full_content', + 'removeduplicate', 'excludefield', + ] as $name) { + $this->assertNotContains($name, $filters, $name); + } + } + + public function testRegisterRejectsAV1FilterName(): void + { + $this->expectException(NewsdataValidationError::class); + $this->api()->get_websocket_register(['qintitle' => 'pizza']); + } + + public function testRegisterKeepsTheV2SourceUrlMutexGroup(): void + { + $this->expectException(NewsdataValidationError::class); + ParamValidator::validate('websocket_register', [ + 'source_url' => 'a.com', + 'exclude_source_url' => 'b.com', + ]); + } + public function testWebsocketEndpointsUseTheRightHttpMethods(): void { $this->assertSame('POST', Constants::ENDPOINT_METHODS['websocket_register']); @@ -266,9 +317,10 @@ public function testWebsocketEndpointsUseTheRightHttpMethods(): void public function testWebsocketEndpointPathsAreRegistered(): void { - $this->assertSame('websocket/register', Constants::ENDPOINTS['websocket_register']); - $this->assertSame('websocket/fetch', Constants::ENDPOINTS['websocket_fetch']); - $this->assertSame('websocket/delete', Constants::ENDPOINTS['websocket_delete']); + // The endpoint path carries the API version; real-time is v2 only. + $this->assertSame('2/websocket/register', Constants::ENDPOINTS['websocket_register']); + $this->assertSame('2/websocket/fetch', Constants::ENDPOINTS['websocket_fetch']); + $this->assertSame('2/websocket/delete', Constants::ENDPOINTS['websocket_delete']); } public function testDeleteRejectsEmptyRegistrationId(): void diff --git a/tests/QuotaExhaustedTest.php b/tests/QuotaExhaustedTest.php index 73e21b0..4614295 100644 --- a/tests/QuotaExhaustedTest.php +++ b/tests/QuotaExhaustedTest.php @@ -5,12 +5,15 @@ namespace NewsdataIO\Tests; use NewsdataIO\Constants; +use NewsdataIO\Exception\NewsdataApiKeyLimitExceededError; +use NewsdataIO\Exception\NewsdataApiLimitExceededError; +use NewsdataIO\Exception\NewsdataRateLimitError; use PHPUnit\Framework\TestCase; /** - * A 429 covers three cases: a burst limit, a rate limit, and exhausted API - * credits. Only the first two are worth retrying — waiting out the backoff - * cannot conjure more credits. + * A 429 covers a burst limit, a rate limit, exhausted API credits, and a full + * set of real-time registrations. Only the first two are worth retrying — + * waiting out the backoff cannot conjure credits or free a registration slot. * * The retry loop itself needs a live socket, so these pin the code set and the * classification helper rather than driving cURL. @@ -23,7 +26,10 @@ public function testQuotaCodesMatchTheApi(): void // variant is accepted too because the spec is not exhaustive. $this->assertContains('ApiLimitExceeded', Constants::QUOTA_EXHAUSTED_CODES); $this->assertContains('ApiKeyLimitExceeded', Constants::QUOTA_EXHAUSTED_CODES); - $this->assertCount(2, Constants::QUOTA_EXHAUSTED_CODES); + // Not a credit code: every real-time registration the plan allows is + // in use, and only deleting one frees a slot. + $this->assertContains('RegistrationLimitExceeded', Constants::QUOTA_EXHAUSTED_CODES); + $this->assertCount(3, Constants::QUOTA_EXHAUSTED_CODES); } public function testTransientRateLimitCodesAreNotTreatedAsQuota(): void @@ -34,50 +40,83 @@ public function testTransientRateLimitCodesAreNotTreatedAsQuota(): void } } + public function testEachQuotaCodeMapsToItsOwnErrorClass(): void + { + // The two credit codes mean the credits are gone, but the remedy + // differs, so each gets its own class. Both subclass + // NewsdataRateLimitError, so code written against the old single class + // keeps working. + $this->assertSame( + NewsdataApiLimitExceededError::class, + Constants::QUOTA_EXHAUSTED_ERRORS['ApiLimitExceeded'] + ); + $this->assertSame( + NewsdataApiKeyLimitExceededError::class, + Constants::QUOTA_EXHAUSTED_ERRORS['ApiKeyLimitExceeded'] + ); + $this->assertTrue( + is_subclass_of(NewsdataApiLimitExceededError::class, NewsdataRateLimitError::class) + ); + $this->assertTrue( + is_subclass_of(NewsdataApiKeyLimitExceededError::class, NewsdataRateLimitError::class) + ); + // Registration slots are not credits, so this one keeps the base class. + $this->assertSame( + NewsdataRateLimitError::class, + Constants::QUOTA_EXHAUSTED_ERRORS['RegistrationLimitExceeded'] + ); + // Every code in the set must map to a class, or the throw would fall + // back to the base class and lose the distinction. + foreach (Constants::QUOTA_EXHAUSTED_CODES as $code) { + $this->assertArrayHasKey($code, Constants::QUOTA_EXHAUSTED_ERRORS); + } + } + /** * The classification helper is private; exercise it through reflection so * the body-shape handling (array and object decoding) is covered. * * @dataProvider quotaBodies * - * @param mixed $body + * @param mixed $body + * @param string|null $expected */ - public function testQuotaExhaustedDetection($body, bool $expected): void + public function testQuotaExhaustedDetection($body, ?string $expected): void { $api = new \NewsdataIO\NewsdataApi('key'); - $method = new \ReflectionMethod($api, 'quotaExhausted'); + $method = new \ReflectionMethod($api, 'quotaExhaustedError'); $method->setAccessible(true); $this->assertSame($expected, $method->invoke($api, $body)); } - /** @return array */ + /** @return array */ public static function quotaBodies(): array { return [ 'array, quota code' => [ ['status' => 'error', 'results' => ['code' => 'ApiLimitExceeded']], - true, + NewsdataApiLimitExceededError::class, ], 'array, key quota code' => [ ['status' => 'error', 'results' => ['code' => 'ApiKeyLimitExceeded']], - true, + NewsdataApiKeyLimitExceededError::class, ], 'array, transient code' => [ ['status' => 'error', 'results' => ['code' => 'RateLimitExceeded']], - false, + null, ], 'object, quota code' => [ (object) ['status' => 'error', 'results' => (object) ['code' => 'ApiLimitExceeded']], - true, + NewsdataApiLimitExceededError::class, ], 'object, transient code' => [ (object) ['status' => 'error', 'results' => (object) ['code' => 'TooManyRequests']], - false, + null, ], - 'no code at all' => [['status' => 'error', 'results' => []], false], - 'no results key' => [['status' => 'error'], false], - 'not a body' => ['plain string', false], + 'no code at all' => [['status' => 'error', 'results' => []], null], + 'no results key' => [['status' => 'error'], null], + 'not a body' => ['plain string', null], ]; } } diff --git a/tests/V2Test.php b/tests/V2Test.php new file mode 100644 index 0000000..23c234d --- /dev/null +++ b/tests/V2Test.php @@ -0,0 +1,218 @@ + */ + public static function v2Endpoints(): array + { + return [ + 'news' => ['news_v2', '2/news'], + 'market' => ['market_v2', '2/market'], + 'crypto' => ['crypto_v2', '2/crypto'], + 'sources' => ['sources_v2', '2/sources'], + 'count news' => ['count_news_v2', '2/count/news'], + 'count market' => ['count_market_v2', '2/count/market'], + 'count crypto' => ['count_crypto_v2', '2/count/crypto'], + ]; + } + + /** + * @dataProvider v2Endpoints + */ + public function testEachV2EndpointHasAVersionedPathAndFilterSet( + string $key, + string $path + ): void { + $this->assertSame($path, Constants::ENDPOINTS[$key]); + $this->assertArrayHasKey($key, Constants::FILTERS); + $this->assertNotEmpty(Constants::FILTERS[$key]); + } + + public function testBaseUrlNoLongerCarriesTheVersion(): void + { + // The version lives in the endpoint path so v1 and v2 can share a base. + $this->assertSame('https://newsdata.io/api/', Constants::BASE_URL); + $this->assertStringStartsWith('1/', Constants::ENDPOINTS['latest']); + $this->assertStringStartsWith('2/', Constants::ENDPOINTS['news_v2']); + } + + public function testEveryV2MethodIsExposed(): void + { + $api = new NewsdataApi('key'); + foreach ([ + 'get_news', 'get_market', 'get_crypto', 'get_sources', + 'get_count_news', 'get_count_market', 'get_count_crypto', + ] as $method) { + $this->assertTrue(method_exists($api, $method), $method . ' should exist'); + } + } + + public function testV2AcceptsTheSnakeCaseVocabulary(): void + { + $out = ParamValidator::validate('news_v2', [ + 'q_in_title' => 'tesla', + 'exclude_country' => 'cn', + 'source_url' => 'bbc.com', + 'source_priority' => 'top', + 'content' => true, + 'remove_duplicate' => true, + 'exclude_field' => 'description', + ]); + + $this->assertSame([ + 'q_in_title' => 'tesla', + 'exclude_country' => 'cn', + 'source_url' => 'bbc.com', + 'source_priority' => 'top', + 'content' => '1', + 'remove_duplicate' => '1', + 'exclude_field' => 'description', + ], $out); + } + + /** @return array}> */ + public static function v1Spellings(): array + { + return [ + 'qInTitle' => [['qInTitle' => 'x']], + 'domain' => [['domain' => 'bbc.com']], + 'domainurl' => [['domainurl' => 'bbc.com']], + 'excludedomain' => [['excludedomain' => 'bbc.com']], + 'excludedomainurl' => [['excludedomainurl' => 'bbc.com']], + 'prioritydomain' => [['prioritydomain' => 'top']], + 'full_content' => [['full_content' => true]], + 'removeduplicate' => [['removeduplicate' => true]], + 'excludefield' => [['excludefield' => 'description']], + ]; + } + + /** + * @dataProvider v1Spellings + * + * @param array $params + */ + public function testV2RejectsTheV1SpellingsItReplaced(array $params): void + { + $this->expectException(NewsdataValidationError::class); + ParamValidator::validate('news_v2', $params); + } + + public function testV1StillAcceptsTheV1Spellings(): void + { + $out = ParamValidator::validate('latest', [ + 'qInTitle' => 'x', + 'domain' => 'bbc.com', + 'full_content' => true, + ]); + $this->assertSame( + ['qintitle' => 'x', 'domain' => 'bbc.com', 'full_content' => '1'], + $out + ); + } + + public function testSourceUrlAndExcludeSourceUrlAreMutuallyExclusive(): void + { + $this->expectException(NewsdataValidationError::class); + ParamValidator::validate('news_v2', [ + 'source_url' => 'a.com', + 'exclude_source_url' => 'b.com', + ]); + } + + public function testV2QGroupIsMutuallyExclusive(): void + { + $this->expectException(NewsdataValidationError::class); + ParamValidator::validate('news_v2', ['q' => 'a', 'q_in_title' => 'b']); + } + + public function testV2CountryGroupIsMutuallyExclusive(): void + { + $this->expectException(NewsdataValidationError::class); + ParamValidator::validate('news_v2', ['country' => 'us', 'exclude_country' => 'cn']); + } + + public function testV2RawQueryIsCheckedAgainstTheV2Keyset(): void + { + $out = ParamValidator::validate('news_v2', [ + 'raw_query' => 'q_in_title=tesla&source_url=bbc.com', + ]); + $this->assertSame( + ['q_in_title' => 'tesla', 'source_url' => 'bbc.com'], + $out + ); + } + + public function testV2RawQueryRejectsAV1Name(): void + { + $this->expectException(NewsdataValidationError::class); + ParamValidator::validate('news_v2', ['raw_query' => 'qInTitle=tesla']); + } + + public function testCoinAndMarketIdKeepTheirNames(): void + { + $this->assertContains('coin', Constants::FILTERS['crypto_v2']); + $this->assertContains('coin', Constants::FILTERS['count_crypto_v2']); + $this->assertContains('market_id', Constants::FILTERS['market_v2']); + $this->assertContains('market_id', Constants::FILTERS['count_market_v2']); + } + + public function testV2SourcesAcceptsRawQuery(): void + { + // Unlike v1 sources, the v2 one takes a raw query too. + $out = ParamValidator::validate('sources_v2', ['raw_query' => 'country=us']); + $this->assertSame(['country' => 'us'], $out); + } + + // ---- excludedomainurl (v1) ------------------------------------------- + + /** @return array */ + public static function v1EndpointsTakingExcludeDomainUrl(): array + { + return [ + 'latest' => ['latest'], + 'archive' => ['archive'], + 'crypto' => ['crypto'], + 'market' => ['market'], + 'count' => ['count'], + 'crypto_count' => ['crypto_count'], + 'market_count' => ['market_count'], + ]; + } + + /** + * @dataProvider v1EndpointsTakingExcludeDomainUrl + */ + public function testExcludeDomainUrlIsAcceptedOnTheV1Endpoints(string $endpoint): void + { + $this->assertContains('excludedomainurl', Constants::FILTERS[$endpoint]); + } + + public function testExcludeDomainUrlIsNotASourcesFilter(): void + { + $this->assertNotContains('excludedomainurl', Constants::FILTERS['sources']); + } + + public function testExcludeDomainUrlJoinsTheV1DomainMutexGroup(): void + { + $this->expectException(NewsdataValidationError::class); + ParamValidator::validate('latest', [ + 'domain' => 'a.com', + 'excludedomainurl' => 'b.com', + ]); + } +}