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
73 changes: 48 additions & 25 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 (`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

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,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()
```
Expand All @@ -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)

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

Expand All @@ -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

Expand Down
24 changes: 14 additions & 10 deletions examples/basic_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from __future__ import annotations

import datetime
import os
from pathlib import Path

Expand All @@ -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.
Expand All @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
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.3.5"
__version__ = "0.4.0"

__all__ = [
"NewsDataApiClient",
Expand Down
Loading
Loading