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
51 changes: 36 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,18 @@ dependency is Jackson for JSON. Thread-safe.
<dependency>
<groupId>io.newsdata</groupId>
<artifactId>newsdataapi</artifactId>
<version>0.3.0</version>
<version>0.4.0</version>
</dependency>
```

### Gradle (Kotlin DSL)
```kotlin
implementation("io.newsdata:newsdataapi:0.2.1")
implementation("io.newsdata:newsdataapi:0.4.0")
```

### Gradle (Groovy DSL)
```groovy
implementation 'io.newsdata:newsdataapi:0.2.1'
implementation 'io.newsdata:newsdataapi:0.4.0'
```

## Quickstart
Expand Down Expand Up @@ -141,7 +141,8 @@ for (ArticleV2 a : resp.articlesV2(client.objectMapper())) {
| `imageUrl()`, `videoUrl()` | `media().imageUrl()`, `media().videoUrl()` |
| `sentiment()`, `sentimentStats()` | `ai().sentiment().label()`, `ai().sentiment().score()` |
| `aiTag()`, `aiRegion()`, `aiOrg()` | `ai().tag()`, `ai().region()`, `ai().organization()` |
| — | `ai().summary()`, `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` |
| `aiSummary()` | `ai().summary()` |
| `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` | `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` |

A group the API did not send (`source`, `media`, `ai`) is `null`; a list field
it did not send is an empty list. `ai().region()` entries are comma-separated
Expand All @@ -168,6 +169,14 @@ field holds the single notice, and a withheld sentiment carries it in

The real-time service is v2 only — there are no v1 WebSocket methods.

v1 articles decode with `resp.articles(client.objectMapper())`. On plans
without the AI add-ons, `ai_tag`, `ai_region` and `ai_org` arrive as the API's
notice string: the list then holds that single notice
(`ArticleV2.isPlanNotice(value)` recognises it), and `sentimentStats()` is
`null`. If the results cannot be decoded at all, `articles()` and
`articlesV2()` throw a `NewsdataException` carrying the decoding error rather
than returning an empty list.

`params` is a `Map<String, Object>`. Use the bundled [`Params`](src/main/java/io/newsdata/api/Params.java) helper for fluent construction — `null` values are dropped automatically so you can chain optional fields without `if`-guards. Values may be `String`, `Number`, `Boolean`, or `Collection<String>` (sent comma-joined). Parameter names are case-insensitive — `qInTitle` and `qintitle` are equivalent.

## Pagination
Expand All @@ -194,19 +203,19 @@ client.paginate(Endpoint.LATEST, Params.of().with("q", "news"))
client.latest(Params.of().with("rawQuery", "q=bitcoin&country=us&language=en"));
```

`rawQuery` is mutually exclusive with every other parameter and is parsed and validated against the endpoint's allowed keys before the request leaves.
`rawQuery` is mutually exclusive with every other parameter and is parsed and validated against the endpoint's allowed keys before the request leaves; for the v1 count endpoints it must also carry `from_date` and `to_date`. It works with `scrollAll`, `paginate` and `websocketRegister` too: parameters are validated once, and the page cursor (or `news_type`) is added afterwards.

## Client-side validation

A `NewsdataValidationException` is thrown — before any HTTP request — when:

- a parameter is not accepted by that endpoint;
- mutually-exclusive parameters are set together — `q`/`qInTitle`/`qInMeta`, `country`/`excludecountry`, `category`/`excludecategory`, `language`/`excludelanguage`, `domain`/`domainurl`/`excludedomain`;
- mutually-exclusive parameters are set together — version 1: `q`/`qInTitle`/`qInMeta`, `country`/`excludecountry`, `category`/`excludecategory`, `language`/`excludelanguage`, `domain`/`domainurl`/`excludedomain`/`excludedomainurl`; version 2: `q`/`q_in_title`/`q_in_meta`, `country`/`exclude_country`, `category`/`exclude_category`, `language`/`exclude_language`, `source_url`/`exclude_source_url`;
- `size` is outside 1–50;
- `sentiment_score` is set without `sentiment`;
- a count endpoint is missing `from_date` or `to_date`.

