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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 69 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

</div>

`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

Expand All @@ -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:
Expand All @@ -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
Expand All @@ -100,22 +140,22 @@ 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):

```python
with NewsDataApiWebSocket(client) as ws:
for response in ws.stream(registration_id):
print(response["totalResults"])
print(response["total_results"])
break
```

Expand All @@ -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())
```
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:

Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions examples/websocket_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion src/newsdataapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
)
from .websocket import NewsDataApiWebSocket

__version__ = "0.4.1"
__version__ = "0.4.2"

__all__ = [
"NewsDataApiClient",
Expand Down
2 changes: 2 additions & 0 deletions src/newsdataapi/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}


Expand Down
8 changes: 4 additions & 4 deletions src/newsdataapi/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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
3 changes: 2 additions & 1 deletion src/newsdataapi/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading