Claude API Java Client Library: A Working Example
If you're building a Java application and need to talk to Claude, there's no official Anthropic SDK for Java (as of this writing, Anthropic maintains SDKs for Python and TypeScript). That means most Java developers end up writing a thin HTTP client around the REST API themselves, or using a community-maintained wrapper. This article shows you exactly how to do that: a working Java client built on java.net.http.HttpClient, with request/response handling for /v1/messages, plus notes on streaming and error handling.
The short answer to "how do I call the Claude API from Java": you send a POST request with a JSON body to the messages endpoint, set your API key in a header, and parse the JSON response. No special library is required — Java's built-in HttpClient (available since Java 11) is enough for most use cases.
A minimal Java client for the Claude API
Here's a self-contained class that sends a message and returns the text response. It uses only the JDK's HttpClient and a small JSON library (Jackson) for parsing.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ClaudeClient {
private final String apiKey;
private final String baseUrl;
private final HttpClient http;
private final ObjectMapper mapper = new ObjectMapper();
public ClaudeClient(String apiKey, String baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
}
public String sendMessage(String model, String userMessage) throws Exception {
String body = """
{
"model": "%s",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "%s"}]
}
""".formatted(model, userMessage.replace("\"", "\\\""));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/v1/messages"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey)
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
throw new RuntimeException("API error " + response.statusCode() + ": " + response.body());
}
JsonNode json = mapper.readTree(response.body());
return json.get("content").get(0).get("text").asText();
}
}
Usage:
ClaudeClient client = new ClaudeClient(System.getenv("CLAUDE_API_KEY"), "https://api.example.com");
String reply = client.sendMessage("claude-3-5-sonnet-20241022", "Summarize this ticket in one sentence.");
System.out.println(reply);
This pattern — build a JSON body, POST it with an Authorization header, parse the response — covers 90% of what you need from Java, whether you're calling Anthropic's API directly or going through a proxy.
Why you might not call the raw API directly
Three practical problems come up quickly when you build a Java integration this way:
- Streaming requires manual SSE parsing. Server-sent events don't map cleanly to
HttpClient's blocking model — you needHttpResponse.BodyHandlers.ofLines()or a reactive stream subscriber, and you have to parsedata:chunks yourself. - Key management across environments. Hardcoding a provider key into a backend service, then rotating it across staging, production and a dozen microservices, is error-prone.
- No per-service usage visibility. If five Java services share one Claude account, you can't tell which service is burning tokens without building your own logging layer.
This is exactly the gap SubToAPI fills. It sits between your Java code and Claude, turning your existing Claude access into a standard HTTPS API with its own scoped keys (sub_live_...), one per service or team member. The request shape is nearly identical to what's shown above — you just point baseUrl at https://api.subtoapi.app/v1 and use a SubToAPI key:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.subtoapi.app/v1/messages"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + System.getenv("SUBTOAPI_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
Because the API contract matches the /v1/messages format, the ClaudeClient class above works unmodified — you only change the key and base URL. See the quickstart and messages reference for the full request/response schema.
Handling streaming responses in Java
For long completions, streaming avoids blocking your thread until the full response is ready. With HttpClient, you can read the response as a line stream and parse each SSE event:
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.subtoapi.app/v1/messages"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + System.getenv("SUBTOAPI_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(streamingBody))
.build();
HttpResponse<Stream<String>> response = http.send(request, HttpResponse.BodyHandlers.ofLines());
response.body().forEach(line -> {
if (line.startsWith("data:")) {
String payload = line.substring(5).trim();
if (!payload.equals("[DONE]")) {
// parse payload as JSON, extract delta text
System.out.print(payload);
}
}
});
Details on event types and delta formats are covered in the streaming docs.
Calling tools from Java
If your Java app needs Claude to call functions — looking up inventory, querying a database, hitting an internal API — you define tool schemas in the request body the same way as in any other language:
String toolsJson = """
[{
"name": "get_order_status",
"description": "Look up the status of an order by ID",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"]
}
}]
""";
Include this tools array in the request body, then inspect the response for a tool_use content block, execute the matching Java method, and send the result back in a follow-up message with role tool_result. Full examples and schema details are in the tools docs.
Choosing between raw API calls and a managed layer
If you're prototyping or building a single internal tool, the raw HttpClient approach above is enough. If you're shipping a product with multiple Java services, team members, or client applications that all need Claude access, a managed API key layer saves you from building key rotation, usage tracking and rate limiting yourself. Pricing starts at €9/month for solo developers, with team and scale tiers for larger setups — and a free trial at signup if you want to test it against your existing Java code first.
Questions
Is there an official Claude API client library for Java? No. Anthropic currently ships official SDKs for Python and TypeScript/JavaScript. Java developers typically use the built-in HttpClient or a third-party community wrapper to call the REST API directly.
Which Java HTTP library should I use for the Claude API? java.net.http.HttpClient, included since Java 11, is sufficient for most use cases — it supports synchronous and asynchronous requests, and with BodyHandlers.ofLines() it can handle streamed SSE responses without extra dependencies.
Can I use the same Java code with SubToAPI instead of calling Claude directly? Yes. SubToAPI exposes the same /v1/messages request and response shape, so you only need to change the base URL and API key — the rest of your Java client code, including streaming and tool-use logic, stays the same.