Booleans for `full_content`, `image`, `video`, and `removeduplicate` are coerced to `"1"`/`"0"`.
Booleans for `full_content`, `image`, `video`, `removeduplicate`, and the version 2 `content` and `remove_duplicate` are coerced to `"1"`/`"0"`.

## Real-time news (WebSocket)

Expand Down Expand Up @@ -262,12 +271,22 @@ rejection — bad API key or unknown
`registration_id`, exhausted API credits, or too many simultaneous devices — throws
`NewsdataWebSocketAuthException` and is **not** retried.

The server always accepts the handshake and then closes with code **1008** when
the connection is refused, carrying one of three reasons: `invalid credentials
or registration not found`, `api limit reached`, or `device limit reached` (more
than 5 devices on one `registration_id`). Every other close code — including
`1013` (`send timeout`, meaning the client read too slowly) — is transient and
reconnects.
When it refuses a connection, the server accepts the handshake, sends one error
response — `{"status":"error","results":{"message":"…","code":"…"}}` — and
closes. That response never reaches your handler: it becomes the exception,
whose message is the server's explanation, `errorCode()` its code and
`responseBody()` the raw response. Close code **1008** is permanent; its reason
is the bare code: `Unauthorized` or `InvalidRequest` (bad key or unknown
`registration_id`), `ApiLimitExceeded` or `ApiKeyLimitExceeded` (credits used
up), `DeviceLimitExceeded` (more than 5 devices on one `registration_id`).
Every other close code — `1011` (server error) and `1013` (the client read too
slowly) included — is transient and reconnects; with `.reconnect(false)` it
throws `NewsdataWebSocketException` carrying the server's message.

A quiet stream is not a failure: news can be minutes apart. When nothing
arrives for `pingInterval` (default 20 s) the client sends a ping, and only
when nothing comes back within `pingTimeout` (default 20 s) is the connection
treated as dead and reconnected.

**Each delivered article consumes 1 API credit per connected device.**

Expand All @@ -277,7 +296,7 @@ Catch it like any other client error:
try {
ws.stream(registrationId, response -> true);
} catch (NewsdataWebSocketAuthException e) {
System.err.println("rejected: " + e.getMessage());
System.err.println("rejected (" + e.errorCode() + "): " + e.getMessage());
} catch (NewsdataWebSocketException e) {
System.err.println("stream error: " + e.getMessage());
}
Expand All @@ -292,6 +311,8 @@ NewsDataApiWebSocket ws = NewsDataApiWebSocket.builder(client)
.reconnectDelay(Duration.ofSeconds(1)) // first delay; doubles each retry
.reconnectDelayMax(Duration.ofSeconds(30)) // cap on the delay
.handshakeTimeout(Duration.ofSeconds(10)) // opening handshake bound
.pingInterval(Duration.ofSeconds(20)) // silence before a keepalive ping; ZERO = off
.pingTimeout(Duration.ofSeconds(20)) // wait for a reply before reconnecting
.headers(Map.of("X-Trace", "abc")) // extra handshake headers
.build();
```
Expand Down Expand Up @@ -357,7 +378,7 @@ NewsDataApiClient client = NewsDataApiClient.builder()

`baseUrl` 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.3.0 it included the version (`https://newsdata.io/api/1/`), so drop the trailing `1/` if you override it.

Retries cover network errors, HTTP 429, and 5xx. 429 honours the `Retry-After` header (integer seconds or HTTP-date); otherwise backoff is exponential. Auth (401/403) and other 4xx errors are never retried. The API key is redacted from URLs passed to the logger.
Retries cover network errors, HTTP 429, and 5xx. A 429 waits for its `Retry-After` (integer seconds or HTTP-date) plus one second; without the header, backoff is exponential. When `Retry-After` is longer than `retryBackoffMax`, the call throws `NewsdataRateLimitException` at once with `retryAfter()` set, leaving the wait to you. Auth (401/403) and other 4xx errors are never retried. The API key is redacted from URLs passed to the logger and from error messages; a `baseUrl` that is not a valid absolute URL is rejected by `build()`.

