Claude API Java SDK Tutorial: A Working Example
If you're building a backend in Java or Kotlin and want to call Claude, you have two practical paths: Anthropic's official Java SDK, or a plain HTTP client hitting the REST API directly. This tutorial covers both, with a working example you can copy into a Maven or Gradle project right now.
The short answer: install com.anthropic:anthropic-java from Maven Central, set your ANTHROPIC_API_KEY environment variable, instantiate AnthropicClient, and call client.messages().create(...). Below is the full setup, a streaming example, and what to do when you need multiple team members or applications sharing access to the same Claude account.
Setting Up the Project
Add the dependency to your pom.xml:
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java</artifactId>
<version>0.8.0</version>
</dependency>
Or with Gradle:
implementation 'com.anthropic:anthropic-java:0.8.0'
Check Maven Central for the latest version number — the SDK ships frequent releases as the API evolves.
Set your credentials as an environment variable rather than hardcoding them:
export ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxx
Your First Message Call
Here's the minimal example to send a message and read the response:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
public class ClaudeExample {
public static void main(String[] args) {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(1024L)
.addUserMessage("Explain checked exceptions in Java in two sentences.")
.build();
Message message = client.messages().create(params);
System.out.println(message.content());
}
}
The client picks up ANTHROPIC_API_KEY from the environment automatically via fromEnv(). MessageCreateParams is a builder — chain .addUserMessage(), .system(), and .maxTokens() as needed.
Multi-Turn Conversations
Claude is stateless between calls, so you resend the conversation history each time:
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(1024L)
.addUserMessage("What's a good name for a logging library?")
.addAssistantMessage("How about 'Logbook'? Simple and memorable.")
.addUserMessage("I like it. Suggest a tagline.")
.build();
Message message = client.messages().create(params);
Each call must include the full history up to that point, which also means your token usage grows with conversation length — worth tracking if you're running this in production.
Streaming Responses in Java
For chat UIs or long completions, streaming avoids making users wait for the full response:
import com.anthropic.models.messages.RawMessageStreamEvent;
import com.anthropic.core.http.StreamResponse;
try (StreamResponse<RawMessageStreamEvent> stream =
client.messages().createStreaming(params)) {
stream.stream().forEach(event -> {
event.contentBlockDelta().ifPresent(delta ->
System.out.print(delta.delta().text().orElse("")));
});
}
Each event arrives as a typed object you can pattern-match on, so you don't need to parse raw server-sent events yourself — the SDK does that for you.
Using Tools (Function Calling)
Claude can call tools you define, which is useful for structured data extraction or triggering actions in your app:
import com.anthropic.models.messages.Tool;
Tool getWeather = Tool.builder()
.name("get_weather")
.description("Get current weather for a city")
.inputSchema(Tool.InputSchema.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.build())
.build();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_3_5_SONNET_LATEST)
.maxTokens(1024L)
.addTool(getWeather)
.addUserMessage("What's the weather in Lisbon?")
.build();
When Claude decides to use the tool, the response contains a tool_use content block with structured input you parse, execute, and send back as a tool_result in the next message.
Handling Errors and Retries
The SDK throws typed exceptions (RateLimitException, AuthenticationException, InternalServerException) so you can branch logic without string-matching error messages:
try {
Message message = client.messages().create(params);
} catch (RateLimitException e) {
// back off and retry
} catch (AuthenticationException e) {
// check your API key
}
Build in exponential backoff for rate limits — Claude's API enforces per-minute token and request limits that vary by plan.
When One API Key Isn't Enough
The official SDK is built around a single Anthropic account and a single API key. That's fine for a solo project, but it gets awkward once multiple services, environments, or team members need their own scoped access — you end up sharing one secret key across everything or managing a pile of separate Anthropic accounts.
This is where SubToAPI fits in. It sits in front of your existing Claude access and issues separate sub_live_... keys per application or team member, each with its own usage metadata, while routing requests through the same underlying Claude account. You can call it from Java with any standard HTTP client — no special SDK required, since it's a plain HTTPS endpoint:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-latest",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello"}]
}'
From Java, that's just an OkHttpClient POST request instead of the Anthropic SDK call — the request and response shapes match, so you can keep most of your existing parsing logic. See the quickstart and messages docs for the full request format, streaming for SSE details, and tools for function-calling support. Plans start at €9 for solo use, with team seats at €19 and €49 — check pricing or start a free trial.
Wrapping Up
The official Java SDK covers the core use cases well: single calls, streaming, multi-turn conversations, and tool use, with typed exceptions and builder patterns that feel idiomatic in Java. If your use case stays within one application and one API key, it's the right starting point. Once you need per-team or per-app key management and usage visibility across multiple callers, a layer like SubToAPI handles that without requiring you to rewrite your HTTP logic.
Is there an official Java SDK for Claude API?
Yes. Anthropic publishes anthropic-java on Maven Central, with support for messages, streaming, tool use, and typed exception handling. It's actively maintained alongside the Python and TypeScript SDKs.
Can I call Claude from Java without the SDK?
Yes. Claude's API is a standard HTTPS/JSON endpoint, so any HTTP client (OkHttp, Java's built-in HttpClient, Apache HttpClient) works fine — useful if you want fewer dependencies or need to route requests through a gateway.
How do I handle streaming responses in Java?
Use client.messages().createStreaming(params) from the official SDK, which returns a StreamResponse you iterate over as typed events. If you're calling the API directly over HTTP, you'll need to parse server-sent events yourself.