Official Java client (SDK) for the Newsdata.io News
API. Wraps every endpoint (latest, archive, sources, crypto, market,
count, crypto/count, market/count) with client-side parameter
validation, automatic retries with exponential backoff, lazy Stream-based
pagination, and a typed exception hierarchy.
Built on Java 17's built-in java.net.http.HttpClient — the only runtime
dependency is Jackson for JSON. Thread-safe.
<dependency>
<groupId>io.newsdata</groupId>
<artifactId>newsdataapi</artifactId>
<version>0.4.0</version>
</dependency>implementation("io.newsdata:newsdataapi:0.4.0")implementation 'io.newsdata:newsdataapi:0.4.0'import io.newsdata.api.*;
import java.util.List;
NewsDataApiClient client = NewsDataApiClient.builder()
.apiKey(System.getenv("NEWSDATA_API_KEY"))
.build();
NewsdataResponse resp = client.latest(Params.of()
.with("q", "bitcoin")
.with("country", List.of("us", "gb"))
.with("language", List.of("en")));
for (Article article : resp.articles(client.objectMapper())) {
System.out.println(article.title() + " - " + article.link());
}The API has two versions. v2 is the current one; the v1 methods keep working unchanged.
| Method | Endpoint | Notes |
|---|---|---|
client.newsV2(params) |
/2/news |
Latest news, or historical with from_date / to_date |
client.marketV2(params) |
/2/market |
Market / financial news |
client.cryptoV2(params) |
/2/crypto |
Cryptocurrency news |
client.sourcesV2(params) |
/2/sources |
Available sources (single page) |
client.countNewsV2(params) |
/2/count/news |
Aggregate news counts |
client.countMarketV2(params) |
/2/count/market |
Aggregate market counts |
client.countCryptoV2(params) |
/2/count/crypto |
Aggregate crypto counts |
client.websocketRegister(params) |
/2/websocket/register |
Register a real-time query |
client.websocketFetch() |
/2/websocket/fetch |
List registered queries |
client.websocketDelete(id) |
/2/websocket/delete |
Delete a registered query |
v2 renames the filter vocabulary to snake_case and folds the four domain filters into two:
| v1 | v2 |
|---|---|
qInTitle, qInMeta |
q_in_title, q_in_meta |
excludecountry, excludecategory, excludelanguage |
exclude_country, exclude_category, exclude_language |
domain, domainurl, excludedomain, excludedomainurl |
source_url, exclude_source_url |
prioritydomain |
source_priority |
full_content |
content |
removeduplicate, excludefield |
remove_duplicate, exclude_field |
coin and market_id keep their names.
NewsdataResponse resp = client.newsV2(Params.of()
.with("q_in_title", "tesla")
.with("source_url", "bbc.com")
.with("content", true));The v2 envelope spells its total and cursor total_results / next_page
where v1 spells them totalResults / nextPage. NewsdataResponse reads
either, so totalResults(), nextPage(), scrollAll and paginate behave
the same whichever version answered. Pass Endpoint.NEWS_V2 and friends to
the pagination helpers.
There is no /2/archive — newsV2 covers historical news through
from_date / to_date.
v2 renamed and regrouped the article fields, so the v2 endpoints and the
real-time stream decode with articlesV2(…) and ArticleV2, while the v1
endpoints keep articles(…) and Article:
NewsdataResponse resp = client.newsV2(Params.of().with("q", "bitcoin"));
for (ArticleV2 a : resp.articlesV2(client.objectMapper())) {
System.out.println(a.title() + " " + a.url() + " " + a.publishedAt());
System.out.println(a.source().name() + " " + a.source().priority());
System.out.println(a.media().imageUrl());
System.out.println(a.ai().summary() + " " + a.ai().sentiment().label() + " " + a.ai().tag());
}v1 (Article) |
v2 (ArticleV2) |
|---|---|
articleId() |
id() |
link() |
url() |
pubDate() |
publishedAt() |
description() |
metaDescription() |
keywords() |
keyword() |
symbol() |
ticker() |
sourceName(), sourceUrl(), sourcePriority(), sourceIcon() |
source().name(), source().url(), source().priority(), source().iconUrl() |
imageUrl(), videoUrl() |
media().imageUrl(), media().videoUrl() |
sentiment(), sentimentStats() |
ai().sentiment().label(), ai().sentiment().score() |
aiTag(), aiRegion(), aiOrg() |
ai().tag(), ai().region(), ai().organization() |
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
paths from the narrowest place to the widest ("mumbai,maharashtra,india"), so
do not split them on commas.
A field your plan does not include arrives as the API's notice string in place
of the data ("ONLY AVAILABLE IN PAID PLANS"). Decoding tolerates it — a list
field holds the single notice, and a withheld sentiment carries it in
label() — and ArticleV2.isPlanNotice(value) tells it apart from real data.
| Method | Endpoint | Notes |
|---|---|---|
client.latest(params) |
/1/latest |
Real-time news |
client.archive(params) |
/1/archive |
Historical news |
client.sources(params) |
/1/sources |
Available sources (single page) |
client.crypto(params) |
/1/crypto |
Cryptocurrency news |
client.market(params) |
/1/market |
Market / financial news |
client.count(params) |
/1/count |
Aggregate counts (requires from_date, to_date) |
client.cryptoCount(params) |
/1/crypto/count |
Aggregate crypto counts |
client.marketCount(params) |
/1/market/count |
Aggregate market counts |
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 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.
Two helpers — both work for every endpoint except sources:
// 1) scrollAll: follow nextPage and return one merged response.
NewsdataResponse all = client.scrollAll(
Endpoint.LATEST,
Params.of().with("q", "news"),
200); // maxResults; 0 = no cap
// 2) paginate: lazy Stream<NewsdataResponse>, one page at a time.
// Composes with .limit, .takeWhile, .filter, etc.
client.paginate(Endpoint.LATEST, Params.of().with("q", "news"))
.limit(5)
.forEach(page -> process(page.articles(client.objectMapper())));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; 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.
A NewsdataValidationException is thrown — before any HTTP request — when:
- a parameter is not accepted by that endpoint;
- 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; sizeis outside 1–50;sentiment_scoreis set withoutsentiment;- a count endpoint is missing
from_dateorto_date.
Booleans for full_content, image, video, removeduplicate, and the version 2 content and remove_duplicate are coerced to "1"/"0".
The real-time service is part of API v2. Register a query first — the returned
registration_id identifies it from then on:
NewsdataResponse registered = client.websocketRegister(
Params.of().with("q", "bitcoin").with("language", "en"));
String registrationId = registered.results().path("registration_id").asText();websocketRegister takes the same filter names as newsV2 (q,
q_in_title, country, exclude_country, source_url, content,
exclude_field, timezone, …) — the date, paging and sorting filters, id
and url don't apply to a standing query. Registering an identical query twice
throws NewsdataApiException with status 409; the existing id is in its
response body.
websocketFetch() lists every registered query: results() is an array with
one entry per query, carrying its registration_id, the filters it was
registered with (query), how many devices are streaming it now
(active_clients) and when one last connected (last_used, UTC).
websocketDelete(id) removes one. Once every registration the plan allows is
in use, registering another throws a 429 NewsdataRateLimitException carrying
the code RegistrationLimitExceeded; it is not retried, since only deleting a
registration frees a slot.
Then stream. Each response carries status, total_results and results —
read through status(), totalResults() and results() — and its articles
use the v2 layout, so decode them with articlesV2(…). The handler returns
true to keep streaming and false to stop:
try (NewsDataApiWebSocket ws = new NewsDataApiWebSocket(client)) {
ws.stream(registrationId, response -> {
for (ArticleV2 a : response.articlesV2(client.objectMapper())) {
System.out.println(a.title() + " - " + a.url() + " (" + a.source().name() + ")");
}
return true;
});
}stream blocks until the handler returns false, the instance is closed, or
the calling thread is interrupted. Closing from another thread — including via
try-with-resources — ends an in-flight stream.
Transient drops (network errors, server restarts, abnormal closes) are
reconnected automatically with a capped exponential backoff. Build with
.reconnect(false) to stop on the first disconnect instead. A permanent
rejection — bad API key or unknown
registration_id, exhausted API credits, or too many simultaneous devices — throws
NewsdataWebSocketAuthException and is not retried.
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.
Catch it like any other client error:
try {
ws.stream(registrationId, response -> true);
} catch (NewsdataWebSocketAuthException e) {
System.err.println("rejected (" + e.errorCode() + "): " + e.getMessage());
} catch (NewsdataWebSocketException e) {
System.err.println("stream error: " + e.getMessage());
}All connection options go through the builder:
NewsDataApiWebSocket ws = NewsDataApiWebSocket.builder(client)
.baseUrl("wss://ws.newsdata.io/ws/event") // staging / self-hosted / proxied
.reconnect(true) // default true
.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();All SDK exceptions extend RuntimeException, so they don't pollute method signatures with throws clauses. Catch by type to react to specific failures:
import io.newsdata.api.exception.*;
try {
client.latest(Params.of().with("q", "news"));
} catch (NewsdataValidationException e) {
// bad parameter — e.param()
} catch (NewsdataAuthException e) {
// 401 / 403
} catch (NewsdataRateLimitException e) {
// 429 — e.retryAfter() (seconds)
} catch (NewsdataServerException e) {
// 5xx
} catch (NewsdataApiException e) {
// other API errors — e.statusCode(), e.responseBody()
} catch (NewsdataNetworkException e) {
// I/O, timeout, interrupted — e.getCause()
}Hierarchy:
NewsdataException (extends RuntimeException)
├── NewsdataValidationException (.param())
├── NewsdataApiException (.statusCode(), .responseBody())
│ ├── NewsdataAuthException (401 / 403)
│ ├── NewsdataRateLimitException (429; .retryAfter())
│ │ ├── NewsdataApiLimitExceededException (account credits gone)
│ │ └── NewsdataApiKeyLimitExceededException (this key's cap gone)
│ │ (RegistrationLimitExceeded stays on NewsdataRateLimitException —
│ │ real-time registration slots, not credits)
│ └── NewsdataServerException (5xx)
├── NewsdataNetworkException (.getCause())
└── NewsdataWebSocketException (real-time stream)
└── NewsdataWebSocketAuthException (policy-violation close 1008)
NewsDataApiClient client = NewsDataApiClient.builder()
.apiKey(apiKey)
.timeout(Duration.ofSeconds(30)) // per-request
.maxRetries(5) // 1 = no retry
.retryBackoff(Duration.ofSeconds(2)) // base, exponential
.retryBackoffMax(Duration.ofSeconds(60)) // cap on a single sleep
.paginationDelay(Duration.ofSeconds(1))
.baseUrl("https://staging.example/api") // root, no version
.includeHeaders(true) // attach response headers
.httpClient(myCustomHttpClient) // proxies, mTLS, etc.
.logger((level, msg) -> System.out.println(level + ": " + msg))
.build();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. 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.
NewsDataApiClient is thread-safe — share one instance across your application. The underlying HttpClient reuses connections.
mvn -B verify # compile + run the unit suite (33 tests, no API key needed)
mvn -B test # tests onlyThe test suite uses Java's built-in com.sun.net.httpserver.HttpServer as a local mock — no WireMock, no network, no external test dep.
Releases are automated via .github/workflows/publish.yml — push a v-prefixed tag whose number matches pom.xml's <version> and the workflow signs, uploads, and publishes.
# bump <version> in pom.xml first
git commit -am "Bump to 0.0.2"
git tag -a v0.0.2 -m "v0.0.2"
git push origin main v0.0.2 # tag push fires publish.ymlMaven Central is the heaviest of the registries to wire up — it predates OIDC trusted publishing and requires GPG-signed artifacts. The good news: you do this once.
- Sign up at https://central.sonatype.com/.
- Account → Add Namespace → enter
io.newsdata. - Verify by adding the displayed TXT record to
newsdata.io's DNS. Propagation typically takes minutes; longer for stubborn DNS providers.
On https://central.sonatype.com/account → Generate User Token → copy the token name and token password (you can't see them again).
gpg --gen-key # interactive; default RSA 3072 is fine
gpg --list-secret-keys --keyid-format LONG # note the key ID (after sec rsa3072/)
gpg --keyserver keys.openpgp.org --send-keys <KEY_ID> # upload public key
gpg --export-secret-keys --armor <KEY_ID> > private.key # this file goes into GitHubRepo Settings → Secrets and variables → Actions → New repository secret:
| Secret name | Value |
|---|---|
MAVEN_USERNAME |
the user-token name from step 2 |
MAVEN_PASSWORD |
the user-token password from step 2 |
GPG_PRIVATE_KEY |
the full contents of private.key from step 3 (including -----BEGIN PGP PRIVATE KEY BLOCK----- lines) |
GPG_PASSPHRASE |
the passphrase you set in step 3 |
Then delete private.key from your machine.
Push a tag (git push origin v0.0.2). The workflow:
- Verifies the tag matches
<version>inpom.xml. - Runs
mvn verify(all tests). - Runs
mvn -Prelease deploy— signs every artifact (jar, sources, javadoc, pom) with your GPG key and uploads via thecentral-publishing-maven-plugin. - With
autoPublish=trueset in the release profile, the deployment is released directly. (For a manual approval gate, setautoPublish=falseand approve on https://central.sonatype.com/publishing.)
Artifacts appear on Maven Central indexes within ~10–30 minutes after a successful workflow run, then in the public search within 1–4 hours.
Unlike npm, PyPI, and pub.dev, the Sonatype Central Portal doesn't yet support tokenless GitHub Actions publishing via OIDC — it's on their roadmap. Until then, the user-token + GPG-signing flow above is the supported path.
Official Newsdata.io clients across languages and runtimes:
- Python — newsdataapi/python-client (PyPI)
- Node.js — newsdataapi/newsdata-nodejs-client (npm)
- React (hooks) — newsdataapi/newsdata-reactjs-client (npm)
- PHP — newsdataapi/php-client (Packagist)
- .NET — newsdataapi/newsdata-dotnet-sdk (NuGet)
- Go — newsdataapi/newsdata-go-client (pkg.go.dev)
- Dart / Flutter — newsdataapi/newsdata-flutter-client (pub.dev)
- MCP Server (AI assistants) — newsdataapi/newsdata.io-mcp (PyPI)
Also see free news datasets for ML / NLP work.