A 429 that waiting cannot fix is never retried: `NewsdataApiLimitExceededException` means the account's whole credit pool is exhausted, `NewsdataApiKeyLimitExceededException` means this one key hit its own cap while the account may still have credits, and both extend `NewsdataRateLimitException`, so an existing `catch` on that type keeps working. `RegistrationLimitExceeded` is also never retried, but keeps the plain `NewsdataRateLimitException` — it is about real-time registration slots, not credits, and is fixed by deleting a registration.

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>io.newsdata</groupId>
<artifactId>newsdataapi</artifactId>
<version>0.3.0</version>
<version>0.4.0</version>
<packaging>jar</packaging>

<name>newsdataapi</name>
Expand Down
55 changes: 44 additions & 11 deletions src/main/java/io/newsdata/api/Article.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

/**
* One news article from API v1 of the Newsdata.io API.
Expand All @@ -16,6 +17,15 @@
* {@code article.getTitle()}.
*
* <p>JSON keys use the API's snake_case; component names are camelCase.
*
* <p>The crypto endpoint fills {@code coin}; the market endpoint fills
* {@code symbol} and {@code marketId}.
*
* <p>On plans without the AI add-ons the API sends a plain notice string in
* place of some fields: a list field then holds that one notice (see
* {@link ArticleV2#isPlanNotice(String)}) and {@code sentimentStats} is
* {@code null}. A field the API does not send (or sends as {@code null}) is
* {@code null}.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public record Article(
Expand All @@ -24,8 +34,8 @@ public record Article(
@JsonProperty("link") String link,
@JsonProperty("description") String description,
@JsonProperty("content") String content,
@JsonProperty("keywords") List<String> keywords,
@JsonProperty("creator") List<String> creator,
@JsonProperty("keywords") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> keywords,
@JsonProperty("creator") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> creator,
@JsonProperty("video_url") String videoUrl,
@JsonProperty("image_url") String imageUrl,
@JsonProperty("pubDate") String pubDate,
Expand All @@ -36,14 +46,37 @@ public record Article(
@JsonProperty("source_icon") String sourceIcon,
@JsonProperty("source_name") String sourceName,
@JsonProperty("language") String language,
@JsonProperty("country") List<String> country,
@JsonProperty("category") List<String> category,
@JsonProperty("ai_tag") List<String> aiTag,
@JsonProperty("ai_region") List<String> aiRegion,
@JsonProperty("ai_org") List<String> aiOrg,
@JsonProperty("country") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> country,
@JsonProperty("category") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> category,
@JsonProperty("ai_tag") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> aiTag,
@JsonProperty("ai_region") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> aiRegion,
@JsonProperty("ai_org") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> aiOrg,
@JsonProperty("sentiment") String sentiment,
@JsonProperty("sentiment_stats") Map<String, Object> sentimentStats,
@JsonProperty("sentiment_stats") @JsonDeserialize(using = LenientMapDeserializer.class)
Map<String, Object> sentimentStats,
@JsonProperty("datatype") String dataType,
@JsonProperty("symbol") List<String> symbol,
@JsonProperty("market_id") List<String> marketId
) {}
@JsonProperty("symbol") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> symbol,
@JsonProperty("market_id") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> marketId,
@JsonProperty("fetched_at") String fetchedAt,
@JsonProperty("ai_summary") String aiSummary,
@JsonProperty("duplicate") Boolean duplicate,
@JsonProperty("coin") @JsonDeserialize(using = NullableStringListDeserializer.class) List<String> coin
) {
/**
* The constructor from before {@code fetchedAt}, {@code aiSummary},
* {@code duplicate} and {@code coin} were added; those four are
* {@code null}. Kept so code that builds articles by hand still compiles.
*/
public Article(String articleId, String title, String link, String description, String content,
List<String> keywords, List<String> creator, String videoUrl, String imageUrl,
String pubDate, String pubDateTZ, String sourceId, Integer sourcePriority, String sourceUrl,
String sourceIcon, String sourceName, String language, List<String> country,
List<String> category, List<String> aiTag, List<String> aiRegion, List<String> aiOrg,
String sentiment, Map<String, Object> sentimentStats, String dataType, List<String> symbol,
List<String> marketId) {
this(articleId, title, link, description, content, keywords, creator, videoUrl, imageUrl,
pubDate, pubDateTZ, sourceId, sourcePriority, sourceUrl, sourceIcon, sourceName,
language, country, category, aiTag, aiRegion, aiOrg, sentiment, sentimentStats,
dataType, symbol, marketId, null, null, null, null);
}
}
13 changes: 10 additions & 3 deletions src/main/java/io/newsdata/api/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
/**
* Static configuration: base URL, endpoint paths, HTTP defaults, and the
* per-endpoint accepted-parameter sets. Mirrors the server-side filter
* mapping and the official Python/PHP/Node/Go/Dart clients.
* mapping.
*
* <p>Parameter names are stored lowercase here; user-supplied keys are
* lowercased before validation (the API is case-insensitive, so
Expand Down Expand Up @@ -102,6 +102,12 @@ private Constants() {}
/** Bound on the opening handshake. */
public static final Duration WS_HANDSHAKE_TIMEOUT = Duration.ofSeconds(10);

