Twitter (X) API in Java: a typed client with HttpClient and Jackson

- No SDK needed: one shared
HttpClient(it is immutable and pools connections) plus anX-API-Keyheader reaches every read endpoint; the client on this page compiles cleanly withjavac -Xlint:allon JDK 21 with Jackson 2.23.0. - Ids are strings, keep them that way: all 1,160 tweet ids we pulled were 19-digit JSON strings above 2^53; 1,112 of them (95.9%) would change value through a
double. - Counters fit in
inttoday, uselonganyway: the biggestviewCountin the sample was 12,145,290, 0.57% ofInteger.MAX_VALUE; the median was 4,642. - One date pattern parses everything:
EEE MMM dd HH:mm:ss Z yyyywithLocale.ROOTparsed 1,160 of 1,160createdAtvalues with zero failures. - Paging is a
Stream: wraphas_next_page/next_cursorin anIteratorand callers writeapi.search(q, "Latest", 3).limit(50); error text lives inmsg,message(auth) ordetail(HTTP 400). - Cost: $0.15 per 1,000 tweets returned versus $0.005 per post read ($5 per 1,000) on X's pay-per-usage rate card, about 33x apart; this whole study cost about $0.18.
Search for a Java Twitter API example and the majority of what comes back was written for X's own OAuth-protected API: Twitter4J snippets, the beta twitter-api-java-sdk that X generated from its OpenAPI spec, or tutorials built around consumer keys and bearer tokens. None of them shows what a tweet object actually looks like once you put a Java type on every field, and that is where many client bugs come from: an id truncated by a double, a counter declared int, a date pattern that breaks on a non-English default locale.
This guide builds a small, typed Java 17+ client for the TwitterAPI.io read endpoints with only the JDK's java.net.http.HttpClient and Jackson. Every type choice is checked against data rather than guessed: we pulled 1,160 recent posts from 12 public Java-ecosystem accounts (including @java, @OpenJDK, @springcentral, @intellijidea, @gradle and @kotlin), measured the numeric ranges, id lengths, date formats and optional-object rates, then re-parsed the same raw pages with the Java records below on JDK 21.
If you write in another language, the same API is covered in our Python, C# and Node.js guides linked at the end; this page stays on Java and Spring.
95.9%
Which Twitter (X) API a Java app calls, and what changes in your code
There are two different APIs behind the phrase "Twitter API Java". X's official API lives at api.x.com under /2/... paths, requires a developer account and an app, signs requests with OAuth 2.0 bearer tokens or OAuth 1.0a user context, and bills on X's pay-per-usage rate card (docs.x.com/x-api/getting-started/pricing). TwitterAPI.io is a separate service at api.twitterapi.io with paths such as /twitter/user/info and /twitter/tweet/advanced_search; reads use one API key in an X-API-Key header, and no X account is needed.
The Java libraries you will find all target the first one. Twitter4J (Apache-2.0, about 2,800 GitHub stars) is not archived, but its latest release on Maven Central is 4.1.2 from October 2022 and the latest commit on its main branch is a README update from July 2023. X's own twitter-api-java-sdk is published on Maven Central as 2.0.3 (October 2022) and its README describes it as beta; the repository was last pushed in July 2025. Twittered, a community v2 client, last shipped 2.23 to Maven Central in July 2023. They are useful if you hold X API credentials and want X's object model; they do not speak to TwitterAPI.io, and they bring OAuth setup you do not need for these reads.
Against TwitterAPI.io, a library is optional: the protocol is plain HTTPS with JSON, so a client is about 150 lines of standard Java. That is what the rest of this page builds, in this order: one shared HttpClient, Jackson records, a request method with retries and readable errors, a paging Stream, and a short program that pulls a profile, a timeline and a search.
Set up one shared HttpClient and ObjectMapper
java.net.http.HttpClient has shipped with the JDK since Java 11. Its Javadoc is explicit about lifetime: once built, a client is immutable and can be used to send multiple requests, and it manages its own connection pool, so building a new client for every request throws those connections away. Keep exactly one instance, as a static final field or a singleton bean. In Java 21 it also implements AutoCloseable, which matters only if you build short-lived clients in tests.
Treat Jackson's ObjectMapper the same way: configure it once and reuse it for every response, as this client does. The only dependency is jackson-databind (it pulls in jackson-core and jackson-annotations); version 2.23.0 was the latest release on Maven Central when we compiled this page's code.
Keep the key out of source. Read it from an environment variable or your secrets manager and pass it to the constructor. The header name is X-API-Key; a request without it comes back as HTTP 403 with the explanation in a message field, and a wrong key returns HTTP 401 with message: "API key is invalid". We triggered both on purpose while testing the error handler below.
<!-- Maven: Jackson is the only dependency; HttpClient ships with the JDK (11+) -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.23.0</version>
</dependency>
// Gradle (Kotlin DSL)
implementation("com.fasterxml.jackson.core:jackson-databind:2.23.0")
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.http.HttpClient;
import java.time.Duration;
import java.util.Objects;
public class TwitterApi {
private static final String BASE = "https://api.twitterapi.io";
// One immutable client for the whole application: it owns the connection pool.
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
// ObjectMapper is thread-safe once configured; share it too.
static final ObjectMapper JSON = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
private final String apiKey;
public TwitterApi(String apiKey) {
this.apiKey = Objects.requireNonNull(apiKey); // sent as the X-API-Key header
}
}Model a tweet with Jackson records: ids, counters and dates
Java records are a good fit for API responses: immutable and compact, and Jackson binds them through the canonical constructor (the records below were tested on Jackson 2.23.0). Two annotations do almost all the work. @JsonIgnoreProperties(ignoreUnknown = true) keeps the client alive when the API adds a field, and @JsonProperty maps the snake_case keys (quoted_tweet, retweeted_tweet, and every field on the follower endpoints) onto camelCase components.
Ids: String, not long, and never double. In our sample every tweet id arrived as a JSON string and every one was 19 digits long. All 1,160 were above 2^53 (9,007,199,254,740,992), the largest integer a double holds exactly, and 1,112 of them (95.9%) changed value when round-tripped through one. That is the bug JavaScript clients hit; in Java it appears when someone reads the id with asDouble() or maps it into a generic Map<String, Object> that a downstream tool turns into a number. The largest id was 23.03% of Long.MAX_VALUE, so Long.parseLong(id) works when you need numeric ordering, but storing the string avoids the question.
Counters: long. Across the six engagement counters, the largest value was a viewCount of 12,145,290 on one @jetbrains post, 0.57% of Integer.MAX_VALUE; only 4 of 1,160 posts passed one million views. likeCount peaked at 1,298 and quoteCount at 55. An int would hold every value we saw, but view counts on the largest accounts on X are a different order of magnitude from Java tooling accounts, and a long costs four bytes. Declaring the counters as primitives also means a missing field becomes 0 rather than null, which is why the mapper above disables FAIL_ON_NULL_FOR_PRIMITIVES.
Dates: one pattern, Locale.ROOT. createdAt looks like Thu Oct 16 12:34:56 +0000 2026. DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z yyyy", Locale.ROOT) parsed all 1,160 values in the sample in both Python and Java, with zero failures. Leave out the locale and the same code throws DateTimeParseException on a server whose default locale is not English, because EEE and MMM are matched against localized day and month names.
Optional objects: nullable components. quoted_tweet was absent or null on 95.5% of posts and retweeted_tweet on 75.3%; card was empty on 70.4% and place on all of them. extendedEntities never went missing but was an empty object {} on 61.1% of posts, so test for a non-empty media list rather than for null. The records below type only what the client uses; add components as you need them.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
@JsonIgnoreProperties(ignoreUnknown = true)
public record Author(String id, String userName, String name,
long followers, long following, boolean isBlueVerified) {}
@JsonIgnoreProperties(ignoreUnknown = true)
public record Tweet(String id, String url, String text, String createdAt, String lang,
long likeCount, long retweetCount, long replyCount, long quoteCount,
long viewCount, long bookmarkCount, boolean isReply, Author author,
@JsonProperty("quoted_tweet") Tweet quotedTweet, // usually null
@JsonProperty("retweeted_tweet") Tweet retweetedTweet) { // null unless a repost
static final DateTimeFormatter X_DATE =
DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z yyyy", Locale.ROOT);
public OffsetDateTime created() {
return OffsetDateTime.parse(createdAt, X_DATE);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record UserInfo(String id, String userName, String name, long followers, long following,
long statusesCount, String createdAt, boolean isBlueVerified, boolean canDm) {}
// /twitter/user/followers and /followings return snake_case objects
@JsonIgnoreProperties(ignoreUnknown = true)
public record Follower(String id,
@JsonProperty("screen_name") String screenName,
String name,
@JsonProperty("followers_count") long followersCount,
@JsonProperty("created_at") String createdAt) {}
Send requests with retries and readable errors
Errors reach a Java client in three shapes, and a robust get method handles all of them. HTTP 200 with status: "error": the request was valid but the API could not serve it, and the reason is in msg (for example user not found on /twitter/user/info). HTTP 400: a missing or invalid parameter, with the explanation in detail. HTTP 401 or 403: a bad or missing key, with the text in message.
HTTP 429 and 5xx are worth a retry. Back off exponentially (one, two, four, eight seconds) and give up after a few attempts. Accounts start at 0.2 requests per second before the first payment and move to 20 per second once paid (50 on Scale, 500 on Business), so a fresh trial key hits 429 quickly if you loop without a pause.
One more case deserves its own branch: an account that exists but is suspended. When we checked @ApacheMaven for the study, /twitter/user/info returned HTTP 200, status: "success", and a data object containing only unavailable: true and unavailableReason: "Suspended". Bound naively to the UserInfo record, that becomes a profile full of nulls and zeros; the userInfo method in the next sections checks for it explicitly.
public static class ApiException extends RuntimeException {
private static final long serialVersionUID = 1L;
public final int httpStatus;
public ApiException(int httpStatus, String message) { super(message); this.httpStatus = httpStatus; }
}
/** GET a path with query params; retries 429 and 5xx with exponential backoff. */
JsonNode get(String path, Map<String, String> params) throws IOException, InterruptedException {
String query = params.entrySet().stream()
.map(e -> e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpRequest req = HttpRequest.newBuilder(URI.create(BASE + path + (query.isEmpty() ? "" : "?" + query)))
.header("X-API-Key", apiKey)
.timeout(Duration.ofSeconds(30))
.GET().build();
long backoffMs = 1000;
for (int attempt = 1; ; attempt++) {
HttpResponse<String> res = HTTP.send(req, HttpResponse.BodyHandlers.ofString());
int code = res.statusCode();
if ((code == 429 || code >= 500) && attempt < 5) {
Thread.sleep(backoffMs);
backoffMs *= 2;
continue;
}
JsonNode body = res.body().isBlank() ? JSON.createObjectNode() : JSON.readTree(res.body());
if (code != 200) {
// 400: text in "detail"; 401/403 auth errors: text in "message"; others: "msg"
String why = body.path("detail").isMissingNode()
? body.path("msg").asText(body.path("message").asText(res.body()))
: body.path("detail").toString();
throw new ApiException(code, "HTTP " + code + ": " + why);
}
if ("error".equals(body.path("status").asText())) { // HTTP 200 with status:"error"
throw new ApiException(200, body.path("msg").asText("unknown error"));
}
return body;
}
}Page through timelines and search as a Java Stream
Both tweet endpoints are cursor-paged. The first request sends cursor as an empty string; each response carries has_next_page and next_cursor, and you stop when either says there is nothing more. A timeline page from /twitter/user/last_tweets holds up to 20 tweets, newest first, under data.tweets; /twitter/tweet/advanced_search puts tweets at the top level; /twitter/user/followers returns about 200 snake_case followers per page.
Wrapping that loop in an Iterator turned into a lazy Stream keeps every caller simple and, more importantly, keeps billing under the caller's control: a page is fetched only when the stream needs it, so .limit(50) on a search stops after three pages. The maxPages argument is a hard ceiling on top of that, which is the line that protects you from a loop that never ends on a busy query.
Checked exceptions inside the iterator. Iterator.next() cannot throw IOException, so the code wraps it in UncheckedIOException and restores the interrupt flag on InterruptedException. Callers that care can catch UncheckedIOException around the terminal operation.
Tweets cost per result, so the page size is the unit. A full 20-tweet page costs $0.003 at $0.15 per 1,000 tweets returned; a search that returns nothing is billed the 15-credit minimum, $0.00015.
/** Lazily pages through has_next_page / next_cursor. itemsAt picks the array out of one page. */
<T> Stream<T> paged(String path, Map<String, String> params,
Function<JsonNode, JsonNode> itemsAt, Class<T> type, int maxPages) {
Iterator<List<T>> pages = new Iterator<>() {
String cursor = "";
boolean more = true;
int fetched = 0;
public boolean hasNext() { return more && fetched < maxPages; }
public List<T> next() {
if (!hasNext()) throw new NoSuchElementException();
Map<String, String> p = new LinkedHashMap<>(params);
p.put("cursor", cursor);
try {
JsonNode body = get(path, p);
fetched++;
String nextCursor = body.path("next_cursor").asText("");
more = body.path("has_next_page").asBoolean(false) && !nextCursor.isEmpty();
cursor = nextCursor;
List<T> out = new ArrayList<>();
for (JsonNode n : itemsAt.apply(body)) out.add(JSON.treeToValue(n, type));
return out;
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(pages, Spliterator.ORDERED), false)
.flatMap(List::stream);
}
public Stream<Tweet> lastTweets(String userName, int maxPages) { // tweets live under data.tweets
return paged("/twitter/user/last_tweets", Map.of("userName", userName),
b -> b.path("data").path("tweets"), Tweet.class, maxPages);
}
public Stream<Tweet> search(String query, String queryType, int maxPages) { // top-level tweets
return paged("/twitter/tweet/advanced_search", Map.of("query", query, "queryType", queryType),
b -> b.path("tweets"), Tweet.class, maxPages);
}
public Stream<Follower> followers(String userName, int maxPages) { // top-level followers
return paged("/twitter/user/followers", Map.of("userName", userName),
b -> b.path("followers"), Follower.class, maxPages);
}Use the client: profile, timeline and search in one program
The program below fetches the @java profile, prints the five newest @OpenJDK posts with their dates and view counts, and counts up to three pages of English search results for a phrase. Search queries use X's operator syntax (from:, lang:, since:, OR and so on) in the query parameter, with queryType set to Latest or Top.
What we ran. We compiled the full client (records, get, paged, userInfo and this main) with javac -Xlint:all on Temurin JDK 21 against Jackson 2.23.0, with no warnings. We then ran it in an offline mode over the raw timeline pages collected for the study: the records bound all 1,160 tweets, every createdAt parsed, and Long.parseLong accepted every id. Finally we ran main against the live API without a key to exercise the error path, which printed ApiException(403): HTTP 403: API key required.... We did not paste a production key into this test, so the happy-path output depends on your key; the same calls are what the study made through our collection script.
Java version. Records need Java 16 or later and HttpClient Java 11; anything from Java 17 LTS up compiles the client as written.
public UserInfo userInfo(String userName) throws IOException, InterruptedException {
JsonNode data = get("/twitter/user/info", Map.of("userName", userName)).path("data");
if (data.isNull() || data.isMissingNode())
throw new ApiException(200, "user not found: " + userName);
if (data.path("unavailable").asBoolean(false)) // {"unavailable":true,"unavailableReason":"Suspended"}
throw new ApiException(200, userName + " unavailable: " + data.path("unavailableReason").asText());
return JSON.treeToValue(data, UserInfo.class);
}
public static void main(String[] args) throws Exception {
TwitterApi api = new TwitterApi(System.getenv("TWITTERAPI_IO_KEY"));
try {
UserInfo java = api.userInfo("java");
System.out.printf("@%s: %,d followers, %,d posts%n",
java.userName(), java.followers(), java.statusesCount());
api.lastTweets("OpenJDK", 2).limit(5).forEach(t ->
System.out.printf("%s %,d views %s%n", t.created().toLocalDate(), t.viewCount(), t.url()));
long n = api.search("\"Java 25\" lang:en", "Latest", 3).count(); // up to 3 pages
System.out.println("search results: " + n);
} catch (ApiException e) {
System.out.println("ApiException(" + e.httpStatus + "): " + e.getMessage());
}
}Spring Boot: the same calls with RestClient
In a Spring Boot service, use RestClient rather than hand-rolling HttpClient. Spring's reference documentation states that as of Spring Framework 7.0, RestTemplate is deprecated in favor of RestClient and will be removed in a future version; for reactive or streaming work it points to WebClient. Define one RestClient bean with the base URL and the X-API-Key default header, and inject it where needed.
retrieve() throws a RestClientException subclass on 4xx and 5xx by default; an onStatus handler lets you turn those into your own exceptions with the body text. With a Jackson message converter on the classpath, which a Spring Boot web application normally has, the same records bind with .body(Tweet.class); for a whole page, read a JsonNode and pull tweets, has_next_page and next_cursor from it exactly as the plain-Java client does. For HTTP 429, wrap the call in your retry library of choice (Spring Retry and Resilience4j are common) or keep the backoff loop from the earlier section.
Keep the key in configuration (twitterapi.key resolved from an environment variable or a vault), never in application.properties checked into the repository.
// Spring Boot: RestClient (RestTemplate is deprecated as of Spring Framework 7.0)
@Bean
RestClient twitterApi(@Value("${twitterapi.key}") String key) {
return RestClient.builder()
.baseUrl("https://api.twitterapi.io")
.defaultHeader("X-API-Key", key)
.build();
}
JsonNode page = restClient.get()
.uri(b -> b.path("/twitter/tweet/advanced_search")
.queryParam("query", "from:java")
.queryParam("queryType", "Latest")
.queryParam("cursor", cursor)
.build())
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (req, res) -> {
throw new IllegalStateException("TwitterAPI.io returned " + res.getStatusCode());
})
.body(JsonNode.class); // then read page.path("tweets"), has_next_page, next_cursorHow often Java-ecosystem accounts post, and what reading them costs
The same sample answers an operational question: if your Java service watches these accounts, how much is there to fetch? Not much. The median account posted 0.365 times a day over its last 100 posts; the busiest, @QuarkusIO, posted 1.54 times a day, and @apachekafka 0.07. For every account, at least 99.47% of five-minute polling windows would have found nothing new.
That matters for cost because an empty check is still billed the 15-credit minimum, $0.00015. Polling one account every five minutes for a month is 8,640 checks, about $1.30 in minimums before any tweet is returned; every 60 seconds it is 43,200 checks, $6.48. For a dozen low-volume accounts, one advanced_search query that combines them (from:java OR from:OpenJDK OR from:gradle) every five minutes costs the same as a single account, and the tweets it does return are billed at $0.15 per 1,000.
If you need lower latency than polling gives, TwitterAPI.io also offers filter rules that push matches to a webhook; the Spring RestClient above is the natural receiver's counterpart for any follow-up reads.
TwitterAPI.io bills per result: 15 credits per tweet returned, which is $0.15 per 1,000 tweets, with a 15-credit ($0.00015) minimum on a request that returns nothing; profiles are 18 credits each ($0.18 per 1,000), and follower or following lists are 1 to 3 credits per user returned. X's pay-per-usage rate card lists $0.005 per post read, $0.010 per user read and $0.010 per follower or following read, with post reads capped at 3 million per monthly billing cycle before Enterprise. Per 1,000 tweets that is $5 against $0.15, about 33x. Our 1,160-tweet study cost about $0.18 in total; the same reads at $0.005 each would be about $5.80.
New accounts that pass the automatic bot check get up to $1 of free credits (up to 100,000 credits, no card, one per person or network, expiring after 31 days). Purchased credits never expire, and subscription plans (Starter $29, Builder $99, Pro $199, Scale $499, Business $1,499 a month) are on the pricing page linked below.
Writing from Java. Posting, liking, retweeting, following and media upload are available too, through an authenticated session rather than the API key alone: one /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies, and each write such as /twitter/create_tweet_v2 or /twitter/follow_user_v2 then costs 60 credits ($0.0006), billed per HTTP 200 call. Every write acts as that X account, so X can rate-limit, lock or suspend it; keep a human pace and expect the session to need a fresh login from time to time. The same get-style helper works with a POST body built by Jackson.

How we collected this
Question. Which Java types does a tweet actually need (counter ranges against Integer.MAX_VALUE, id length and the share above 2^53, createdAt parse success with one DateTimeFormatter pattern, optional-object rates), and how often do Java-ecosystem accounts post?
Accounts. 12 public organization accounts: @java, @OpenJDK, @springcentral, @SpringBoot, @intellijidea, @gradle, @kotlin, @jetbrains, @QuarkusIO, @micronautfw, @graalvm and @apachekafka. @ApacheMaven was checked and excluded because /twitter/user/info reported it as suspended; @ApacheNetBeans was excluded for having no posts.
Method and window. /twitter/user/last_tweets with default settings (replies excluded), newest first, up to five pages (about 100 posts) per account, deduplicated by id: 1,160 posts. Each account's window runs from its oldest to newest post in the sample, from 39 days for @QuarkusIO to about 1,400 days for @apachekafka. Collected in 2026 with 74 requests in total (14 profile checks, 59 timeline pages, 1 error probe), costing about $0.18. The same raw pages were then re-parsed with the Java records on this page on JDK 21.
What the sample cannot show. These are developer-tooling accounts with modest reach; counters on large consumer or news accounts are much larger, which is the reason to choose long. Pinned posts and replies are not included, and reposts carry the original post's counters. The cadence table describes each account's recent past, not a forecast.
Privacy. Aggregates only, organization accounts only; reposted and quoted authors are not analyzed. Raw timeline pages are kept in the repository only for accounts whose pages contain no other authors.
"""check_java_types.py - pull a few timeline pages from TwitterAPI.io and report the facts
that decide your Java types: largest counters vs Integer.MAX_VALUE, tweet ids above 2^53,
and whether every createdAt parses with the pattern your DateTimeFormatter will use.
pip install requests
export TWITTERAPI_IO_KEY=... # from the twitterapi.io dashboard
python check_java_types.py java
"""
import os
import sys
from datetime import datetime
import requests
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
INT_MAX = 2**31 - 1
SAFE_DOUBLE = 2**53
COUNTERS = ["viewCount", "likeCount", "retweetCount", "replyCount", "quoteCount", "bookmarkCount"]
X_DATE = "%a %b %d %H:%M:%S %z %Y" # same as Java "EEE MMM dd HH:mm:ss Z yyyy"
def timeline(user_name, max_pages=3):
cursor = ""
for _ in range(max_pages):
r = requests.get(
f"{BASE}/twitter/user/last_tweets",
headers=HEADERS,
params={"userName": user_name, "cursor": cursor},
timeout=40,
)
r.raise_for_status()
body = r.json()
if body.get("status") == "error":
raise SystemExit(body.get("msg"))
for tweet in (body.get("data") or {}).get("tweets", []):
yield tweet
if not body.get("has_next_page") or not body.get("next_cursor"):
break
cursor = body["next_cursor"]
def main():
user = sys.argv[1] if len(sys.argv) > 1 else "java"
tweets = list(timeline(user))
if not tweets:
raise SystemExit("no tweets returned")
print(f"{len(tweets)} tweets from @{user}")
for field in COUNTERS:
top = max(t.get(field) or 0 for t in tweets)
print(f" {field:<14} max {top:>12,} ({100 * top / INT_MAX:.4f}% of Integer.MAX_VALUE)")
ids = [int(t["id"]) for t in tweets]
print(f" id JSON type: {type(tweets[0]['id']).__name__}, digits {min(len(str(i)) for i in ids)}-{max(len(str(i)) for i in ids)}")
print(f" ids above 2^53: {sum(i > SAFE_DOUBLE for i in ids)} / {len(ids)}")
bad = 0
for t in tweets:
try:
datetime.strptime(t["createdAt"], X_DATE)
except ValueError:
bad += 1
print(f" createdAt parse failures: {bad}")
print(f" cost: about ${len(tweets) * 0.00015:.4f} at $0.15 per 1,000 tweets returned")
if __name__ == "__main__":
main()
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
Is there an official Java SDK for the Twitter (X) API?
X publishes twitter-api-java-sdk for its own API v2; Maven Central lists 2.0.3 from October 2022 and the README describes it as beta. Community libraries such as Twitter4J (latest release 4.1.2, October 2022) also target X's official, OAuth-protected API. For TwitterAPI.io you do not need an SDK: HttpClient plus Jackson is enough, as shown on this page.
Is Twitter4J still maintained?
The Twitter4J repository on GitHub is not archived, but its latest release on Maven Central is 4.1.2 from October 2022 and the latest commit on its main branch is a README change from July 2023. It also targets X's own API with OAuth credentials and X's pricing, not TwitterAPI.io.
Should a tweet id be a long or a String in Java?
Store it as a String. The API sends ids as JSON strings; all 1,160 ids in our sample were 19 digits, and 95.9% changed value when converted to a double. Long.parseLong works if you need numeric ordering, since the largest id was about 23% of Long.MAX_VALUE.
How do I parse the createdAt date in Java?
Use DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z yyyy", Locale.ROOT) with OffsetDateTime.parse. It parsed all 1,160 dates in our sample. Always pass Locale.ROOT or Locale.ENGLISH; without it the parse fails on servers with a non-English default locale.
Do I need an X developer account or OAuth to get tweets in Java?
Not for TwitterAPI.io reads. You send one API key in the X-API-Key header; no X account, developer app or OAuth flow is involved. X's own API does require a developer account and OAuth credentials.
How do I use the Twitter API in Spring Boot?
Define one RestClient bean with baseUrl("https://api.twitterapi.io") and defaultHeader("X-API-Key", key), then call .get().uri(...).retrieve().body(...). Spring's documentation marks RestTemplate deprecated as of Spring Framework 7.0 in favor of RestClient.
How much does it cost to fetch tweets from Java?
TwitterAPI.io charges $0.15 per 1,000 tweets returned, with a $0.00015 minimum on a request that returns nothing; profiles are $0.18 per 1,000. X's pay-per-usage rate card lists $0.005 per post read, $5 per 1,000. New accounts that pass the automatic bot check get up to $1 of free credits (up to 100,000 credits, no card, one per person or network, expiring after 31 days).
How do I handle rate limits (HTTP 429) in a Java client?
Retry with exponential backoff (for example 1, 2, 4 and 8 seconds) and cap the attempts. Limits are 0.2 requests per second before the first payment, 20 once paid, 50 on Scale and 500 on Business, so trial keys need a pause between calls.
Continue
- Java 21 API: java.net.http.HttpClient (immutable, reusable, owns its connection pool)
- Spring Framework reference: REST clients (RestClient; RestTemplate deprecated as of 7.0)
- TwitterAPI.io docs: GET /twitter/user/last_tweets
- X API pricing (docs.x.com): pay-per-usage rate card
- Twitter4J on GitHub (Apache-2.0)
- Maven Central: jackson-databind releases
- X (Twitter) API hub: endpoints, pricing and guides
- C# Twitter (X) API client with HttpClient and System.Text.Json
- Twitter (X) API in Python: the complete guide
- The twitter-api-v2 npm package for Node.js
- Twitter API v2 explained: endpoints, auth and limits
- Find the numeric id of any X account
- TwitterAPI.io API reference: every endpoint, parameter and response field
- TwitterAPI.io pricing: pay only for the data returned
- 01Twitter (X) Account Suspended: Why It Happened and How to Get It Back
- 02How to DM on Twitter (X): send a message on web, iPhone and Android
- 03Twitter (X) API in Pydantic AI: A Typed Search Tool for Your Agent
- 04Unofficial Twitter (X) API: Access Without a Developer Account
- 05Twitter (X) Verification in 2026: What the Blue, Gold and Grey Checkmarks Mean and How to Get One
- 06Twitter (X) API Cost — A Straight Answer
- 07Twitter (X) API 1.1 in 2026: What Still Works and Where Each Endpoint Went
- 08Hootsuite Pricing 2026: Plans, Per-Seat Costs and What You Get for Twitter (X)
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.