The Anthropic Java SDK provides convenient access to the Anthropic REST API from applications written in Java. It uses the builder pattern for creating requests and supports both synchronous and asynchronous operations.
For API feature documentation with code examples, see the API reference. This page covers Java-specific SDK features and configuration.
This library requires Java 8 or later.
The SDK supports Java 8 and later. Code examples in this documentation are written as JDK 25 compact source files, using a bare void main() entry point and IO.println() for output. The API calls themselves are identical on every supported JDK; to compile an example on an earlier version, replace IO.println(...) with System.out.println(...) and place the body inside public static void main(String[] args) within a class.
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;
// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties
// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_7)
.build();
Message message = client.messages().create(params);Configure the client using system properties or environment variables:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties
// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables
AnthropicClient client = AnthropicOkHttpClient.fromEnv();Or configure manually:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.apiKey("my-anthropic-api-key")
.build();Or use a combination of both approaches:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
// Configures using system properties or environment variables
.fromEnv()
.apiKey("my-anthropic-api-key")
.build();For authentication options including Workload Identity Federation, see Authentication.
| Setter | System property | Environment variable | Required | Default value |
|---|---|---|---|---|
apiKey | anthropic.apiKey | ANTHROPIC_API_KEY | false | - |
authToken | anthropic.authToken | ANTHROPIC_AUTH_TOKEN | false | - |
baseUrl | anthropic.baseUrl | ANTHROPIC_BASE_URL | true | "https://api.anthropic.com" |
System properties take precedence over environment variables.
Don't create more than one client in the same application. Each client has a connection pool and thread pools, which are more efficient to share between requests.
To temporarily use a modified client configuration while reusing the same connection and thread pools, call withOptions() on any client or service:
import com.anthropic.client.AnthropicClient;
AnthropicClient clientWithOptions = client.withOptions(optionsBuilder -> {
optionsBuilder.baseUrl("https://example.com");
optionsBuilder.maxRetries(42);
});The withOptions() method does not affect the original client or service.
The default client is synchronous. To switch to asynchronous execution, call the async() method:
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;
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_7)
.build();
CompletableFuture<Message> message = client.async().messages().create(params);Or create an asynchronous client from the beginning:
import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_7)
.build();
CompletableFuture<Message> message = client.messages().create(params);The asynchronous client supports the same options as the synchronous one, except most methods return CompletableFutures.
The SDK defines methods that return response "chunk" streams, where each chunk can be individually processed as soon as it arrives instead of waiting on the full response.
These streaming methods return StreamResponse for synchronous clients:
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.messages.RawMessageStreamEvent;
try (StreamResponse<RawMessageStreamEvent> streamResponse = client.messages().createStreaming(params)) {
streamResponse.stream().forEach(chunk -> {
IO.println(chunk);
});
IO.println("No more chunks!");
}For asynchronous clients, the method returns AsyncStreamResponse:
import com.anthropic.core.http.AsyncStreamResponse;
import com.anthropic.models.messages.RawMessageStreamEvent;
client.async().messages().createStreaming(params).subscribe(chunk -> {
IO.println(chunk);
});
// If you need to handle errors or completion of the stream
client.async().messages().createStreaming(params).subscribe(new AsyncStreamResponse.Handler<>() {
@Override
public void onNext(RawMessageStreamEvent chunk) {
IO.println(chunk);
}
@Override
public void onComplete(Optional<Throwable> error) {
if (error.isPresent()) {
IO.println("Something went wrong!");
throw new RuntimeException(error.get());
} else {
IO.println("No more chunks!");
}
}
});
// Or use futures
client.async().messages().createStreaming(params)
.subscribe(chunk -> {
IO.println(chunk);
})
.onCompleteFuture()
.whenComplete((unused, error) -> {
if (error != null) {
IO.println("Something went wrong!");
throw new RuntimeException(error);
} else {
IO.println("No more chunks!");
}
});Async streaming uses a dedicated per-client cached thread pool Executor to stream without blocking the current thread. To use a different Executor:
Executor executor = Executors.newFixedThreadPool(4);
client.async().messages().createStreaming(params).subscribe(
chunk -> IO.println(chunk), executor
);Or configure the client globally using the streamHandlerExecutor method:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.streamHandlerExecutor(Executors.newFixedThreadPool(4))
.build();A MessageAccumulator can record the stream of events in the response as they are processed and accumulate a Message object similar to what would have been returned by the non-streaming API.
For a synchronous response, add a Stream.peek() call to the stream pipeline to accumulate each event:
import com.anthropic.core.http.StreamResponse;
import com.anthropic.helpers.MessageAccumulator;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.RawMessageStreamEvent;
MessageAccumulator messageAccumulator = MessageAccumulator.create();
try (StreamResponse<RawMessageStreamEvent> streamResponse =
client.messages().createStreaming(createParams)) {
streamResponse.stream()
.peek(messageAccumulator::accumulate)
.flatMap(event -> event.contentBlockDelta().stream())
.flatMap(deltaEvent -> deltaEvent.delta().text().stream())
.forEach(textDelta -> IO.print(textDelta.text()));
}
Message message = messageAccumulator.message();For an asynchronous response, add the MessageAccumulator to the subscribe() call:
import com.anthropic.helpers.MessageAccumulator;
import com.anthropic.models.messages.Message;
MessageAccumulator messageAccumulator = MessageAccumulator.create();
client.async().messages()
.createStreaming(createParams)
.subscribe(event -> messageAccumulator.accumulate(event).contentBlockDelta().stream()
.flatMap(deltaEvent -> deltaEvent.delta().text().stream())
.forEach(textDelta -> IO.print(textDelta.text())))
.onCompleteFuture()
.join();
Message message = messageAccumulator.message();A BetaMessageAccumulator is also available for the accumulation of a BetaMessage object. It is used in the same manner as the MessageAccumulator.
For complete structured outputs documentation including Java examples, see Structured outputs.
Tool use with Claude lets you integrate external tools and functions directly into the AI model's responses. Instead of producing plain text, the model can output instructions (with parameters) for calling a tool or function when appropriate. You define JSON schemas for tools, and the model uses the schemas to determine when and how to use these tools.
The tool use feature supports a "strict" mode that guarantees that the JSON output from the AI model will conform to the JSON schema you provide in the input parameters.
The SDK can derive a tool and its parameters automatically from the structure of an arbitrary Java class: the class's name (converted to snake case) provides the tool name, and the class's fields define the tool's parameters.
Declare your tool classes as top-level classes or static nested classes. This requirement comes from the Jackson Databind library (com.fasterxml.jackson.databind), which the SDK uses to deserialize tool inputs into your class instances and cannot instantiate non-static inner classes.
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
enum Unit {
CELSIUS,
FAHRENHEIT;
public String toString() {
switch (this) {
case CELSIUS:
return "C";
case FAHRENHEIT:
default:
return "F";
}
}
public double fromKelvin(double temperatureK) {
switch (this) {
case CELSIUS:
return temperatureK - 273.15;
case FAHRENHEIT:
default:
return (temperatureK - 273.15) * 1.8 + 32.0;
}
}
}
@JsonClassDescription("Get the weather in a given location")
static class GetWeather {
@JsonPropertyDescription("The city and state, e.g. San Francisco, CA")
public String location;
@JsonPropertyDescription("The unit of temperature")
public Unit unit;
public Weather execute() {
double temperatureK;
switch (location) {
case "San Francisco, CA":
temperatureK = 300.0;
break;
case "New York, NY":
temperatureK = 310.0;
break;
case "Dallas, TX":
temperatureK = 305.0;
break;
default:
temperatureK = 295;
break;
}
return new Weather(String.format("%.0f%s", unit.fromKelvin(temperatureK), unit));
}
}
static class Weather {
public String temperature;
public Weather(String temperature) {
this.temperature = temperature;
}
}When your tool classes are defined, add them to the message parameters using MessageCreateParams.Builder.addTool(Class<T>) and then call them if requested to do so in the AI model's response. BetaToolUseBlock.input(Class<T>) can be used to parse a tool's parameters in JSON form to an instance of your tool-defining class.
After calling the tool, use BetaToolResultBlockParam.Builder.contentAsJson(Object) to pass the tool's result back to the AI model:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.beta.messages.*;
import com.anthropic.models.messages.Model;
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_7)
.maxTokens(2048)
.addTool(GetWeather.class)
.addUserMessage("What's the temperature in New York?");
client.beta().messages().create(createParamsBuilder.build()).content().stream()
.flatMap(contentBlock -> contentBlock.toolUse().stream())
.forEach(toolUseBlock -> createParamsBuilder
// Add a message indicating that the tool use was requested.
.addAssistantMessageOfBetaContentBlockParams(
List.of(BetaContentBlockParam.ofToolUse(BetaToolUseBlockParam.builder()
.name(toolUseBlock.name())
.id(toolUseBlock.id())
.input(toolUseBlock._input())
.build())))
// Add a message with the result of the requested tool use.
.addUserMessageOfBetaContentBlockParams(
List.of(BetaContentBlockParam.ofToolResult(BetaToolResultBlockParam.builder()
.toolUseId(toolUseBlock.id())
.contentAsJson(callTool(toolUseBlock))
.build()))));
client.beta().messages().create(createParamsBuilder.build()).content().stream()
.flatMap(contentBlock -> contentBlock.text().stream())
.forEach(textBlock -> IO.println(textBlock.text()));
private static Object callTool(BetaToolUseBlock toolUseBlock) {
if (!"get_weather".equals(toolUseBlock.name())) {
throw new IllegalArgumentException("Unknown tool: " + toolUseBlock.name());
}
GetWeather tool = toolUseBlock.input(GetWeather.class);
return tool != null ? tool.execute() : new Weather("unknown");
}Tool names are derived from the camel case tool class names (e.g., GetWeather) and converted to snake case (e.g., get_weather). Word boundaries begin where the current character is not the first character, is upper-case, and either the preceding character is lower-case, or the following character is lower-case. For example, MyJSONParser becomes my_json_parser and ParseJSON becomes parse_json. This conversion can be overridden using the @JsonTypeName annotation.
You can perform local validation to check that the JSON schema derived from your tool class respects Anthropic's restrictions. Local validation is enabled by default, but it can be disabled:
MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_7)
.maxTokens(2048)
.addTool(GetWeather.class, JsonSchemaLocalValidation.NO)
.addUserMessage("What's the temperature in New York?");You can use annotations to add further information about tools to the JSON schemas:
@JsonClassDescription - Add a description to a tool class detailing when and how to use that tool.@JsonTypeName - Set the tool name to something other than the simple name of the class converted to snake case.@JsonPropertyDescription - Add a detailed description to a tool parameter.@JsonIgnore - Exclude a public field or getter method from the generated JSON schema for a tool's parameters.@JsonProperty - Include a non-public field or getter method in the generated JSON schema for a tool's parameters.The SDK provides support for Batch processing under the client.messages().batches() namespace. See Pagination for how to list and paginate through batches.
The SDK defines methods that accept files through the MultipartField class:
import com.anthropic.core.MultipartField;
import com.anthropic.models.beta.files.FileMetadata;
import com.anthropic.models.beta.files.FileUploadParams;
FileUploadParams params = FileUploadParams.builder()
.file(
MultipartField.<InputStream>builder()
.value(Files.newInputStream(Paths.get("/path/to/file.pdf")))
.contentType("application/pdf")
.build()
)
.build();
FileMetadata fileMetadata = client.beta().files().upload(params);Or from an InputStream:
import com.anthropic.core.MultipartField;
import com.anthropic.models.beta.files.FileMetadata;
import com.anthropic.models.beta.files.FileUploadParams;
FileUploadParams params = FileUploadParams.builder()
.file(
MultipartField.<InputStream>builder()
.value(new URL("https://example.com/path/to/file").openStream())
.filename("document.pdf")
.contentType("application/pdf")
.build()
)
.build();
FileMetadata fileMetadata = client.beta().files().upload(params);Or from in-memory bytes:
import com.anthropic.core.MultipartField;
import com.anthropic.models.beta.files.FileMetadata;
import com.anthropic.models.beta.files.FileUploadParams;
FileUploadParams params = FileUploadParams.builder()
.file(
MultipartField.<InputStream>builder()
.value(new ByteArrayInputStream("content".getBytes()))
.filename("document.txt")
.contentType("text/plain")
.build()
)
.build();
FileMetadata fileMetadata = client.beta().files().upload(params);The SDK defines methods that return binary responses for API responses that aren't necessarily parsed as JSON:
import com.anthropic.core.http.HttpResponse;
HttpResponse response = client.beta().files().download("file_id");To save the response content to a file:
import com.anthropic.core.http.HttpResponse;
try (HttpResponse response = client.beta().files().download(params)) {
Files.copy(
response.body(),
Paths.get(path),
StandardCopyOption.REPLACE_EXISTING
);
} catch (Exception e) {
IO.println("Something went wrong!");
throw new RuntimeException(e);
}Or transfer the response content to any OutputStream:
import com.anthropic.core.http.HttpResponse;
try (HttpResponse response = client.beta().files().download(params)) {
response.body().transferTo(Files.newOutputStream(Paths.get(path)));
} catch (Exception e) {
IO.println("Something went wrong!");
throw new RuntimeException(e);
}The SDK throws custom unchecked exception types:
AnthropicServiceException - Base class for HTTP errors.AnthropicIoException - I/O networking errors.AnthropicRetryableException - Generic error indicating a failure that could be retried.AnthropicInvalidDataException - Failure to interpret successfully parsed data (e.g., when accessing a property that's supposed to be required, but the API unexpectedly omitted it).AnthropicException - Base class for all exceptions.| Status | Exception |
|---|---|
| 400 | BadRequestException |
| 401 | UnauthorizedException |
| 403 | PermissionDeniedException |
| 404 | NotFoundException |
| 422 | UnprocessableEntityException |
| 429 | RateLimitException |
| 5xx | InternalServerException |
| others | UnexpectedStatusCodeException |
SseException is thrown for errors encountered during SSE streaming after a successful initial HTTP response.
import com.anthropic.errors.*;
try {
Message message = client.messages().create(params);
} catch (RateLimitException e) {
IO.println("Rate limited, retry after: " + e.headers());
} catch (UnauthorizedException e) {
IO.println("Invalid API key");
} catch (AnthropicServiceException e) {
IO.println("API error: " + e.statusCode());
} catch (AnthropicIoException e) {
IO.println("Network error: " + e.getMessage());
}When using raw responses, you can access the request-id response header using the requestId() method:
import com.anthropic.core.http.HttpResponseFor;
import com.anthropic.models.messages.Message;
HttpResponseFor<Message> message = client.messages().withRawResponse().create(params);
Optional<String> requestId = message.requestId();This can be used to quickly log failing requests and report them back to Anthropic. For more information on debugging requests, see Request ID.
The SDK automatically retries 2 times by default, with a short exponential backoff between requests.
Only the following error types are retried:
The API may also explicitly instruct the SDK to retry or not retry a request.
To set a custom number of retries, configure the client using the maxRetries method:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder().fromEnv().maxRetries(4).build();Requests time out after 10 minutes by default.
However, for methods that accept maxTokens, if you specify a large maxTokens value and are streaming, then the default timeout will be calculated dynamically using this formula:
Duration.ofSeconds(
Math.min(
60 * 60, // 1 hour max
Math.max(
10 * 60, // 10 minute minimum
60 * 60 * maxTokens / 128_000
)
)
)This results in a timeout of up to 60 minutes, scaled by the maxTokens parameter, unless overridden.
For non-streaming requests, the dynamic timeout scales from a 30 second minimum up to a 10 minute maximum based on maxTokens.
To set a custom timeout per-request:
import com.anthropic.models.messages.Message;
Message message = client
.messages()
.create(params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build());Or configure the default for all method calls at the client level:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.timeout(Duration.ofSeconds(30))
.build();Consider using streaming for longer running requests.
Avoid setting a large maxTokens value without using streaming. Some networks may drop idle connections after a certain period of time, which can cause the request to fail or timeout without receiving a response from Anthropic. The SDK periodically pings the API to keep the connection alive and reduce the impact of these networks.
The SDK throws an error if a non-streaming request is expected to take longer than 10 minutes. Using a streaming method or overriding the timeout at the client or request level disables the error.
The SDK provides convenient ways to access paginated results either one page at a time or item-by-item across all pages.
To iterate through all results across all pages, use the autoPager() method, which automatically fetches more pages as needed.
import com.anthropic.models.messages.batches.BatchListPage;
import com.anthropic.models.messages.batches.MessageBatch;
BatchListPage page = client.messages().batches().list();
// Process as an Iterable
for (MessageBatch batch : page.autoPager()) {
IO.println(batch);
}
// Process as a Stream
page.autoPager()
.stream()
.limit(50)
.forEach(batch -> IO.println(batch));When using the asynchronous client, the method returns an AsyncStreamResponse:
import com.anthropic.core.http.AsyncStreamResponse;
import com.anthropic.models.messages.batches.BatchListPageAsync;
import com.anthropic.models.messages.batches.MessageBatch;
CompletableFuture<BatchListPageAsync> pageFuture = client.async().messages().batches().list();
pageFuture.thenAccept(page -> page.autoPager().subscribe(batch -> {
IO.println(batch);
}));
// If you need to handle errors or completion of the stream
pageFuture.thenAccept(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() {
@Override
public void onNext(MessageBatch batch) {
IO.println(batch);
}
@Override
public void onComplete(Optional<Throwable> error) {
if (error.isPresent()) {
IO.println("Something went wrong!");
throw new RuntimeException(error.get());
} else {
IO.println("No more!");
}
}
}));
// Or use futures
pageFuture.thenAccept(page -> page.autoPager()
.subscribe(batch -> {
IO.println(batch);
})
.onCompleteFuture()
.whenComplete((unused, error) -> {
if (error != null) {
IO.println("Something went wrong!");
throw new RuntimeException(error);
} else {
IO.println("No more!");
}
}));To access individual page items and manually request the next page:
import com.anthropic.models.messages.batches.BatchListPage;
import com.anthropic.models.messages.batches.MessageBatch;
BatchListPage page = client.messages().batches().list();
while (true) {
for (MessageBatch batch : page.items()) {
IO.println(batch);
}
if (!page.hasNextPage()) {
break;
}
page = page.nextPage();
}Each class in the SDK has an associated builder for constructing it. Each class is immutable once constructed. If the class has an associated builder, then it has a toBuilder() method, which can be used to convert it back to a builder for making a modified copy.
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_7)
.build();
// Create a modified copy using toBuilder()
MessageCreateParams modified = params.toBuilder().maxTokens(2048L).build();Because each class is immutable, builder modification will never affect already built class instances.
To send a request to the Claude API, build an instance of some Params class and pass it to the corresponding client method. When the response is received, it is deserialized into an instance of a Java class.
For example, client.messages().create(...) should be called with an instance of MessageCreateParams, and it will return an instance of Message.
To set undocumented parameters, call the putAdditionalHeader, putAdditionalQueryParam, or putAdditionalBodyProperty methods on any Params class:
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.MessageCreateParams;
MessageCreateParams params = MessageCreateParams.builder()
.putAdditionalHeader("Secret-Header", "42")
.putAdditionalQueryParam("secret_query_param", "42")
.putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
.build();These can be accessed on the built object later using the _additionalHeaders(), _additionalQueryParams(), and _additionalBodyProperties() methods.
The values passed to these methods overwrite values passed to earlier methods. For security reasons, ensure these methods are only used with trusted input data.
To set undocumented parameters on nested headers, query params, or body classes:
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Metadata;
MessageCreateParams params = MessageCreateParams.builder()
.metadata(
Metadata.builder().putAdditionalProperty("secretProperty", JsonValue.from("42")).build()
)
.build();These properties can be accessed on the nested built object later using the _additionalProperties() method.
To set a documented parameter or property to an undocumented or not yet supported value, pass a JsonValue object to its setter:
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(JsonValue.from(3.14))
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_7)
.build();The most straightforward way to create a JsonValue is using its from(...) method:
import com.anthropic.core.JsonValue;
// Create primitive JSON values
JsonValue nullValue = JsonValue.from(null);
JsonValue booleanValue = JsonValue.from(true);
JsonValue numberValue = JsonValue.from(42);
JsonValue stringValue = JsonValue.from("Hello World!");
// Create a JSON array value equivalent to `["Hello", "World"]`
JsonValue arrayValue = JsonValue.from(List.of("Hello", "World"));
// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`
JsonValue objectValue = JsonValue.from(Map.of("a", 1, "b", 2));
// Create an arbitrarily nested JSON equivalent to:
// { "a": [1, 2], "b": [3, 4] }
JsonValue complexValue = JsonValue.from(Map.of("a", List.of(1, 2), "b", List.of(3, 4)));Normally a Builder class's build method will throw IllegalStateException if any required parameter or property is unset. To forcibly omit a required parameter or property, pass JsonMissing:
import com.anthropic.core.JsonMissing;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.addUserMessage("Hello, world")
.model(Model.CLAUDE_OPUS_4_7)
.maxTokens(JsonMissing.of())
.build();To access undocumented response properties, call the _additionalProperties() method:
import com.anthropic.core.JsonValue;
Map<String, JsonValue> additionalProperties = client
.messages()
.create(params)
._additionalProperties();
JsonValue secretPropertyValue = additionalProperties.get("secretProperty");
String result = secretPropertyValue.accept(new JsonValue.Visitor<>() {
@Override
public String visitNull() {
return "It's null!";
}
@Override
public String visitBoolean(boolean value) {
return "It's a boolean!";
}
@Override
public String visitNumber(Number value) {
return "It's a number!";
}
// Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`
// The default implementation of each unimplemented method delegates to `visitDefault`,
// which throws by default, but can also be overridden
});To access a property's raw JSON value, call its _ prefixed method:
import com.anthropic.core.JsonField;
import com.anthropic.models.messages.StopReason;
JsonField<StopReason> stopReason = client.messages().create(params)._stopReason();
if (stopReason.isMissing()) {
// The property is absent from the JSON response
} else if (stopReason.isNull()) {
// The property was set to literal null
} else {
// Check if value was provided as a string
// Other methods include `asNumber()`, `asBoolean()`, etc.
Optional<String> jsonString = stopReason.asString();
// Try to deserialize into a custom type
MyClass myObject = stopReason.asUnknown().orElseThrow().convert(MyClass.class);
}By default, the SDK does not throw an exception when the API returns a response that doesn't match the expected type. It throws AnthropicInvalidDataException only if you directly access the property.
To check that the response is completely well-typed upfront, call validate():
import com.anthropic.models.messages.Message;
Message message = client.messages().create(params).validate();Or configure per-request:
import com.anthropic.models.messages.Message;
Message message = client
.messages()
.create(params, RequestOptions.builder().responseValidation(true).build());Or configure the default for all method calls at the client level:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.responseValidation(true)
.build();import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import java.net.Proxy;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https://example.com", 8080)))
.build();Most applications should not call these methods, and instead use the system defaults. The defaults include special optimizations that can be lost if the implementations are modified.
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.sslSocketFactory(yourSSLSocketFactory)
.trustManager(yourTrustManager)
.hostnameVerifier(yourHostnameVerifier)
.build();The SDK consists of three artifacts:
anthropic-java-core - Contains core SDK logic, does not depend on OkHttp. Exposes AnthropicClient, AnthropicClientAsync, and their implementation classes, all of which can work with any HTTP client.anthropic-java-client-okhttp - Depends on OkHttp. Exposes AnthropicOkHttpClient and AnthropicOkHttpClientAsync.anthropic-java - Depends on and exposes the APIs of both anthropic-java-core and anthropic-java-client-okhttp. Does not have its own logic.This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies.
Try the available network options before replacing the default client.
To use a customized OkHttpClient:
anthropic-java dependency with anthropic-java-core.anthropic-java-client-okhttp's OkHttpClient class into your code and customize it.AnthropicClientImpl or AnthropicClientAsyncImpl using your customized client.To use a completely custom HTTP client:
anthropic-java dependency with anthropic-java-core.HttpClient interface.AnthropicClientImpl or AnthropicClientAsyncImpl using your new client class.For detailed platform setup guides with code examples, see:
The Java SDK supports the following platforms through separate dependencies that provide platform-specific Backend implementations:
com.anthropic:anthropic-java-bedrock: Use BedrockMantleBackend.fromEnv() or BedrockMantleBackend.builder() for the Messages-API Bedrock endpoint, or BedrockBackend.fromEnv() / BedrockBackend.builder() (bedrock-runtime path).com.anthropic:anthropic-java-vertex: Use VertexBackend.fromEnv() or VertexBackend.builder().com.anthropic:anthropic-java-foundry: Use FoundryBackend.fromEnv() or FoundryBackend.builder().com.anthropic:anthropic-java-aws: Use AwsBackend.fromEnv() (reads ANTHROPIC_AWS_WORKSPACE_ID and the AWS default region/credential chain) or AwsBackend.builder(). Available in beta.Use BedrockMantleBackend for new projects; BedrockBackend remains for existing applications using the Bedrock InvokeModel API.
Each Backend implementation is passed to the client with .backend() on AnthropicOkHttpClient.builder(). Each cloud backend pulls in its respective cloud-platform SDK classes as transitive dependencies.
To access HTTP headers, status codes, and the raw response body, prefix any HTTP method call with withRawResponse():
import com.anthropic.core.http.Headers;
import com.anthropic.core.http.HttpResponseFor;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_7)
.build();
HttpResponseFor<Message> message = client.messages().withRawResponse().create(params);
int statusCode = message.statusCode();
Headers headers = message.headers();You can still deserialize the response into an instance of a Java class if needed:
import com.anthropic.models.messages.Message;
Message parsedMessage = message.parse();The SDK uses the standard OkHttp logging interceptor.
Enable logging by setting the ANTHROPIC_LOG environment variable to info:
export ANTHROPIC_LOG=infoOr to debug for more verbose logging:
export ANTHROPIC_LOG=debugThe SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.
To set undocumented request parameters, use the putAdditionalHeader, putAdditionalQueryParam, or putAdditionalBodyProperty methods as described in Undocumented parameters.
To access undocumented response properties, use the _additionalProperties() method as described in Response properties.
Beta features are available before general release to get early feedback and test new functionality. You can check the availability of all of Claude's capabilities and tools in the build with Claude overview.
You can access most beta API features through the beta() method on the client. To enable a particular beta feature, add the appropriate beta header with .addBeta() when building the message params.
For example, to use the Files API:
import com.anthropic.models.beta.AnthropicBeta;
import com.anthropic.models.beta.messages.BetaContentBlockParam;
import com.anthropic.models.beta.messages.BetaMessage;
import com.anthropic.models.beta.messages.BetaRequestDocumentBlock;
import com.anthropic.models.beta.messages.BetaTextBlockParam;
import com.anthropic.models.beta.messages.MessageCreateParams;
void main() {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
BetaMessage message = client.beta().messages().create(
MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_7)
.maxTokens(1024L)
.addBeta(AnthropicBeta.FILES_API_2025_04_14)
.addUserMessageOfBetaContentBlockParams(List.of(
BetaContentBlockParam.ofText(
BetaTextBlockParam.builder()
.text("Please summarize this document for me.")
.build()),
BetaContentBlockParam.ofDocument(
BetaRequestDocumentBlock.builder()
.fileSource("file_abc123")
.build())))
.build());
}This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
Was this page helpful?