diff --git a/README.md b/README.md index fb2a295..186ed29 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ -`newsdataapi` is the official Python SDK for the [NewsData.io](https://newsdata.io) REST API. It wraps every endpoint (`latest`, `archive`, `sources`, `crypto`, `market`, `count`, `crypto/count`, `market/count`) with consistent retry, pagination, and error handling. It also covers the real-time WebSocket service end to end with `NewsDataApiWebSocket`: register, list, and delete queries, and stream the matching news as it is published (sync or asyncio). +`newsdataapi` is the official Python SDK for the [NewsData.io](https://newsdata.io) REST API. It wraps every endpoint of both API versions, version 2 (`news`, `market`, `crypto`, `sources`, `count/news`, `count/market`, `count/crypto`) and version 1 (`latest`, `archive`, `crypto`, `market`, `sources`, `count`, `crypto/count`, `market/count`), with consistent retry, pagination, and error handling. It also covers the real-time WebSocket service end to end with `NewsDataApiWebSocket`: register, list, and delete queries, and stream the matching news as it is published (sync or asyncio). ## Installation @@ -35,9 +35,9 @@ Supports Python 3.8 through 3.14. The runtime dependencies are `requests` (REST) from newsdataapi import NewsDataApiClient with NewsDataApiClient("YOUR_API_KEY") as client: - response = client.latest_api(q="bitcoin", country="us", language="en") + response = client.news(q="bitcoin", country="us", language="en") for article in response["results"]: - print(article["title"], "-", article["link"]) + print(article["title"], "-", article["url"]) ``` The context-manager form closes the underlying HTTP session cleanly when the block exits. If you prefer not to use `with`, create the client directly and call `client.close()` yourself: @@ -47,49 +47,89 @@ from newsdataapi import NewsDataApiClient client = NewsDataApiClient("YOUR_API_KEY") try: - response = client.latest_api(q="bitcoin", country="us", language="en") + response = client.news(q="bitcoin", country="us", language="en") for article in response["results"]: - print(article["title"], "-", article["link"]) + print(article["title"], "-", article["url"]) finally: client.close() ``` +The version 1 methods are called the same way, for example `client.latest_api(q="bitcoin", country="us", language="en")`; their articles use the version 1 layout, with `link` instead of `url` (see "Version 1 and version 2" below). + ## Endpoints +Both API versions are available, and the client has methods for each. + +### API version 2 + +| Method | Endpoint | Notes | +|--------|----------|-------| +| `news()` | `/2/news` | Latest news, or historical news with `from_date` / `to_date` | +| `market()` | `/2/market` | Market / financial news | +| `crypto()` | `/2/crypto` | Cryptocurrency news | +| `sources()` | `/2/sources` | Available news sources | +| `count_news()` | `/2/count/news` | News counts per time interval | +| `count_market()` | `/2/count/market` | Market news counts per time interval | +| `count_crypto()` | `/2/count/crypto` | Crypto news counts per time interval | + +The version 2 count methods return `total_results` and a `results` list with one `{"date_time": ..., "count": ...}` entry per `interval` (`month`, `day` or `hour`). They page like the news methods, so `scroll` and `paginate` work on them too. + +### API version 1 + | Method | Endpoint | Notes | |--------|----------|-------| -| `latest_api()` | `/latest` | Real-time news | -| `archive_api()` | `/archive` | Historical news | -| `sources_api()` | `/sources` | Available news sources | -| `crypto_api()` | `/crypto` | Cryptocurrency news | -| `market_api()` | `/market` | Market / financial news | -| `count_api(from_date, to_date)` | `/count` | Aggregate counts | -| `crypto_count_api(from_date, to_date)` | `/crypto/count` | Aggregate crypto counts | -| `market_count_api(from_date, to_date)` | `/market/count` | Aggregate market counts | +| `latest_api()` | `/1/latest` | Real-time news | +| `archive_api()` | `/1/archive` | Historical news | +| `sources_api()` | `/1/sources` | Available news sources | +| `crypto_api()` | `/1/crypto` | Cryptocurrency news | +| `market_api()` | `/1/market` | Market / financial news | +| `count_api(from_date, to_date)` | `/1/count` | Aggregate counts | +| `crypto_count_api(from_date, to_date)` | `/1/crypto/count` | Aggregate crypto counts | +| `market_count_api(from_date, to_date)` | `/1/market/count` | Aggregate market counts | -All endpoint parameters are keyword-only (except the required `from_date` / `to_date` on the count endpoints). Most accept either a single string or a `list[str]`; lists are comma-joined for the API. The real-time WebSocket endpoints are covered by `NewsDataApiWebSocket` (see below). +All parameters are keyword-only, except the required `from_date` / `to_date` of the version 1 count methods. Most accept either a single string or a `list[str]`; lists are comma-joined for the API. The real-time WebSocket endpoints are covered by `NewsDataApiWebSocket` (see below). See the [NewsData.io documentation](https://newsdata.io/documentation) — or the [OpenAPI 3.1 spec](https://newsdata.io/openapi.json) — for the full parameter reference. +## Version 1 and version 2 + +Both versions serve the same news. They differ in method names, parameter names and response layout: + +| Version 1 | Version 2 | +|-----------|-----------| +| `latest_api()`, `archive_api()` | `news()` | +| `crypto_api()`, `market_api()`, `sources_api()` | `crypto()`, `market()`, `sources()` | +| `count_api()`, `crypto_count_api()`, `market_count_api()` | `count_news()`, `count_crypto()`, `count_market()` | +| `qInTitle`, `qInMeta` | `q_in_title`, `q_in_meta` | +| `domainurl`, `excludedomainurl`, `excludedomain` | `source_url`, `exclude_source_url`, `exclude_source_url` | +| `domain` | `source_url`, with the source's URL (`bbc.com`) instead of its id (`bbc`) | +| `prioritydomain` | `source_priority` | +| `excludecountry`, `excludecategory`, `excludelanguage` | `exclude_country`, `exclude_category`, `exclude_language` | +| `excludefield`, `removeduplicate` | `exclude_field`, `remove_duplicate` | +| `full_content` | `content` | +| `totalResults`, `nextPage` in the response | `total_results`, `next_page` | + +Version 2 articles use `url` instead of `link`, and group related fields under `media`, `source` and `ai`. The version 2 count methods take `from_date` and `to_date` as optional keyword arguments; the version 1 count methods require them. + ## Three ways to consume an endpoint ```python # 1. Single request (the default). -response = client.latest_api(q="news") +response = client.news(q="news") -# 2. Auto-merge — follow nextPage cursors and return one combined dict. -merged = client.latest_api(q="news", scroll=True, max_result=200) +# 2. Auto-merge — follow next_page cursors and return one combined dict. +merged = client.news(q="news", scroll=True, max_result=200) # 3. Iterate one response per page (a generator). -for page in client.latest_api(q="news", paginate=True, max_pages=5): +for page in client.news(q="news", paginate=True, max_pages=5): process(page["results"]) ``` -`scroll` and `paginate` are mutually exclusive. `scroll=True` truncates strictly to `max_result`; `paginate=True` stops at `max_pages` or when the API returns no `nextPage`. +`scroll` and `paginate` are mutually exclusive. `scroll=True` truncates strictly to `max_result`; `paginate=True` stops at `max_pages` or when the API returns no `next_page`. The version 1 methods support the same three modes (for example `client.latest_api(q="news", paginate=True)`), following `nextPage` instead. ## Real-time news (WebSocket) -Requires Python 3.10 or newer. Register a query first — the returned `registration_id` identifies it from then on: +Requires Python 3.10 or newer. The real-time service is part of API version 2. Register a query first — the returned `registration_id` identifies it from then on: ```python from newsdataapi import NewsDataApiClient, NewsDataApiWebSocket @@ -100,14 +140,14 @@ response = ws.websocket_register(q="bitcoin", language="en") registration_id = response["results"]["registration_id"] ``` -`websocket_register` accepts the familiar filter parameters (`q`, `country`, `language`, `domain`, …). Registering an identical query twice raises `NewsdataAPIError` with `status_code=409` — the existing id is in `e.response_body["results"]["registration_id"]`. `websocket_fetch()` lists every registered query, and `websocket_delete(registration_id)` removes one. +`websocket_register` takes the same filter parameters as `news()`, under the same names (`q`, `q_in_title`, `country`, `exclude_country`, `source_url`, `content`, `exclude_field`, `timezone`, …); the date, paging and sorting parameters, `id` and `url` don't apply to a standing query. Registering an identical query twice raises `NewsdataAPIError` with `status_code=409` — the existing id is in `e.response_body["results"]["registration_id"]`. `websocket_fetch()` lists every registered query: its `results` list has one entry per query, with the `registration_id`, the filters it was registered with (`query`), the number of devices streaming it now (`active_clients`) and when a device last connected (`last_used`, in UTC). `websocket_delete(registration_id)` removes one. -Then stream — each yielded response has the familiar `status` / `totalResults` / `results` shape: +Then stream. Each yielded response has `status`, `total_results` and `results` keys, and its articles have the same layout as `news()` results (`id`, `url`, `published_at`, …, with related fields grouped under `media`, `source` and `ai`); the registration's `exclude_field` and `timezone` apply to them: ```python for response in ws.stream(registration_id): for article in response["results"]: - print(article["title"], "-", article["link"]) + print(article["title"], "-", article["url"]) ``` Use it as a context manager to close the connection promptly when you stop early (otherwise it closes when iteration ends): @@ -115,7 +155,7 @@ Use it as a context manager to close the connection promptly when you stop early ```python with NewsDataApiWebSocket(client) as ws: for response in ws.stream(registration_id): - print(response["totalResults"]) + print(response["total_results"]) break ``` @@ -128,7 +168,7 @@ async def main(): async with NewsDataApiWebSocket(client) as ws: async for response in ws.stream_async(registration_id): for article in response["results"]: - print(article["title"], "-", article["link"]) + print(article["title"], "-", article["url"]) asyncio.run(main()) ``` @@ -177,7 +217,7 @@ from newsdataapi import ( ) try: - client.latest_api(q="news") + client.news(q="news") except NewsdataAuthError as e: print(f"bad API key (HTTP {e.status_code})") except NewsdataApiKeyLimitExceededError: @@ -224,7 +264,7 @@ client = NewsDataApiClient(apikey, folder_path="./out") client.save_to_csv(response, filename="latest_news") ``` -`save_to_csv` returns a `pathlib.Path`. Cell values that are dicts or lists are stringified (`key:value,key:value` for dicts, comma-joined for lists). Quoting is delegated to the standard `csv.DictWriter`, so the output round-trips correctly through any CSV reader. +`save_to_csv` returns a `pathlib.Path`. Nested fields get one column each, named with dots (`source.name`, `ai.sentiment.label`); lists are comma-joined, and lists of objects are written as JSON. Responses from the version 1 methods keep the version 1 format: dict and list cells are stringified (`key:value,key:value` for dicts, comma-joined for lists). Quoting is delegated to the standard `csv.DictWriter`, so the output round-trips correctly through any CSV reader. The function is also importable as a standalone: @@ -254,9 +294,9 @@ client = NewsDataApiClient( ) ``` -`base_url` (and `set_base_url()`) is the API root without a version segment; the default is `https://newsdata.io/api`, and the client adds the version itself. Before 0.4.0 it included the version (`https://newsdata.io/api/1/`), so drop the trailing `/1/` if you override it. +`base_url` (and `set_base_url()`) is the API root without a version segment; the default is `https://newsdata.io/api`, and the client adds `/1/...` or `/2/...` itself. Before 0.4.0 it included the version (`https://newsdata.io/api/1/`), so drop the trailing `/1/` if you override it. -A request that fails with a server error, a rate limit, or a network error is attempted 5 times by default, sleeping 2 s, 4 s, 8 s and 16 s between attempts (30 s in total; a single sleep never exceeds `retry_backoff_max`). A 429 response is instead retried after the server's `Retry-After` plus one second (both integer-seconds and HTTP-date forms are parsed); when `Retry-After` is longer than `retry_backoff_max`, the client does not wait and raises `NewsdataRateLimitError` with `retry_after` set. The API key is redacted in log output. +A request that fails with a server error, a rate limit, or a network error is attempted 5 times by default, sleeping 2 s, 4 s, 8 s and 16 s between attempts (30 s in total; a single sleep never exceeds `retry_backoff_max`). A 429 response is instead retried after the server's `Retry-After` plus one second (both integer-seconds and HTTP-date forms are parsed); when `Retry-After` is longer than `retry_backoff_max`, the client does not wait and raises `NewsdataRateLimitError` with `retry_after` set. A 429 that waiting cannot fix is raised at once, without retrying: `ApiLimitExceeded` and `ApiKeyLimitExceeded` (credits used up) and `RegistrationLimitExceeded` (all the real-time registrations the plan allows are in use; delete one to free a slot). The API key is redacted in log output. ## Development diff --git a/examples/websocket_usage.py b/examples/websocket_usage.py index dfc4359..56915f8 100644 --- a/examples/websocket_usage.py +++ b/examples/websocket_usage.py @@ -67,7 +67,7 @@ def sync_example() -> None: with NewsDataApiWebSocket(client) as ws: for response in ws.stream(registration_id): for article in response["results"]: - print(article.get("title"), "-", article.get("link")) + print(article.get("title"), "-", article.get("url")) async def async_example() -> None: @@ -77,7 +77,7 @@ async def async_example() -> None: async with NewsDataApiWebSocket(client) as ws: async for response in ws.stream_async(registration_id): for article in response["results"]: - print(article.get("title"), "-", article.get("link")) + print(article.get("title"), "-", article.get("url")) def main() -> None: diff --git a/src/newsdataapi/__init__.py b/src/newsdataapi/__init__.py index 1047bf8..f856e98 100644 --- a/src/newsdataapi/__init__.py +++ b/src/newsdataapi/__init__.py @@ -17,7 +17,7 @@ ) from .websocket import NewsDataApiWebSocket -__version__ = "0.4.1" +__version__ = "0.4.2" __all__ = [ "NewsDataApiClient", diff --git a/src/newsdataapi/client.py b/src/newsdataapi/client.py index 1fac64c..7285a67 100644 --- a/src/newsdataapi/client.py +++ b/src/newsdataapi/client.py @@ -116,6 +116,8 @@ _QUOTA_EXHAUSTED_ERRORS: dict[str, type[NewsdataRateLimitError]] = { "ApiLimitExceeded": NewsdataApiLimitExceededError, "ApiKeyLimitExceeded": NewsdataApiKeyLimitExceededError, + # every real-time registration the plan allows is in use: only deleting one frees a slot + "RegistrationLimitExceeded": NewsdataRateLimitError, } diff --git a/src/newsdataapi/constants.py b/src/newsdataapi/constants.py index 3f65e88..a169636 100644 --- a/src/newsdataapi/constants.py +++ b/src/newsdataapi/constants.py @@ -15,9 +15,6 @@ COUNT_ENDPOINT = "1/count" CRYPTO_COUNT_ENDPOINT = "1/crypto/count" MARKET_COUNT_ENDPOINT = "1/market/count" -WEBSOCKET_REGISTER_ENDPOINT = "1/websocket/register" -WEBSOCKET_FETCH_ENDPOINT = "1/websocket/fetch" -WEBSOCKET_DELETE_ENDPOINT = "1/websocket/delete" # v2 endpoint paths. NEWS_V2_ENDPOINT = "2/news" @@ -27,6 +24,9 @@ COUNT_NEWS_V2_ENDPOINT = "2/count/news" COUNT_MARKET_V2_ENDPOINT = "2/count/market" COUNT_CRYPTO_V2_ENDPOINT = "2/count/crypto" +WEBSOCKET_REGISTER_ENDPOINT = "2/websocket/register" +WEBSOCKET_FETCH_ENDPOINT = "2/websocket/fetch" +WEBSOCKET_DELETE_ENDPOINT = "2/websocket/delete" # HTTP defaults. DEFAULT_REQUEST_TIMEOUT = 30 # seconds @@ -37,7 +37,7 @@ # Real-time WebSocket defaults (newsdataapi.NewsDataApiWebSocket). WS_BASE_URL = "wss://ws.newsdata.io/ws/event" -WS_NEWS_TYPE = "latest" # feed a registered query matches against +WS_NEWS_TYPE = "news" # feed a registered query matches against (only news so far) WS_POLICY_VIOLATION = 1008 # close code for a permanent connection rejection WS_RECONNECT_DELAY = 1.0 # seconds before the first reconnect; doubles each retry WS_RECONNECT_DELAY_MAX = 30.0 # cap on the reconnect delay diff --git a/src/newsdataapi/exceptions.py b/src/newsdataapi/exceptions.py index f9576ed..fb468cd 100644 --- a/src/newsdataapi/exceptions.py +++ b/src/newsdataapi/exceptions.py @@ -54,7 +54,8 @@ class NewsdataAuthError(NewsdataAPIError): class NewsdataRateLimitError(NewsdataAPIError): """Raised on 429 responses when retries are exhausted, or at once when the ``Retry-After`` wait is longer than the client's - ``retry_backoff_max``. + ``retry_backoff_max`` or the error code is ``RegistrationLimitExceeded`` + (every real-time registration the plan allows is in use). Attributes: retry_after: Seconds to wait before retrying, parsed from the diff --git a/src/newsdataapi/websocket.py b/src/newsdataapi/websocket.py index b2bd6bf..cacff34 100644 --- a/src/newsdataapi/websocket.py +++ b/src/newsdataapi/websocket.py @@ -190,24 +190,22 @@ def websocket_register( self, *, q: str | None = None, - qInTitle: str | None = None, - qInMeta: str | None = None, + q_in_title: str | None = None, + q_in_meta: str | None = None, country: str | list[str] | None = None, - excludecountry: str | list[str] | None = None, + exclude_country: str | list[str] | None = None, category: str | list[str] | None = None, - excludecategory: str | list[str] | None = None, + exclude_category: str | list[str] | None = None, language: str | list[str] | None = None, - excludelanguage: str | list[str] | None = None, - domain: str | list[str] | None = None, - domainurl: str | list[str] | None = None, - excludedomain: str | list[str] | None = None, - excludedomainurl: str | list[str] | None = None, - prioritydomain: str | None = None, + exclude_language: str | list[str] | None = None, + source_url: str | list[str] | None = None, + exclude_source_url: str | list[str] | None = None, + source_priority: str | None = None, timezone: str | None = None, - full_content: bool | None = None, + content: bool | None = None, image: bool | None = None, video: bool | None = None, - removeduplicate: bool | None = None, + remove_duplicate: bool | None = None, tag: str | list[str] | None = None, sentiment: str | None = None, sentiment_score: float | None = None, @@ -215,7 +213,7 @@ def websocket_register( organization: str | list[str] | None = None, creator: str | list[str] | None = None, datatype: str | list[str] | None = None, - excludefield: str | list[str] | None = None, + exclude_field: str | list[str] | None = None, raw_query: str | None = None, ) -> dict[str, Any]: """Register a real-time WebSocket query. @@ -226,24 +224,22 @@ def websocket_register( params = _validate_params( { "q": q, - "qInTitle": qInTitle, - "qInMeta": qInMeta, + "q_in_title": q_in_title, + "q_in_meta": q_in_meta, "country": country, - "excludecountry": excludecountry, + "exclude_country": exclude_country, "category": category, - "excludecategory": excludecategory, + "exclude_category": exclude_category, "language": language, - "excludelanguage": excludelanguage, - "domain": domain, - "domainurl": domainurl, - "excludedomain": excludedomain, - "excludedomainurl": excludedomainurl, - "prioritydomain": prioritydomain, + "exclude_language": exclude_language, + "source_url": source_url, + "exclude_source_url": exclude_source_url, + "source_priority": source_priority, "timezone": timezone, - "full_content": full_content, + "content": content, "image": image, "video": video, - "removeduplicate": removeduplicate, + "remove_duplicate": remove_duplicate, "tag": tag, "sentiment": sentiment, "sentiment_score": sentiment_score, @@ -251,7 +247,7 @@ def websocket_register( "organization": organization, "creator": creator, "datatype": datatype, - "excludefield": excludefield, + "exclude_field": exclude_field, "raw_query": raw_query, } ) @@ -263,7 +259,7 @@ def websocket_register( def websocket_fetch(self) -> dict[str, Any]: """List the registered WebSocket queries. - ``response["results"]["queries"]`` holds one entry per query. + ``response["results"]`` holds one entry per query. """ return self.api_client._request(constants.WEBSOCKET_FETCH_ENDPOINT, {}) @@ -299,7 +295,7 @@ def _next_delay(self, delay: float) -> float: def stream(self, registration_id: str) -> Iterator[dict[str, Any]]: """Connect and yield each response for ``registration_id`` as it - arrives. Responses have the familiar ``status`` / ``totalResults`` / + arrives. Responses have the ``status`` / ``total_results`` / ``results`` shape.""" _check_registration_id(registration_id) url = self._url(registration_id) diff --git a/tests/test_unit.py b/tests/test_unit.py index f9d6d27..43e3882 100644 --- a/tests/test_unit.py +++ b/tests/test_unit.py @@ -1064,6 +1064,7 @@ def test_429_retry_after_above_backoff_max_raises_without_retry( [ ("ApiLimitExceeded", NewsdataApiLimitExceededError), ("ApiKeyLimitExceeded", NewsdataApiKeyLimitExceededError), + ("RegistrationLimitExceeded", NewsdataRateLimitError), ], ) def test_429_quota_exhausted_raises_without_retry( @@ -1073,8 +1074,9 @@ def test_429_quota_exhausted_raises_without_retry( mocked_responses: responses.RequestsMock, no_sleep: None, ) -> None: - """A 429 whose error code means exhausted credits is never retried, - and raises the specific subclass for that code.""" + """A 429 whose error code waiting cannot fix (exhausted credits, every + real-time registration in use) is never retried, and raises the + exception class for that code.""" body = {"status": "error", "results": {"message": "limit", "code": code}} mocked_responses.get(LATEST_URL, json=body, status=429) with pytest.raises(expected_exc) as exc_info: @@ -1912,9 +1914,9 @@ def test_v2_scroll_and_paginate_mutually_exclusive(client: NewsDataApiClient) -> # WebSocket query management (register / fetch / delete) # =========================================================================== -WS_REGISTER_URL = "https://newsdata.io/api/1/websocket/register" -WS_FETCH_URL = "https://newsdata.io/api/1/websocket/fetch" -WS_DELETE_URL = "https://newsdata.io/api/1/websocket/delete" +WS_REGISTER_URL = "https://newsdata.io/api/2/websocket/register" +WS_FETCH_URL = "https://newsdata.io/api/2/websocket/fetch" +WS_DELETE_URL = "https://newsdata.io/api/2/websocket/delete" # NewsDataApiWebSocket can't be constructed below Python 3.10. requires_websocket = pytest.mark.skipif( @@ -1960,7 +1962,7 @@ def test_websocket_register_posts_query_params( @requires_websocket -def test_websocket_register_always_sends_news_type_latest( +def test_websocket_register_always_sends_news_type_news( client: NewsDataApiClient, mocked_responses: responses.RequestsMock, ) -> None: @@ -1972,7 +1974,7 @@ def test_websocket_register_always_sends_news_type_latest( NewsDataApiWebSocket(client).websocket_register(q="nvidia") sent_url = mocked_responses.calls[0].request.url assert sent_url is not None - assert "news_type=latest" in sent_url + assert "news_type=news" in sent_url @requires_websocket @@ -1981,7 +1983,7 @@ def test_websocket_register_mutex_validation_applies( ) -> None: """The shared mutex groups guard register too — no request is sent.""" with pytest.raises(NewsdataValidationError): - NewsDataApiWebSocket(client).websocket_register(q="a", qInTitle="b") + NewsDataApiWebSocket(client).websocket_register(q="a", q_in_title="b") @requires_websocket @@ -1998,7 +2000,7 @@ def test_websocket_register_raw_query( sent_url = mocked_responses.calls[0].request.url assert sent_url is not None assert "q=pizza" in sent_url - assert "news_type=latest" in sent_url + assert "news_type=news" in sent_url @requires_websocket @@ -2011,7 +2013,16 @@ def test_websocket_register_raw_query_rejects_unknown_param( @requires_websocket -def test_websocket_register_sends_excludedomainurl( +def test_websocket_register_raw_query_rejects_v1_name( + client: NewsDataApiClient, +) -> None: + """Register takes the v2 parameter names only — no request is sent.""" + with pytest.raises(NewsdataValidationError): + NewsDataApiWebSocket(client).websocket_register(raw_query="qInTitle=pizza") + + +@requires_websocket +def test_websocket_register_sends_exclude_source_url( client: NewsDataApiClient, mocked_responses: responses.RequestsMock, ) -> None: @@ -2021,11 +2032,11 @@ def test_websocket_register_sends_excludedomainurl( status=200, ) NewsDataApiWebSocket(client).websocket_register( - q="pizza", excludedomainurl=["bbc.com", "cnn.com"] + q="pizza", exclude_source_url=["bbc.com", "cnn.com"] ) sent_url = mocked_responses.calls[0].request.url assert sent_url is not None - assert "excludedomainurl=bbc.com%2Ccnn.com" in sent_url + assert "exclude_source_url=bbc.com%2Ccnn.com" in sent_url @requires_websocket @@ -2089,23 +2100,22 @@ def test_websocket_fetch_returns_queries( WS_FETCH_URL, json={ "status": "success", - "totalQueries": 1, - "results": { - "queries": [ - { - "registration_id": "abc123", - "active_clients": 2, - "news_type": "latest", - "query": {"q": "pizza"}, - } - ] - }, + "total_results": 1, + "results": [ + { + "registration_id": "abc123", + "active_clients": 2, + "last_used": "2026-11-20T10:15:00Z", + "news_type": "news", + "query": {"q": "pizza"}, + } + ], }, status=200, ) response = NewsDataApiWebSocket(client).websocket_fetch() - assert response["totalQueries"] == 1 - assert response["results"]["queries"][0]["registration_id"] == "abc123" + assert response["total_results"] == 1 + assert response["results"][0]["registration_id"] == "abc123" sent_url = mocked_responses.calls[0].request.url assert sent_url is not None assert "apikey=test_key_xxx" in sent_url diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 10363a5..20ff5dd 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -33,7 +33,7 @@ def _news(*titles: str) -> str: return json.dumps( { "status": "success", - "totalResults": len(titles), + "total_results": len(titles), "results": [{"title": t} for t in titles], } ) @@ -198,7 +198,7 @@ def test_yields_whole_server_responses(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(CONNECT, _FakeConnect(([_news("A", "B"), _news("C")], None))) got = list(_ws(reconnect=False).stream("r")) assert [r["status"] for r in got] == ["success", "success"] - assert [r["totalResults"] for r in got] == [2, 1] + assert [r["total_results"] for r in got] == [2, 1] assert [[a["title"] for a in r["results"]] for r in got] == [["A", "B"], ["C"]] @@ -206,7 +206,7 @@ def test_malformed_frames_are_skipped(monkeypatch: pytest.MonkeyPatch) -> None: frames = ["not json", json.dumps(["not", "a", "dict"]), _news("A")] monkeypatch.setattr(CONNECT, _FakeConnect((frames, None))) got = list(_ws(reconnect=False).stream("r")) - assert [r["totalResults"] for r in got] == [1] + assert [r["total_results"] for r in got] == [1] @pytest.mark.parametrize("bad_id", ["", None, 123]) @@ -533,7 +533,7 @@ async def go() -> list[dict]: return [r async for r in _ws(reconnect=False).stream_async("r")] got = asyncio.run(go()) - assert [r["totalResults"] for r in got] == [2, 1] + assert [r["total_results"] for r in got] == [2, 1] assert [[a["title"] for a in r["results"]] for r in got] == [["A", "B"], ["C"]]