diff --git a/README.md b/README.md index 17f8b05..fb2a295 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 (`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). +`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). ## 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.news(q="bitcoin", country="us", language="en") + response = client.latest_api(q="bitcoin", country="us", language="en") for article in response["results"]: - print(article["title"], "-", article["url"]) + print(article["title"], "-", article["link"]) ``` 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.news(q="bitcoin", country="us", language="en") + response = client.latest_api(q="bitcoin", country="us", language="en") for article in response["results"]: - print(article["title"], "-", article["url"]) + print(article["title"], "-", article["link"]) finally: client.close() ``` @@ -58,55 +58,34 @@ finally: | 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 | +| `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 | -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. +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). 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.news(q="news") +response = client.latest_api(q="news") -# 2. Auto-merge — follow next_page cursors and return one combined dict. -merged = client.news(q="news", scroll=True, max_result=200) +# 2. Auto-merge — follow nextPage cursors and return one combined dict. +merged = client.latest_api(q="news", scroll=True, max_result=200) # 3. Iterate one response per page (a generator). -for page in client.news(q="news", paginate=True, max_pages=5): +for page in client.latest_api(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 `next_page`. +`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`. ## Real-time news (WebSocket) @@ -121,9 +100,9 @@ response = ws.websocket_register(q="bitcoin", language="en") registration_id = response["results"]["registration_id"] ``` -`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. +`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. -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: +Then stream — each yielded response has the familiar `status` / `totalResults` / `results` shape: ```python for response in ws.stream(registration_id): @@ -198,7 +177,7 @@ from newsdataapi import ( ) try: - client.news(q="news") + client.latest_api(q="news") except NewsdataAuthError as e: print(f"bad API key (HTTP {e.status_code})") except NewsdataApiKeyLimitExceededError: @@ -245,7 +224,7 @@ client = NewsDataApiClient(apikey, folder_path="./out") client.save_to_csv(response, filename="latest_news") ``` -`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. +`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. The function is also importable as a standalone: @@ -275,7 +254,7 @@ 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 `/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. +`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. 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. diff --git a/examples/basic_usage.py b/examples/basic_usage.py index f34fd2e..e5032aa 100644 --- a/examples/basic_usage.py +++ b/examples/basic_usage.py @@ -16,7 +16,6 @@ from __future__ import annotations -import datetime import os from pathlib import Path @@ -43,32 +42,29 @@ 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.news(q="bitcoin", country="us", language="en") + response = client.latest_api(q="bitcoin", country="us", language="en") results = response["results"] print( - f"news: {len(results)} articles, " - f"total available: {response.get('total_results')}" + f"latest: {len(results)} articles, " + f"total available: {response.get('totalResults')}" ) # 2. Pagination — yields one response per page, capped at max_pages. for page_index, page in enumerate( - client.crypto(q="ethereum", paginate=True, max_pages=3), + client.crypto_api(q="ethereum", paginate=True, max_pages=3), start=1, ): print(f" crypto page {page_index}: {len(page['results'])} articles") - # 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( + # 3. Scroll — auto-follows nextPage cursors and merges into one dict. + merged = client.archive_api( q="apple", - from_date=(now - datetime.timedelta(days=7)).strftime(date_format), - to_date=(now - datetime.timedelta(days=1)).strftime(date_format), + from_date="2024-01-01 00:00:00", + to_date="2024-01-31 00:00:00", scroll=True, max_result=50, ) - print(f"scrolled news: {len(merged['results'])} articles") + print(f"scrolled archive: {len(merged['results'])} articles") # 4. Persist results to CSV. ``folder_path`` was set on the client, so # we don't pass it again here. @@ -85,7 +81,7 @@ def example_error_handling(apikey: str) -> None: """ with NewsDataApiClient(apikey) as client: try: - client.news(q="news") + client.latest_api(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 850fa85..b8c72d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,11 +91,6 @@ 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 206e67a..1047bf8 100644 --- a/src/newsdataapi/__init__.py +++ b/src/newsdataapi/__init__.py @@ -17,7 +17,7 @@ ) from .websocket import NewsDataApiWebSocket -__version__ = "0.4.0" +__version__ = "0.4.1" __all__ = [ "NewsDataApiClient", diff --git a/src/newsdataapi/client.py b/src/newsdataapi/client.py index 714814d..1fac64c 100644 --- a/src/newsdataapi/client.py +++ b/src/newsdataapi/client.py @@ -5,7 +5,6 @@ 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 @@ -361,16 +360,6 @@ 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. # --------------------------------------------------------------------------- @@ -384,17 +373,13 @@ class NewsDataApiClient: with NewsDataApiClient("YOUR_API_KEY") as client: 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 by the client). Use the context manager (``with``) form, or call :meth:`close` explicitly, to release the session. All endpoint parameters are keyword-only except for the required - ``from_date`` / ``to_date`` on the deprecated ``*count_api`` methods. + ``from_date`` / ``to_date`` on the ``*count_api`` methods. Most parameters accept either a single string or a ``list[str]``; lists are comma-joined before being sent to the API. """ @@ -560,15 +545,11 @@ 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, { @@ -658,12 +639,8 @@ 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, { @@ -721,13 +698,9 @@ 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, @@ -778,12 +751,8 @@ 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, { @@ -866,12 +835,8 @@ 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, { @@ -958,16 +923,12 @@ 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, { @@ -1045,15 +1006,11 @@ 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, { @@ -1129,15 +1086,11 @@ 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, { diff --git a/src/newsdataapi/csv_export.py b/src/newsdataapi/csv_export.py index 568f470..cc3ec22 100644 --- a/src/newsdataapi/csv_export.py +++ b/src/newsdataapi/csv_export.py @@ -21,8 +21,8 @@ def save_to_csv( """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. + In responses from the ``*_api`` methods, dict and list cell values are + stringified instead. Args: response: A response dict from the NewsData API. Expected to have a diff --git a/tests/test_unit.py b/tests/test_unit.py index e3386c0..f9d6d27 100644 --- a/tests/test_unit.py +++ b/tests/test_unit.py @@ -9,7 +9,6 @@ import csv import sys -import warnings from datetime import datetime, timedelta, timezone from email.utils import format_datetime from pathlib import Path @@ -1909,63 +1908,6 @@ def test_v2_scroll_and_paginate_mutually_exclusive(client: NewsDataApiClient) -> 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) # ===========================================================================