diff --git a/README.md b/README.md index 9267c1f..17f8b05 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 (`news`, `market`, `crypto`, `sources`, `count/news`, `count/market`, `count/crypto`) 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,9 +47,9 @@ 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() ``` @@ -58,34 +58,55 @@ finally: | 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 | +| `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 | -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. 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). + +The 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. 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. +## Upgrading from 0.3.x + +The old `*_api()` methods still work, but they are deprecated and will be removed in a future release. Each one emits a `DeprecationWarning` naming its replacement: + +| Old | New | +|-----|-----| +| `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` | + +The article layout changed too: for example `url` replaces `link`, and related fields are grouped under `media`, `source` and `ai`. On the count methods `from_date` and `to_date` are now optional keyword arguments. + ## 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`. ## Real-time news (WebSocket) @@ -100,9 +121,9 @@ 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 parameter names as the deprecated `*_api()` methods (`q`, `qInTitle`, `country`, `excludecountry`, `domainurl`, `full_content`, …), not the names `news()` uses. 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. -Then stream — each yielded response has the familiar `status` / `totalResults` / `results` shape: +Then stream. Each yielded response has `status`, `totalResults` and `results` keys, and its articles carry the same fields the deprecated `*_api()` methods return (`article_id`, `link`, `pubDate`, …), not the `news()` layout: ```python for response in ws.stream(registration_id): @@ -177,7 +198,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 +245,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 deprecated `*_api()` methods keep the old 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: @@ -248,13 +269,15 @@ client = NewsDataApiClient( proxies={"https": "..."}, # passed with every request accept_language="en", # Accept-Language header include_headers=False, # if True, returned dicts include response_headers - base_url="...", # override for staging / proxied environments + base_url="...", # API root; override for staging / proxied environments session=my_session, # inject your own requests.Session folder_path="./out", # default folder for save_to_csv; default None ) ``` -Defaults sleep about a minute total across all retries (2 s → 4 s → 8 s → 16 s → 32 s, capped at 60 s); 429 responses honor `Retry-After` (both integer-seconds and HTTP-date forms are parsed). The API key is redacted in log output. +`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. ## Development diff --git a/examples/basic_usage.py b/examples/basic_usage.py index e5032aa..f34fd2e 100644 --- a/examples/basic_usage.py +++ b/examples/basic_usage.py @@ -16,6 +16,7 @@ from __future__ import annotations +import datetime import os from pathlib import Path @@ -42,29 +43,32 @@ def main() -> None: # the block exits. You can also call ``client.close()`` yourself. with NewsDataApiClient(apikey, folder_path=out_dir) as client: # 1. Single request — the most common pattern. - response = client.latest_api(q="bitcoin", country="us", language="en") + response = client.news(q="bitcoin", country="us", language="en") results = response["results"] print( - f"latest: {len(results)} articles, " - f"total available: {response.get('totalResults')}" + f"news: {len(results)} articles, " + f"total available: {response.get('total_results')}" ) # 2. Pagination — yields one response per page, capped at max_pages. for page_index, page in enumerate( - client.crypto_api(q="ethereum", paginate=True, max_pages=3), + client.crypto(q="ethereum", paginate=True, max_pages=3), start=1, ): print(f" crypto page {page_index}: {len(page['results'])} articles") - # 3. Scroll — auto-follows nextPage cursors and merges into one dict. - merged = client.archive_api( + # 3. Scroll — auto-follows next_page cursors and merges into one dict. + # ``from_date`` / ``to_date`` select historical news. + now = datetime.datetime.now(tz=datetime.timezone.utc) + date_format = "%Y-%m-%d 00:00:00" + merged = client.news( q="apple", - from_date="2024-01-01 00:00:00", - to_date="2024-01-31 00:00:00", + from_date=(now - datetime.timedelta(days=7)).strftime(date_format), + to_date=(now - datetime.timedelta(days=1)).strftime(date_format), scroll=True, max_result=50, ) - print(f"scrolled archive: {len(merged['results'])} articles") + print(f"scrolled news: {len(merged['results'])} articles") # 4. Persist results to CSV. ``folder_path`` was set on the client, so # we don't pass it again here. @@ -81,7 +85,7 @@ def example_error_handling(apikey: str) -> None: """ with NewsDataApiClient(apikey) as client: try: - client.latest_api(q="news") + client.news(q="news") except NewsdataAuthError as e: print(f"API key rejected (HTTP {e.status_code})") except NewsdataRateLimitError as e: diff --git a/pyproject.toml b/pyproject.toml index b8c72d9..850fa85 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,6 +91,11 @@ addopts = [ "--strict-markers", "-m", "not integration", ] +# The v1 methods are deprecated but most of the suite still exercises them; +# keep their warning out of the test summary. +filterwarnings = [ + "ignore:.*is deprecated and will be removed in a future release:DeprecationWarning", +] [tool.ruff] line-length = 100 diff --git a/src/newsdataapi/__init__.py b/src/newsdataapi/__init__.py index 31b291c..206e67a 100644 --- a/src/newsdataapi/__init__.py +++ b/src/newsdataapi/__init__.py @@ -17,7 +17,7 @@ ) from .websocket import NewsDataApiWebSocket -__version__ = "0.3.5" +__version__ = "0.4.0" __all__ = [ "NewsDataApiClient", diff --git a/src/newsdataapi/client.py b/src/newsdataapi/client.py index 8b5cf11..714814d 100644 --- a/src/newsdataapi/client.py +++ b/src/newsdataapi/client.py @@ -5,6 +5,7 @@ import logging import os import time +import warnings from collections.abc import Iterator, Mapping from datetime import datetime, timezone from email.utils import parsedate_to_datetime @@ -35,7 +36,17 @@ # Parameter validation. # --------------------------------------------------------------------------- -_BOOL_PARAMS = frozenset({"full_content", "image", "video", "removeduplicate"}) +_BOOL_PARAMS = frozenset( + { + "full_content", + "image", + "video", + "removeduplicate", + # v2 names + "content", + "remove_duplicate", + } +) _INT_PARAMS = frozenset({"size"}) _FLOAT_PARAMS = frozenset({"sentiment_score"}) _STRING_PARAMS = frozenset( @@ -72,6 +83,16 @@ "interval", "creator", "datatype", + # v2 names + "q_in_title", + "q_in_meta", + "source_url", + "exclude_source_url", + "source_priority", + "exclude_country", + "exclude_category", + "exclude_language", + "exclude_field", } ) @@ -85,6 +106,12 @@ ("category", "excludecategory"), ("language", "excludelanguage"), ("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"), ) _QUOTA_EXHAUSTED_ERRORS: dict[str, type[NewsdataRateLimitError]] = { @@ -112,7 +139,8 @@ def _validate_params(user_params: Mapping[str, Any]) -> dict[str, Any]: ``domain``/``domainurl``/``excludedomain``/``excludedomainurl``) are enforced client-side; setting more than one from any group raises - ``NewsdataValidationError`` before the request leaves. + ``NewsdataValidationError`` before the request leaves. The v2 names + of these groups are enforced the same way. * ``sentiment_score`` requires ``sentiment`` to be set; passing ``sentiment_score`` alone raises ``NewsdataValidationError``. @@ -333,6 +361,16 @@ def _redact_url(url: str, param: str = "apikey") -> str: return urlunparse(parsed._replace(query=urlencode(pairs))) +def _warn_deprecated(old: str, new: str) -> None: + """Warn that the v1 method ``old`` is deprecated in favor of ``new``.""" + warnings.warn( + f"{old}() is deprecated and will be removed in a future release; " + f"use {new}() instead.", + DeprecationWarning, + stacklevel=3, # point at the code that called the deprecated method + ) + + # --------------------------------------------------------------------------- # Client. # --------------------------------------------------------------------------- @@ -344,7 +382,11 @@ class NewsDataApiClient: Example:: with NewsDataApiClient("YOUR_API_KEY") as client: - response = client.latest_api(q="bitcoin", country="us") + response = client.news(q="bitcoin", country="us") + + The ``*_api`` methods (:meth:`latest_api`, :meth:`archive_api`, ...) are + deprecated; use :meth:`news`, :meth:`market`, :meth:`crypto`, + :meth:`sources` and the ``count_*`` methods instead. The client owns a single :class:`requests.Session` for connection pooling. Pass ``session=...`` to inject your own (it will not be closed @@ -352,9 +394,9 @@ class NewsDataApiClient: :meth:`close` explicitly, to release the session. All endpoint parameters are keyword-only except for the required - ``from_date`` / ``to_date`` on the count endpoints. Most parameters - accept either a single string or a ``list[str]``; lists are - comma-joined before being sent to the API. + ``from_date`` / ``to_date`` on the deprecated ``*count_api`` methods. + Most parameters accept either a single string or a ``list[str]``; lists + are comma-joined before being sent to the API. """ proxies: dict[str, Any] | None @@ -461,7 +503,9 @@ def __del__(self) -> None: def set_base_url(self, new_base_url: str) -> None: """Override the base URL (e.g. for a staging or proxied environment). - The new URL is normalized to end with a trailing slash so that + This is the API root without a version segment (the default is + ``https://newsdata.io/api``); endpoint paths add the version. The + new URL is normalized to end with a trailing slash so that :func:`urllib.parse.urljoin` resolves endpoint paths correctly. """ if not isinstance(new_base_url, str) or not new_base_url: @@ -516,11 +560,15 @@ def latest_api( ) -> dict[str, Any] | Iterator[dict[str, Any]]: """Fetch latest news. + .. deprecated:: 0.4.0 + Use :meth:`news` instead. + See https://newsdata.io/documentation for parameter descriptions. Returns a dict by default, the merged dict if ``scroll=True``, or an iterator of per-page dicts if ``paginate=True``. """ + _warn_deprecated("latest_api", "news") return self._dispatch( constants.LATEST_ENDPOINT, { @@ -610,8 +658,12 @@ def archive_api( ) -> dict[str, Any] | Iterator[dict[str, Any]]: """Fetch news from the archive. + .. deprecated:: 0.4.0 + Use :meth:`news` instead. + See https://newsdata.io/documentation for parameter descriptions. """ + _warn_deprecated("archive_api", "news") return self._dispatch( constants.ARCHIVE_ENDPOINT, { @@ -669,9 +721,13 @@ def sources_api( ) -> dict[str, Any]: """List available news sources. + .. deprecated:: 0.4.0 + Use :meth:`sources` instead. + Sources is a single-page endpoint; ``scroll`` and ``paginate`` are not supported. """ + _warn_deprecated("sources_api", "sources") params = _validate_params( { "country": country, @@ -722,8 +778,12 @@ def crypto_api( ) -> dict[str, Any] | Iterator[dict[str, Any]]: """Fetch cryptocurrency news. + .. deprecated:: 0.4.0 + Use :meth:`crypto` instead. + See https://newsdata.io/documentation for parameter descriptions. """ + _warn_deprecated("crypto_api", "crypto") return self._dispatch( constants.CRYPTO_ENDPOINT, { @@ -806,8 +866,12 @@ def market_api( ) -> dict[str, Any] | Iterator[dict[str, Any]]: """Fetch market / financial news. + .. deprecated:: 0.4.0 + Use :meth:`market` instead. + See https://newsdata.io/documentation for parameter descriptions. """ + _warn_deprecated("market_api", "market") return self._dispatch( constants.MARKET_ENDPOINT, { @@ -894,12 +958,16 @@ def count_api( ) -> dict[str, Any] | Iterator[dict[str, Any]]: """Fetch aggregate counts of news for a date range. + .. deprecated:: 0.4.0 + Use :meth:`count_news` instead. + ``from_date`` and ``to_date`` are required. Returns a dict by default, the merged dict if ``scroll=True`` (concatenates per-bucket rows from every page; the final aggregate dict, if any, is captured under the ``aggregate`` key of the merged response), or an iterator of per-page dicts if ``paginate=True``. """ + _warn_deprecated("count_api", "count_news") return self._dispatch( constants.COUNT_ENDPOINT, { @@ -977,11 +1045,15 @@ def crypto_count_api( ) -> dict[str, Any] | Iterator[dict[str, Any]]: """Fetch aggregate counts of crypto news for a date range. + .. deprecated:: 0.4.0 + Use :meth:`count_crypto` instead. + ``from_date`` and ``to_date`` are required. Returns a dict by default, the merged dict if ``scroll=True`` (final aggregate dict, if any, captured under ``aggregate`` key), or an iterator of per-page dicts if ``paginate=True``. """ + _warn_deprecated("crypto_count_api", "count_crypto") return self._dispatch( constants.CRYPTO_COUNT_ENDPOINT, { @@ -1057,11 +1129,15 @@ def market_count_api( ) -> dict[str, Any] | Iterator[dict[str, Any]]: """Fetch aggregate counts of market news for a date range. + .. deprecated:: 0.4.0 + Use :meth:`count_market` instead. + ``from_date`` and ``to_date`` are required. Returns a dict by default, the merged dict if ``scroll=True`` (final aggregate dict, if any, captured under ``aggregate`` key), or an iterator of per-page dicts if ``paginate=True``. """ + _warn_deprecated("market_count_api", "count_market") return self._dispatch( constants.MARKET_COUNT_ENDPOINT, { @@ -1103,6 +1179,529 @@ def market_count_api( is_count=True, ) + # ---- v2 endpoint methods --------------------------------------------- + + def news( + self, + *, + q: str | None = None, + q_in_title: str | None = None, + q_in_meta: str | None = None, + country: str | list[str] | None = None, + exclude_country: str | list[str] | None = None, + category: str | list[str] | None = None, + exclude_category: str | list[str] | None = None, + language: str | list[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, + from_date: str | None = None, + to_date: str | None = None, + timeframe: int | str | None = None, + timezone: str | None = None, + size: int | None = None, + content: bool | None = None, + image: bool | None = None, + video: bool | None = None, + page: str | None = None, + tag: str | list[str] | None = None, + sentiment: str | None = None, + sentiment_score: float | None = None, + region: str | list[str] | None = None, + organization: str | list[str] | None = None, + creator: str | list[str] | None = None, + datatype: str | list[str] | None = None, + exclude_field: str | list[str] | None = None, + remove_duplicate: bool | None = None, + id: str | list[str] | None = None, + url: str | None = None, + sort: str | None = None, + raw_query: str | None = None, + scroll: bool = False, + paginate: bool = False, + max_result: int | None = None, + max_pages: int | None = None, + ) -> dict[str, Any] | Iterator[dict[str, Any]]: + """Fetch the latest news, or historical news with ``from_date`` / ``to_date``. + + See https://newsdata.io/documentation for parameter descriptions. + + Returns a dict by default, the merged dict if ``scroll=True``, or + an iterator of per-page dicts if ``paginate=True``. + """ + return self._dispatch( + constants.NEWS_V2_ENDPOINT, + { + "q": q, + "q_in_title": q_in_title, + "q_in_meta": q_in_meta, + "country": country, + "exclude_country": exclude_country, + "category": category, + "exclude_category": exclude_category, + "language": language, + "exclude_language": exclude_language, + "source_url": source_url, + "exclude_source_url": exclude_source_url, + "source_priority": source_priority, + "from_date": from_date, + "to_date": to_date, + "timeframe": str(timeframe) if timeframe is not None else None, + "timezone": timezone, + "size": size, + "content": content, + "image": image, + "video": video, + "page": page, + "tag": tag, + "sentiment": sentiment, + "sentiment_score": sentiment_score, + "region": region, + "organization": organization, + "creator": creator, + "datatype": datatype, + "exclude_field": exclude_field, + "remove_duplicate": remove_duplicate, + "id": id, + "url": url, + "sort": sort, + "raw_query": raw_query, + }, + scroll=scroll, + paginate=paginate, + max_result=max_result, + max_pages=max_pages, + v2=True, + ) + + def market( + self, + *, + q: str | None = None, + q_in_title: str | None = None, + q_in_meta: str | None = None, + country: str | list[str] | None = None, + exclude_country: str | list[str] | None = None, + language: str | list[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, + from_date: str | None = None, + to_date: str | None = None, + timeframe: int | str | None = None, + timezone: str | None = None, + size: int | None = None, + content: bool | None = None, + image: bool | None = None, + video: bool | None = None, + page: str | None = None, + tag: str | list[str] | None = None, + sentiment: str | None = None, + sentiment_score: float | None = None, + organization: str | list[str] | None = None, + market_id: str | list[str] | None = None, + creator: str | list[str] | None = None, + datatype: str | list[str] | None = None, + exclude_field: str | list[str] | None = None, + remove_duplicate: bool | None = None, + id: str | list[str] | None = None, + url: str | None = None, + sort: str | None = None, + raw_query: str | None = None, + scroll: bool = False, + paginate: bool = False, + max_result: int | None = None, + max_pages: int | None = None, + ) -> dict[str, Any] | Iterator[dict[str, Any]]: + """Fetch market / financial news. + + See https://newsdata.io/documentation for parameter descriptions. + """ + return self._dispatch( + constants.MARKET_V2_ENDPOINT, + { + "q": q, + "q_in_title": q_in_title, + "q_in_meta": q_in_meta, + "country": country, + "exclude_country": exclude_country, + "language": language, + "exclude_language": exclude_language, + "source_url": source_url, + "exclude_source_url": exclude_source_url, + "source_priority": source_priority, + "from_date": from_date, + "to_date": to_date, + "timeframe": str(timeframe) if timeframe is not None else None, + "timezone": timezone, + "size": size, + "content": content, + "image": image, + "video": video, + "page": page, + "tag": tag, + "sentiment": sentiment, + "sentiment_score": sentiment_score, + "organization": organization, + "market_id": market_id, + "creator": creator, + "datatype": datatype, + "exclude_field": exclude_field, + "remove_duplicate": remove_duplicate, + "id": id, + "url": url, + "sort": sort, + "raw_query": raw_query, + }, + scroll=scroll, + paginate=paginate, + max_result=max_result, + max_pages=max_pages, + v2=True, + ) + + def crypto( + self, + *, + q: str | None = None, + q_in_title: str | None = None, + q_in_meta: str | None = None, + coin: str | list[str] | None = None, + language: str | list[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, + from_date: str | None = None, + to_date: str | None = None, + timeframe: int | str | None = None, + timezone: str | None = None, + size: int | None = None, + content: bool | None = None, + image: bool | None = None, + video: bool | None = None, + page: str | None = None, + tag: str | list[str] | None = None, + sentiment: str | None = None, + exclude_field: str | list[str] | None = None, + remove_duplicate: bool | None = None, + id: str | list[str] | None = None, + url: str | None = None, + sort: str | None = None, + raw_query: str | None = None, + scroll: bool = False, + paginate: bool = False, + max_result: int | None = None, + max_pages: int | None = None, + ) -> dict[str, Any] | Iterator[dict[str, Any]]: + """Fetch cryptocurrency news. + + See https://newsdata.io/documentation for parameter descriptions. + """ + return self._dispatch( + constants.CRYPTO_V2_ENDPOINT, + { + "q": q, + "q_in_title": q_in_title, + "q_in_meta": q_in_meta, + "coin": coin, + "language": language, + "exclude_language": exclude_language, + "source_url": source_url, + "exclude_source_url": exclude_source_url, + "source_priority": source_priority, + "from_date": from_date, + "to_date": to_date, + "timeframe": str(timeframe) if timeframe is not None else None, + "timezone": timezone, + "size": size, + "content": content, + "image": image, + "video": video, + "page": page, + "tag": tag, + "sentiment": sentiment, + "exclude_field": exclude_field, + "remove_duplicate": remove_duplicate, + "id": id, + "url": url, + "sort": sort, + "raw_query": raw_query, + }, + scroll=scroll, + paginate=paginate, + max_result=max_result, + max_pages=max_pages, + v2=True, + ) + + def sources( + self, + *, + country: str | list[str] | None = None, + category: str | list[str] | None = None, + language: str | list[str] | None = None, + source_priority: str | None = None, + source_url: str | list[str] | None = None, + raw_query: str | None = None, + ) -> dict[str, Any]: + """List available news sources. + + Sources is a single-page endpoint; ``scroll`` and ``paginate`` are + not supported. + """ + params = _validate_params( + { + "country": country, + "category": category, + "language": language, + "source_priority": source_priority, + "source_url": source_url, + "raw_query": raw_query, + } + ) + return self._request(constants.SOURCES_V2_ENDPOINT, params) + + def count_news( + self, + *, + q: str | None = None, + q_in_title: str | None = None, + q_in_meta: str | None = None, + country: str | list[str] | None = None, + exclude_country: str | list[str] | None = None, + category: str | list[str] | None = None, + exclude_category: str | list[str] | None = None, + language: str | list[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, + from_date: str | None = None, + to_date: str | None = None, + timeframe: int | str | None = None, + interval: str | None = None, + size: int | None = None, + content: bool | None = None, + image: bool | None = None, + video: bool | None = None, + page: str | None = None, + tag: str | list[str] | None = None, + sentiment: str | None = None, + sentiment_score: float | None = None, + region: str | list[str] | None = None, + organization: str | list[str] | None = None, + creator: str | list[str] | None = None, + datatype: str | list[str] | None = None, + remove_duplicate: bool | None = None, + sort: str | None = None, + raw_query: str | None = None, + scroll: bool = False, + paginate: bool = False, + max_result: int | None = None, + max_pages: int | None = None, + ) -> dict[str, Any] | Iterator[dict[str, Any]]: + """Fetch counts of news per time interval. + + See https://newsdata.io/documentation for parameter descriptions. + + Returns a dict by default, the merged dict if ``scroll=True``, or + an iterator of per-page dicts if ``paginate=True``. + """ + return self._dispatch( + constants.COUNT_NEWS_V2_ENDPOINT, + { + "q": q, + "q_in_title": q_in_title, + "q_in_meta": q_in_meta, + "country": country, + "exclude_country": exclude_country, + "category": category, + "exclude_category": exclude_category, + "language": language, + "exclude_language": exclude_language, + "source_url": source_url, + "exclude_source_url": exclude_source_url, + "source_priority": source_priority, + "from_date": from_date, + "to_date": to_date, + "timeframe": str(timeframe) if timeframe is not None else None, + "interval": interval, + "size": size, + "content": content, + "image": image, + "video": video, + "page": page, + "tag": tag, + "sentiment": sentiment, + "sentiment_score": sentiment_score, + "region": region, + "organization": organization, + "creator": creator, + "datatype": datatype, + "remove_duplicate": remove_duplicate, + "sort": sort, + "raw_query": raw_query, + }, + scroll=scroll, + paginate=paginate, + max_result=max_result, + max_pages=max_pages, + v2=True, + ) + + def count_market( + self, + *, + q: str | None = None, + q_in_title: str | None = None, + q_in_meta: str | None = None, + country: str | list[str] | None = None, + exclude_country: str | list[str] | None = None, + language: str | list[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, + from_date: str | None = None, + to_date: str | None = None, + timeframe: int | str | None = None, + interval: str | None = None, + size: int | None = None, + content: bool | None = None, + image: bool | None = None, + video: bool | None = None, + page: str | None = None, + tag: str | list[str] | None = None, + sentiment: str | None = None, + sentiment_score: float | None = None, + organization: str | list[str] | None = None, + market_id: str | list[str] | None = None, + creator: str | list[str] | None = None, + datatype: str | list[str] | None = None, + remove_duplicate: bool | None = None, + sort: str | None = None, + raw_query: str | None = None, + scroll: bool = False, + paginate: bool = False, + max_result: int | None = None, + max_pages: int | None = None, + ) -> dict[str, Any] | Iterator[dict[str, Any]]: + """Fetch counts of market news per time interval. + + See https://newsdata.io/documentation for parameter descriptions. + """ + return self._dispatch( + constants.COUNT_MARKET_V2_ENDPOINT, + { + "q": q, + "q_in_title": q_in_title, + "q_in_meta": q_in_meta, + "country": country, + "exclude_country": exclude_country, + "language": language, + "exclude_language": exclude_language, + "source_url": source_url, + "exclude_source_url": exclude_source_url, + "source_priority": source_priority, + "from_date": from_date, + "to_date": to_date, + "timeframe": str(timeframe) if timeframe is not None else None, + "interval": interval, + "size": size, + "content": content, + "image": image, + "video": video, + "page": page, + "tag": tag, + "sentiment": sentiment, + "sentiment_score": sentiment_score, + "organization": organization, + "market_id": market_id, + "creator": creator, + "datatype": datatype, + "remove_duplicate": remove_duplicate, + "sort": sort, + "raw_query": raw_query, + }, + scroll=scroll, + paginate=paginate, + max_result=max_result, + max_pages=max_pages, + v2=True, + ) + + def count_crypto( + self, + *, + q: str | None = None, + q_in_title: str | None = None, + q_in_meta: str | None = None, + coin: str | list[str] | None = None, + language: str | list[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, + from_date: str | None = None, + to_date: str | None = None, + timeframe: int | str | None = None, + interval: str | None = None, + size: int | None = None, + content: bool | None = None, + image: bool | None = None, + video: bool | None = None, + page: str | None = None, + tag: str | list[str] | None = None, + sentiment: str | None = None, + remove_duplicate: bool | None = None, + sort: str | None = None, + raw_query: str | None = None, + scroll: bool = False, + paginate: bool = False, + max_result: int | None = None, + max_pages: int | None = None, + ) -> dict[str, Any] | Iterator[dict[str, Any]]: + """Fetch counts of crypto news per time interval. + + See https://newsdata.io/documentation for parameter descriptions. + """ + return self._dispatch( + constants.COUNT_CRYPTO_V2_ENDPOINT, + { + "q": q, + "q_in_title": q_in_title, + "q_in_meta": q_in_meta, + "coin": coin, + "language": language, + "exclude_language": exclude_language, + "source_url": source_url, + "exclude_source_url": exclude_source_url, + "source_priority": source_priority, + "from_date": from_date, + "to_date": to_date, + "timeframe": str(timeframe) if timeframe is not None else None, + "interval": interval, + "size": size, + "content": content, + "image": image, + "video": video, + "page": page, + "tag": tag, + "sentiment": sentiment, + "remove_duplicate": remove_duplicate, + "sort": sort, + "raw_query": raw_query, + }, + scroll=scroll, + paginate=paginate, + max_result=max_result, + max_pages=max_pages, + v2=True, + ) + # ---- CSV export convenience ----------------------------------------- def save_to_csv( @@ -1139,15 +1738,24 @@ def _dispatch( max_result: int | None = None, max_pages: int | None = None, is_count: bool = False, + v2: bool = False, ) -> dict[str, Any] | Iterator[dict[str, Any]]: - """Validate ``params`` and route to single / scroll / paginate execution.""" + """Validate ``params`` and route to single / scroll / paginate execution. + + ``v2`` selects the v2 response keys (``total_results`` / ``next_page``) + for the multi-page modes. + """ if scroll and paginate: raise ValueError("scroll and paginate are mutually exclusive") validated = _validate_params(params) if scroll: - return self._scroll_all(endpoint, validated, max_result, is_count=is_count) + return self._scroll_all( + endpoint, validated, max_result, is_count=is_count, v2=v2 + ) if paginate: - return self._paginate(endpoint, validated, max_pages, is_count=is_count) + return self._paginate( + endpoint, validated, max_pages, is_count=is_count, v2=v2 + ) return self._request(endpoint, validated) def _request( @@ -1243,15 +1851,25 @@ def _request( retry_after = _parse_retry_after(response.headers.get("Retry-After")) error_code = _extract_error_code(body) exc_cls = _QUOTA_EXHAUSTED_ERRORS.get(error_code or "", NewsdataRateLimitError) - if error_code in _QUOTA_EXHAUSTED_ERRORS or attempt >= self.max_retries: + # A wait longer than retry_backoff_max is left to the caller. + wait_too_long = ( + retry_after is not None and retry_after > self.retry_backoff_max + ) + if ( + error_code in _QUOTA_EXHAUSTED_ERRORS + or attempt >= self.max_retries + or wait_too_long + ): raise exc_cls( body, status_code=429, response_body=body if isinstance(body, dict) else None, retry_after=retry_after, ) + # Retry-After is in whole seconds: one second more keeps the + # retry from arriving just before the limit resets. sleep_for = ( - retry_after + retry_after + 1 if retry_after is not None else self._compute_backoff(attempt) ) @@ -1310,6 +1928,7 @@ def _scroll_all( max_result: int | None, *, is_count: bool = False, + v2: bool = False, ) -> dict[str, Any]: """Follow ``nextPage`` cursors and return one merged response. @@ -1317,11 +1936,15 @@ def _scroll_all( page. For count endpoints (``is_count=True``), additionally captures the final aggregate dict — when the API returns ``results`` as a dict on the final page — under the ``aggregate`` key of the merged - response. + response. With ``v2=True`` the cursor and total are read from, and + returned under, ``next_page`` / ``total_results``. """ if max_result is None: max_result = self.max_result + total_key, next_key = ( + ("total_results", "next_page") if v2 else ("totalResults", "nextPage") + ) accumulated: list[dict[str, Any]] = [] request_params: dict[str, Any] = dict(params) total_results: Any = None @@ -1331,7 +1954,7 @@ def _scroll_all( while True: response = self._request(endpoint, request_params) - total_results = response.get("totalResults", total_results) + total_results = response.get(total_key, total_results) page_results = response.get("results", []) if isinstance(page_results, list): accumulated.extend(page_results) @@ -1339,7 +1962,7 @@ def _scroll_all( aggregate = page_results if self.include_headers: last_headers = response.get("response_headers") - next_page = response.get("nextPage") + next_page = response.get(next_key) if max_result is not None and len(accumulated) >= max_result: accumulated = accumulated[:max_result] @@ -1352,9 +1975,9 @@ def _scroll_all( time.sleep(self.pagination_delay) merged: dict[str, Any] = { - "totalResults": total_results, + total_key: total_results, "results": accumulated, - "nextPage": next_page, + next_key: next_page, } if aggregate is not None: merged["aggregate"] = aggregate @@ -1369,11 +1992,16 @@ def _paginate( max_pages: int | None, *, is_count: bool = False, + v2: bool = False, ) -> Iterator[dict[str, Any]]: - """Yield one response per page, up to ``max_pages``.""" + """Yield one response per page, up to ``max_pages``. + + With ``v2=True`` the cursor is read from ``next_page``. + """ if max_pages is None: max_pages = self.max_pages + next_key = "next_page" if v2 else "nextPage" request_params: dict[str, Any] = dict(params) page_count = 0 while True: @@ -1387,7 +2015,7 @@ def _paginate( return if max_pages is not None and page_count >= max_pages: return - next_page = response.get("nextPage") + next_page = response.get(next_key) if not next_page: return diff --git a/src/newsdataapi/constants.py b/src/newsdataapi/constants.py index 72be8eb..3f65e88 100644 --- a/src/newsdataapi/constants.py +++ b/src/newsdataapi/constants.py @@ -2,22 +2,31 @@ from __future__ import annotations -# Base URL for the NewsData.io REST API. Must end with a slash so that -# ``urljoin(BASE_URL, "latest")`` produces the right URL. -BASE_URL = "https://newsdata.io/api/1/" +# Root URL of the NewsData.io REST API. Endpoint paths carry the API version +# and are joined to it (the client adds the trailing slash ``urljoin`` needs). +BASE_URL = "https://newsdata.io/api" -# Endpoint paths joined to ``BASE_URL`` to form the full request URL. -LATEST_ENDPOINT = "latest" -ARCHIVE_ENDPOINT = "archive" -SOURCES_ENDPOINT = "sources" -CRYPTO_ENDPOINT = "crypto" -MARKET_ENDPOINT = "market" -COUNT_ENDPOINT = "count" -CRYPTO_COUNT_ENDPOINT = "crypto/count" -MARKET_COUNT_ENDPOINT = "market/count" -WEBSOCKET_REGISTER_ENDPOINT = "websocket/register" -WEBSOCKET_FETCH_ENDPOINT = "websocket/fetch" -WEBSOCKET_DELETE_ENDPOINT = "websocket/delete" +# v1 endpoint paths, joined to ``BASE_URL`` to form the full request URL. +LATEST_ENDPOINT = "1/latest" +ARCHIVE_ENDPOINT = "1/archive" +SOURCES_ENDPOINT = "1/sources" +CRYPTO_ENDPOINT = "1/crypto" +MARKET_ENDPOINT = "1/market" +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" +MARKET_V2_ENDPOINT = "2/market" +CRYPTO_V2_ENDPOINT = "2/crypto" +SOURCES_V2_ENDPOINT = "2/sources" +COUNT_NEWS_V2_ENDPOINT = "2/count/news" +COUNT_MARKET_V2_ENDPOINT = "2/count/market" +COUNT_CRYPTO_V2_ENDPOINT = "2/count/crypto" # HTTP defaults. DEFAULT_REQUEST_TIMEOUT = 30 # seconds diff --git a/src/newsdataapi/csv_export.py b/src/newsdataapi/csv_export.py index 63a9e34..568f470 100644 --- a/src/newsdataapi/csv_export.py +++ b/src/newsdataapi/csv_export.py @@ -3,6 +3,7 @@ from __future__ import annotations import csv +import json import os import time from collections.abc import Iterable, Mapping @@ -19,6 +20,10 @@ def save_to_csv( ) -> Path: """Write ``response['results']`` to a CSV file inside ``folder_path``. + Nested fields get one column each, named with dots (``source.name``). + In responses from the deprecated ``*_api`` methods, dict and list cell + values are stringified instead. + Args: response: A response dict from the NewsData API. Expected to have a ``results`` key holding a list of dicts. ``response`` is read @@ -57,7 +62,13 @@ def save_to_csv( f"Expected response['results'] to be a list, got {type(results).__name__}" ) - rows = [_flatten_row(row) for row in results if isinstance(row, Mapping)] + # A v2 response is recognised by its ``total_results`` key. + is_v2 = "total_results" in response + rows = [ + _flatten_row_v2(row) if is_v2 else _flatten_row(row) + for row in results + if isinstance(row, Mapping) + ] fieldnames = _collect_fieldnames(rows) with target.open("w", newline="", encoding="utf-8") as fh: @@ -89,6 +100,29 @@ def _flatten_row(row: Mapping[str, Any]) -> dict[str, Any]: return flattened +def _flatten_row_v2(row: Mapping[str, Any], prefix: str = "") -> dict[str, Any]: + """Return a flat *copy* of a v2 ``row``. + + Nested dicts become dotted columns (``source.name``), at any depth. + Lists of plain values are joined with ``,``; lists holding dicts or + lists are written as JSON. Other types are passed through unchanged. + """ + flattened: dict[str, Any] = {} + for key, value in row.items(): + column = f"{prefix}{key}" + if isinstance(value, Mapping): + flattened.update(_flatten_row_v2(value, f"{column}.")) + elif isinstance(value, list): + if any(isinstance(item, (Mapping, list)) for item in value): + # default=str: a non-JSON value is written as text, not raised. + flattened[column] = json.dumps(value, ensure_ascii=False, default=str) + else: + flattened[column] = ",".join(str(item) for item in value) + else: + flattened[column] = value + return flattened + + def _collect_fieldnames(rows: Iterable[Mapping[str, Any]]) -> list[str]: """Union of keys across rows, preserving first-seen order.""" seen: dict[str, None] = {} diff --git a/src/newsdataapi/exceptions.py b/src/newsdataapi/exceptions.py index 5cfbda2..f9576ed 100644 --- a/src/newsdataapi/exceptions.py +++ b/src/newsdataapi/exceptions.py @@ -52,7 +52,9 @@ class NewsdataAuthError(NewsdataAPIError): class NewsdataRateLimitError(NewsdataAPIError): - """Raised on 429 responses when retries are exhausted. + """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``. Attributes: retry_after: Seconds to wait before retrying, parsed from the @@ -85,9 +87,9 @@ class NewsdataApiLimitExceededError(NewsdataRateLimitError): class NewsdataApiKeyLimitExceededError(NewsdataRateLimitError): - """Raised on 429 when this specific API key's own credit cap - (``max_credit_limit``) is exhausted, even though the account's overall - pool may still have credits left. Never retried. + """Raised on 429 when this specific API key's own credit cap is + exhausted, even though the account's overall pool may still have + credits left. Never retried. """ diff --git a/src/newsdataapi/websocket.py b/src/newsdataapi/websocket.py index 4e868b5..b2bd6bf 100644 --- a/src/newsdataapi/websocket.py +++ b/src/newsdataapi/websocket.py @@ -291,6 +291,7 @@ def _connect_kwargs(self) -> dict[str, Any]: "ping_timeout": self._ping_timeout, "additional_headers": self._additional_headers, "proxy": self._proxy, + "max_size": None, # responses can exceed websockets' 1 MiB default } def _next_delay(self, delay: float) -> float: diff --git a/tests/test_integration.py b/tests/test_integration.py index 338f2dd..4507d16 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -103,3 +103,48 @@ def test_market_count_api(api: NewsDataApiClient) -> None: ) assert isinstance(response, dict) assert response["status"] == "success" + + +# ---- v2 endpoints ---------------------------------------------------------- + + +def test_news(api: NewsDataApiClient) -> None: + response = api.news() + assert isinstance(response, dict) + assert response["status"] == "success" + + +def test_market(api: NewsDataApiClient) -> None: + response = api.market() + assert isinstance(response, dict) + assert response["status"] == "success" + + +def test_crypto(api: NewsDataApiClient) -> None: + response = api.crypto(q="bitcoin") + assert isinstance(response, dict) + assert response["status"] == "success" + + +def test_sources(api: NewsDataApiClient) -> None: + response = api.sources() + assert isinstance(response, dict) + assert response["status"] == "success" + + +def test_count_news(api: NewsDataApiClient) -> None: + response = api.count_news(language="en") + assert isinstance(response, dict) + assert response["status"] == "success" + + +def test_count_market(api: NewsDataApiClient) -> None: + response = api.count_market(language="en") + assert isinstance(response, dict) + assert response["status"] == "success" + + +def test_count_crypto(api: NewsDataApiClient) -> None: + response = api.count_crypto(language="en") + assert isinstance(response, dict) + assert response["status"] == "success" diff --git a/tests/test_unit.py b/tests/test_unit.py index 91a1727..e3386c0 100644 --- a/tests/test_unit.py +++ b/tests/test_unit.py @@ -7,7 +7,9 @@ from __future__ import annotations +import csv import sys +import warnings from datetime import datetime, timedelta, timezone from email.utils import format_datetime from pathlib import Path @@ -212,6 +214,55 @@ def test_validate_no_mutex_when_one_per_group_set() -> None: } +@pytest.mark.parametrize( + ("params", "first_conflict"), + [ + ({"q": "news", "q_in_title": "bar"}, "q"), + ({"q": "news", "q_in_meta": "bar"}, "q"), + ({"q_in_title": "foo", "q_in_meta": "bar"}, "q_in_title"), + ({"country": "us", "exclude_country": "gb"}, "country"), + ({"category": "business", "exclude_category": "sports"}, "category"), + ({"language": "en", "exclude_language": "fr"}, "language"), + ({"source_url": "bbc.com", "exclude_source_url": "cnn.com"}, "source_url"), + ], +) +def test_validate_v2_mutex_groups_raise( + params: dict[str, str], + first_conflict: str, +) -> None: + """The v2 names of the mutex groups are caught client-side too.""" + with pytest.raises(NewsdataValidationError) as exc_info: + _validate_params(params) + assert "mutually exclusive" in str(exc_info.value) + assert exc_info.value.param == first_conflict + + +def test_validate_v2_param_types() -> None: + """v2 names get the same coercion as their v1 counterparts.""" + out = _validate_params( + { + "q_in_title": "bitcoin", + "source_url": ["bbc.com", "cnn.com"], + "exclude_field": ["content", "ai.summary"], + "content": True, + "remove_duplicate": False, + } + ) + assert out == { + "q_in_title": "bitcoin", + "source_url": "bbc.com,cnn.com", + "exclude_field": "content,ai.summary", + "content": 1, + "remove_duplicate": 0, + } + + +def test_validate_v2_bool_param_rejects_non_bool() -> None: + with pytest.raises(NewsdataValidationError) as exc_info: + _validate_params({"content": 1}) + assert exc_info.value.param == "content" + + def test_validate_float_param_accepts_float() -> None: out = _validate_params({"sentiment": "positive", "sentiment_score": 44.5}) assert out == {"sentiment": "positive", "sentiment_score": 44.5} @@ -564,6 +615,104 @@ def test_csv_results_not_a_list_raises_type_error(tmp_path: Path) -> None: save_to_csv({"results": "not a list"}, tmp_path, filename="x") +def test_csv_v2_nested_fields_become_dotted_columns(tmp_path: Path) -> None: + """A v2 response gets one column per nested field, at any depth.""" + media = {"image_url": "https://img.example/1.png", "video_url": None} + response = { + "status": "success", + "total_results": 1, + "results": [ + { + "id": "a1", + "title": "T", + "keyword": ["btc", "eth"], + "media": media, + "source": {"name": "BBC", "priority": 10}, + "ai": { + "sentiment": {"label": "positive", "score": {"positive": 90.5}}, + "tag": ["crypto"], + }, + } + ], + "next_page": None, + } + out = save_to_csv(response, tmp_path, filename="v2") + with out.open(newline="", encoding="utf-8") as fh: + rows = list(csv.DictReader(fh)) + assert rows == [ + { + "id": "a1", + "title": "T", + "keyword": "btc,eth", + "media.image_url": "https://img.example/1.png", + "media.video_url": "", + "source.name": "BBC", + "source.priority": "10", + "ai.sentiment.label": "positive", + "ai.sentiment.score.positive": "90.5", + "ai.tag": "crypto", + } + ] + # The input is not modified. + assert media == {"image_url": "https://img.example/1.png", "video_url": None} + + +def test_csv_v2_list_of_objects_is_json(tmp_path: Path) -> None: + response = { + "status": "success", + "total_results": 1, + "results": [ + { + "name": "BBC", + "language": [{"code": "en", "name": "english"}], + "stat": {"article_count": 5}, + } + ], + } + out = save_to_csv(response, tmp_path, filename="v2sources") + with out.open(newline="", encoding="utf-8") as fh: + rows = list(csv.DictReader(fh)) + assert rows == [ + { + "name": "BBC", + "language": '[{"code": "en", "name": "english"}]', + "stat.article_count": "5", + } + ] + + +def test_csv_v2_mixed_rows_use_union_of_columns(tmp_path: Path) -> None: + """A field that is nested in one row and plain in another keeps both columns.""" + response = { + "total_results": 2, + "results": [ + {"id": "1", "ai": {"sentiment": {"label": "neutral"}}}, + {"id": "2", "ai": {"sentiment": "not available"}}, + ], + } + out = save_to_csv(response, tmp_path, filename="v2mixed") + with out.open(newline="", encoding="utf-8") as fh: + rows = list(csv.DictReader(fh)) + assert rows == [ + {"id": "1", "ai.sentiment.label": "neutral", "ai.sentiment": ""}, + {"id": "2", "ai.sentiment.label": "", "ai.sentiment": "not available"}, + ] + + +def test_csv_v1_response_keeps_stringified_dict_cells(tmp_path: Path) -> None: + """A v1 response (``totalResults``) is written exactly as before.""" + response = { + "status": "success", + "totalResults": 1, + "results": [{"title": "T", "sentiment_stats": {"positive": 1, "negative": 2}}], + "nextPage": None, + } + out = save_to_csv(response, tmp_path, filename="v1") + with out.open(newline="", encoding="utf-8") as fh: + rows = list(csv.DictReader(fh)) + assert rows == [{"title": "T", "sentiment_stats": "positive:1,negative:2"}] + + # =========================================================================== # Exception hierarchy # =========================================================================== @@ -845,6 +994,7 @@ def test_429_exhausted_raises_rate_limit_with_retry_after( mocked_responses: responses.RequestsMock, no_sleep: None, ) -> None: + client.retry_backoff_max = 60.0 # a Retry-After above this is not retried for _ in range(client.max_retries): mocked_responses.get( LATEST_URL, @@ -857,6 +1007,59 @@ def test_429_exhausted_raises_rate_limit_with_retry_after( assert exc_info.value.retry_after == 5 +@pytest.mark.parametrize( + ("retry_after", "expected_sleep"), + [("0", 1), ("5", 6), ("60", 61)], +) +def test_429_sleeps_one_second_longer_than_retry_after( + retry_after: str, + expected_sleep: int, + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Retry-After is in whole seconds: the extra second keeps the retry from + arriving just before the limit resets, and a ``0`` from retrying at once.""" + slept: list[float] = [] + monkeypatch.setattr("newsdataapi.client.time.sleep", slept.append) + client.retry_backoff_max = 60.0 + mocked_responses.get( + LATEST_URL, + json={"status": "error"}, + status=429, + headers={"Retry-After": retry_after}, + ) + mocked_responses.get( + LATEST_URL, + json={"status": "success", "results": []}, + status=200, + ) + client.latest_api() + assert slept == [expected_sleep] + + +def test_429_retry_after_above_backoff_max_raises_without_retry( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A Retry-After longer than retry_backoff_max is not waited for.""" + slept: list[float] = [] + monkeypatch.setattr("newsdataapi.client.time.sleep", slept.append) + client.retry_backoff_max = 60.0 + mocked_responses.get( + LATEST_URL, + json={"status": "error"}, + status=429, + headers={"Retry-After": "61"}, + ) + with pytest.raises(NewsdataRateLimitError) as exc_info: + client.latest_api() + assert exc_info.value.retry_after == 61 + assert len(mocked_responses.calls) == 1 + assert slept == [] + + @pytest.mark.parametrize( ("code", "expected_exc"), [ @@ -1373,6 +1576,396 @@ def test_raw_query_accepts_excludedomainurl( assert "excludedomainurl=bbc.com" in sent_url +def test_custom_base_url_is_the_api_root( + mocked_responses: responses.RequestsMock, +) -> None: + """A custom base URL is the API root; endpoint paths add the version.""" + mocked_responses.get( + "https://staging.example.com/api/1/latest", + json={"status": "success", "results": []}, + status=200, + ) + mocked_responses.get( + "https://staging.example.com/api/2/news", + json={"status": "success", "total_results": 0, "results": []}, + status=200, + ) + with NewsDataApiClient("k", base_url="https://staging.example.com/api") as c: + c.latest_api() + c.news() + assert len(mocked_responses.calls) == 2 + + +# =========================================================================== +# v2 endpoints +# =========================================================================== + +NEWS_V2_URL = "https://newsdata.io/api/2/news" +COUNT_NEWS_V2_URL = "https://newsdata.io/api/2/count/news" + + +@pytest.mark.parametrize( + ("method_name", "endpoint_path"), + [ + ("news", "news"), + ("market", "market"), + ("crypto", "crypto"), + ("sources", "sources"), + ("count_news", "count/news"), + ("count_market", "count/market"), + ("count_crypto", "count/crypto"), + ], +) +def test_v2_endpoint_url_resolves( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + method_name: str, + endpoint_path: str, +) -> None: + mocked_responses.get( + f"https://newsdata.io/api/2/{endpoint_path}", + json={"status": "success", "total_results": 0, "results": []}, + status=200, + ) + getattr(client, method_name)() + assert len(mocked_responses.calls) == 1 + + +def test_v2_sends_v2_param_names( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, +) -> None: + mocked_responses.get( + NEWS_V2_URL, + json={"status": "success", "total_results": 0, "results": []}, + status=200, + ) + client.news( + q_in_title="bitcoin", + source_url=["bbc.com", "cnn.com"], + exclude_country="us", + source_priority="top", + timeframe=6, + content=True, + remove_duplicate=False, + ) + sent_url = mocked_responses.calls[0].request.url + assert sent_url is not None + assert "q_in_title=bitcoin" in sent_url + assert "source_url=bbc.com%2Ccnn.com" in sent_url + assert "exclude_country=us" in sent_url + assert "source_priority=top" in sent_url + assert "timeframe=6" in sent_url + assert "content=1" in sent_url + assert "remove_duplicate=0" in sent_url + assert "apikey=test_key_xxx" in sent_url + + +@pytest.mark.parametrize( + ("method_name", "endpoint_path"), + [ + ("news", "news"), + ("market", "market"), + ("crypto", "crypto"), + ("count_news", "count/news"), + ("count_market", "count/market"), + ("count_crypto", "count/crypto"), + ], +) +def test_v2_exclude_source_url_sent_as_csv( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + method_name: str, + endpoint_path: str, +) -> None: + mocked_responses.get( + f"https://newsdata.io/api/2/{endpoint_path}", + json={"status": "success", "total_results": 0, "results": []}, + status=200, + ) + getattr(client, method_name)(exclude_source_url=["bbc.com", "cnn.com"]) + sent_url = mocked_responses.calls[0].request.url + assert sent_url is not None + assert "exclude_source_url=bbc.com%2Ccnn.com" in sent_url + + +def test_v2_sources_sends_filters( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, +) -> None: + mocked_responses.get( + "https://newsdata.io/api/2/sources", + json={"status": "success", "total_results": 0, "results": []}, + status=200, + ) + client.sources(country=["us", "gb"], source_priority="top") + sent_url = mocked_responses.calls[0].request.url + assert sent_url is not None + assert "country=us%2Cgb" in sent_url + assert "source_priority=top" in sent_url + + +def test_v2_mutex_validation_applies(client: NewsDataApiClient) -> None: + with pytest.raises(NewsdataValidationError) as exc_info: + client.news(q="a", q_in_title="b") + assert exc_info.value.param == "q" + + +def test_v2_raw_query_accepts_v2_names( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, +) -> None: + mocked_responses.get( + NEWS_V2_URL, + json={"status": "success", "total_results": 0, "results": []}, + status=200, + ) + client.news(raw_query="q_in_title=bitcoin&exclude_source_url=bbc.com") + sent_url = mocked_responses.calls[0].request.url + assert sent_url is not None + assert "q_in_title=bitcoin" in sent_url + assert "exclude_source_url=bbc.com" in sent_url + + +def test_raw_query_rejects_names_of_the_other_version( + client: NewsDataApiClient, +) -> None: + """v2 methods reject v1 parameter names in raw_query, and vice versa.""" + with pytest.raises(NewsdataValidationError): + client.news(raw_query="qInTitle=bitcoin") + with pytest.raises(NewsdataValidationError): + client.latest_api(raw_query="q_in_title=bitcoin") + + +def test_v2_scroll_merges_pages( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + no_sleep: None, +) -> None: + """v2 scroll follows ``next_page`` and returns the v2 response keys.""" + mocked_responses.get( + NEWS_V2_URL, + json={ + "status": "success", + "total_results": 3, + "results": [{"id": "1"}, {"id": "2"}], + "next_page": "p2", + }, + status=200, + ) + mocked_responses.get( + NEWS_V2_URL, + json={ + "status": "success", + "total_results": 3, + "results": [{"id": "3"}], + "next_page": None, + }, + status=200, + ) + result = client.news(q="x", scroll=True) + assert isinstance(result, dict) + assert result == { + "total_results": 3, + "results": [{"id": "1"}, {"id": "2"}, {"id": "3"}], + "next_page": None, + } + second_url = mocked_responses.calls[1].request.url + assert second_url is not None + assert "page=p2" in second_url + + +def test_v2_scroll_truncates_to_max_result( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + no_sleep: None, +) -> None: + mocked_responses.get( + NEWS_V2_URL, + json={ + "status": "success", + "total_results": 20, + "results": [{"id": str(i)} for i in range(5)], + "next_page": "p2", + }, + status=200, + ) + mocked_responses.get( + NEWS_V2_URL, + json={ + "status": "success", + "total_results": 20, + "results": [{"id": str(i)} for i in range(5, 10)], + "next_page": "p3", + }, + status=200, + ) + result = client.news(q="x", scroll=True, max_result=7) + assert isinstance(result, dict) + assert len(result["results"]) == 7 + assert result["next_page"] is None + + +def test_v2_paginate_follows_next_page( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + no_sleep: None, +) -> None: + mocked_responses.get( + NEWS_V2_URL, + json={ + "status": "success", + "total_results": 2, + "results": [{"id": "1"}], + "next_page": "p2", + }, + status=200, + ) + mocked_responses.get( + NEWS_V2_URL, + json={ + "status": "success", + "total_results": 2, + "results": [{"id": "2"}], + "next_page": None, + }, + status=200, + ) + result = client.news(q="x", paginate=True) + pages = list(result) + assert len(pages) == 2 + assert pages[0]["results"] == [{"id": "1"}] + assert pages[1]["results"] == [{"id": "2"}] + second_url = mocked_responses.calls[1].request.url + assert second_url is not None + assert "page=p2" in second_url + + +def test_v2_paginate_max_pages_caps( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + no_sleep: None, +) -> None: + # Exactly ``max_pages`` mocks, each claiming another page exists: a + # third request would raise ConnectionError (no mock for it). + for i in range(2): + mocked_responses.get( + NEWS_V2_URL, + json={ + "status": "success", + "total_results": 9, + "results": [{"id": str(i)}], + "next_page": f"p{i + 1}", + }, + status=200, + ) + pages = list(client.news(q="x", paginate=True, max_pages=2)) + assert len(pages) == 2 + + +def test_v2_count_scroll_merges_list_pages( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + no_sleep: None, +) -> None: + """v2 counts are a list on every page: merged with no aggregate key.""" + mocked_responses.get( + COUNT_NEWS_V2_URL, + json={ + "status": "success", + "total_results": 300, + "results": [{"date_time": "2026-01-02T00:00:00Z", "count": 100}], + "next_page": "1767225600000000000", + }, + status=200, + ) + mocked_responses.get( + COUNT_NEWS_V2_URL, + json={ + "status": "success", + "total_results": 300, + "results": [{"date_time": "2026-01-01T00:00:00Z", "count": 200}], + "next_page": None, + }, + status=200, + ) + result = client.count_news(language="en", scroll=True) + assert isinstance(result, dict) + assert result == { + "total_results": 300, + "results": [ + {"date_time": "2026-01-02T00:00:00Z", "count": 100}, + {"date_time": "2026-01-01T00:00:00Z", "count": 200}, + ], + "next_page": None, + } + second_url = mocked_responses.calls[1].request.url + assert second_url is not None + assert "page=1767225600000000000" in second_url + + +def test_v2_scroll_and_paginate_mutually_exclusive(client: NewsDataApiClient) -> None: + with pytest.raises(ValueError): + client.news(scroll=True, paginate=True) + + +# =========================================================================== +# v1 deprecation +# =========================================================================== + + +@pytest.mark.parametrize( + ("method_name", "endpoint_path", "args", "replacement"), + [ + ("latest_api", "latest", (), "news"), + ("archive_api", "archive", (), "news"), + ("sources_api", "sources", (), "sources"), + ("crypto_api", "crypto", (), "crypto"), + ("market_api", "market", (), "market"), + ("count_api", "count", ("2024-01-01", "2024-01-31"), "count_news"), + ("crypto_count_api", "crypto/count", ("2024-01-01", "2024-01-31"), "count_crypto"), + ("market_count_api", "market/count", ("2024-01-01", "2024-01-31"), "count_market"), + ], +) +def test_v1_methods_warn_deprecated( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, + method_name: str, + endpoint_path: str, + args: tuple[str, ...], + replacement: str, +) -> None: + """Each v1 method warns once, names its replacement, and still works.""" + mocked_responses.get( + f"https://newsdata.io/api/1/{endpoint_path}", + json={"status": "success", "results": []}, + status=200, + ) + with pytest.warns( + DeprecationWarning, + match=rf"^{method_name}\(\) is deprecated .* use {replacement}\(\) instead\.$", + ) as record: + response = getattr(client, method_name)(*args) + assert response["status"] == "success" + # Exactly one warning, attributed to the calling code (this file). + assert [w.filename for w in record if w.category is DeprecationWarning] == [__file__] + + +def test_v2_methods_do_not_warn( + client: NewsDataApiClient, + mocked_responses: responses.RequestsMock, +) -> None: + mocked_responses.get( + NEWS_V2_URL, + json={"status": "success", "total_results": 0, "results": []}, + status=200, + ) + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + client.news(q="x") + assert not [w for w in record if "is deprecated" in str(w.message)] + + # =========================================================================== # WebSocket query management (register / fetch / delete) # =========================================================================== diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 009fd19..10363a5 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -171,6 +171,13 @@ def test_connect_params_passed_through(monkeypatch: pytest.MonkeyPatch) -> None: assert kw["proxy"] == "http://proxy:3128" +def test_no_message_size_limit(monkeypatch: pytest.MonkeyPatch) -> None: + fake = _FakeConnect(([_news("A")], None)) + monkeypatch.setattr(CONNECT, fake) + list(_ws(reconnect=False).stream("r")) + assert fake.kwargs[0]["max_size"] is None # websockets' default rejects messages over 1 MiB + + def test_custom_reconnect_backoff(monkeypatch: pytest.MonkeyPatch) -> None: slept: list[float] = [] monkeypatch.setattr( @@ -512,6 +519,13 @@ def test_async_url_and_params(monkeypatch: pytest.MonkeyPatch) -> None: assert fake.kwargs[0]["proxy"] == "http://proxy:3128" +def test_async_no_message_size_limit(monkeypatch: pytest.MonkeyPatch) -> None: + fake = _FakeAsyncConnect(([_news("A")], None)) + monkeypatch.setattr(CONNECT_ASYNC, fake) + _atitles(_ws(reconnect=False)) + assert fake.kwargs[0]["max_size"] is None + + def test_async_yields_whole_server_responses(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(CONNECT_ASYNC, _FakeAsyncConnect(([_news("A", "B"), _news("C")], None)))