/** Keepalive: silence after which the client sends a ping. */
public static final Duration WS_PING_INTERVAL = Duration.ofSeconds(20);

/** Keepalive: how long to wait for anything after a ping before the connection counts as dead. */
public static final Duration WS_PING_TIMEOUT = Duration.ofSeconds(20);

/**
* Error codes on a 429 that waiting cannot fix, so they are never retried.
* {@code ApiLimitExceeded} and {@code ApiKeyLimitExceeded} mean the API
Expand Down Expand Up @@ -294,14 +300,15 @@ NewsdataRateLimitException create(String message, int statusCode, String respons
// Real-time query registration. The real-time service is v2 only,
// so these are the v2 filter names. No date or paging filters apply
// — a registered query matches news as it is published.
// `news_type` is set by websocketRegister, not by the caller.
// `news_type` is not accepted from the caller: websocketRegister
// adds it after validation (so it also works with rawQuery).
Map.entry("websocket_register", Set.of(
"q", "q_in_title", "q_in_meta", "country", "exclude_country",
"category", "exclude_category", "language", "exclude_language",
"source_url", "exclude_source_url", "source_priority", "timezone",
"content", "image", "video", "remove_duplicate", "tag", "sentiment",
"sentiment_score", "region", "organization", "creator", "datatype",
"exclude_field", "news_type"
"exclude_field"
)),
Map.entry("websocket_fetch", Set.<String>of()),
Map.entry("websocket_delete", Set.of("registration_id"))
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/io/newsdata/api/LenientMapDeserializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.newsdata.api;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

/**
* Reads a JSON object as a {@code Map}, and anything else as {@code null}.
*
* <p>On plans without the AI add-ons the API replaces object fields such as
* {@code sentiment_stats} with a plain "not in your plan" notice string. Plain
* map deserialization fails on that and loses the whole page; this reads the
* notice as "no data" instead.
*
* <p>Package-private: it is an implementation detail of {@link Article}.
*/
final class LenientMapDeserializer extends JsonDeserializer<Map<String, Object>> {

@Override
public Map<String, Object> deserialize(JsonParser parser, DeserializationContext context)
throws IOException {
JsonNode node = parser.readValueAsTree();
if (node == null || !node.isObject()) return null;
return context.readTreeAsValue(node,
context.getTypeFactory().constructMapType(LinkedHashMap.class, String.class, Object.class));
}
}
Loading
Loading