Repository Public
1---2title: Java SDK3url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java4description: Install and configure the Anthropic Java SDK with builder patterns and async support5---67The Anthropic Java SDK provides convenient access to the Claude API from applications written in Java. It uses the builder pattern for creating requests and supports both synchronous and asynchronous operations.89<Info>10 For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Java-specific SDK features and configuration.11</Info>1213## Installation1415<Tabs>16 <Tab title="Gradle">17 ```kotlin18 implementation("com.anthropic:anthropic-java:2.63.0")19 ```20 </Tab>2122 <Tab title="Maven">23 ```xml24 <dependency>25 <groupId>com.anthropic</groupId>26 <artifactId>anthropic-java</artifactId>27 <version>2.63.0</version>28 </dependency>29 ```30 </Tab>31</Tabs>3233## Requirements3435This library requires Java 8 or later.3637<Note>38 The SDK supports Java 8 and later. Code examples in this documentation are written as [JDK 25 compact source files](https://openjdk.org/jeps/512), 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.39</Note>4041## Quick start4243```java44import com.anthropic.client.AnthropicClient;45import com.anthropic.client.okhttp.AnthropicOkHttpClient;46import com.anthropic.models.messages.Message;47import com.anthropic.models.messages.MessageCreateParams;48import com.anthropic.models.messages.Model;4950// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties51// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables52AnthropicClient client = AnthropicOkHttpClient.fromEnv();5354MessageCreateParams params = MessageCreateParams.builder()55 .maxTokens(1024L)56 .addUserMessage("Hello, Claude")57 .model(Model.CLAUDE_OPUS_5)58 .build();5960Message message = client.messages().create(params);61```6263## Client configuration6465### API key setup6667Configure the client using system properties or environment variables:6869```java70import com.anthropic.client.AnthropicClient;71import com.anthropic.client.okhttp.AnthropicOkHttpClient;7273// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties74// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables75AnthropicClient client = AnthropicOkHttpClient.fromEnv();76```7778Or configure manually:7980```java81import com.anthropic.client.AnthropicClient;82import com.anthropic.client.okhttp.AnthropicOkHttpClient;8384AnthropicClient client = AnthropicOkHttpClient.builder()85 .apiKey("my-anthropic-api-key")86 .build();87```8889Or use a combination of both approaches:9091```java92import com.anthropic.client.AnthropicClient;93import com.anthropic.client.okhttp.AnthropicOkHttpClient;9495AnthropicClient client = AnthropicOkHttpClient.builder()96 // Configures using system properties or environment variables97 .fromEnv()98 .apiKey("my-anthropic-api-key")99 .build();100```101102For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK.103104### Configuration options105106| Setter | System property | Environment variable | Required | Default value |107| ----------- | --------------------- | ---------------------- | -------- | ----------------------------- |108| `apiKey` | `anthropic.apiKey` | `ANTHROPIC_API_KEY` | false | - |109| `authToken` | `anthropic.authToken` | `ANTHROPIC_AUTH_TOKEN` | false | - |110| `baseUrl` | `anthropic.baseUrl` | `ANTHROPIC_BASE_URL` | true | `"https://api.anthropic.com"` |111112System properties take precedence over environment variables.113114<Tip>115 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.116</Tip>117118### Modifying configuration119120To temporarily use a modified client configuration while reusing the same connection and thread pools, call `withOptions()` on any client or service:121122```java123import com.anthropic.client.AnthropicClient;124125AnthropicClient clientWithOptions = client.withOptions(optionsBuilder -> {126 optionsBuilder.baseUrl("https://example.com");127 optionsBuilder.maxRetries(42);128});129```130131The `withOptions()` method does not affect the original client or service.132133## Async usage134135The default client is synchronous. To switch to asynchronous execution, call the `async()` method:136137```java138import com.anthropic.client.AnthropicClient;139import com.anthropic.client.okhttp.AnthropicOkHttpClient;140import com.anthropic.models.messages.Message;141import com.anthropic.models.messages.MessageCreateParams;142import com.anthropic.models.messages.Model;143144AnthropicClient client = AnthropicOkHttpClient.fromEnv();145146MessageCreateParams params = MessageCreateParams.builder()147 .maxTokens(1024L)148 .addUserMessage("Hello, Claude")149 .model(Model.CLAUDE_OPUS_5)150 .build();151152CompletableFuture<Message> message = client.async().messages().create(params);153```154155Or create an asynchronous client from the beginning:156157```java158import com.anthropic.client.AnthropicClientAsync;159import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;160import com.anthropic.models.messages.Message;161import com.anthropic.models.messages.MessageCreateParams;162import com.anthropic.models.messages.Model;163164AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();165166MessageCreateParams params = MessageCreateParams.builder()167 .maxTokens(1024L)168 .addUserMessage("Hello, Claude")169 .model(Model.CLAUDE_OPUS_5)170 .build();171172CompletableFuture<Message> message = client.messages().create(params);173```174175The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s.176177## Streaming178179The 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.180181### Synchronous streaming182183These streaming methods return `StreamResponse` for synchronous clients:184185```java186import com.anthropic.core.http.StreamResponse;187import com.anthropic.models.messages.RawMessageStreamEvent;188189try (StreamResponse<RawMessageStreamEvent> streamResponse = client.messages().createStreaming(params)) {190 streamResponse.stream().forEach(chunk -> {191 IO.println(chunk);192 });193 IO.println("No more chunks!");194}195```196197### Asynchronous streaming198199For asynchronous clients, the method returns `AsyncStreamResponse`:200201```java202import com.anthropic.core.http.AsyncStreamResponse;203import com.anthropic.models.messages.RawMessageStreamEvent;204205client.async().messages().createStreaming(params).subscribe(chunk -> {206 IO.println(chunk);207});208209// If you need to handle errors or completion of the stream210client.async().messages().createStreaming(params).subscribe(new AsyncStreamResponse.Handler<>() {211 @Override212 public void onNext(RawMessageStreamEvent chunk) {213 IO.println(chunk);214 }215216 @Override217 public void onComplete(Optional<Throwable> error) {218 if (error.isPresent()) {219 IO.println("Something went wrong!");220 throw new RuntimeException(error.get());221 } else {222 IO.println("No more chunks!");223 }224 }225});226227// Or use futures228client.async().messages().createStreaming(params)229 .subscribe(chunk -> {230 IO.println(chunk);231 })232 .onCompleteFuture()233 .whenComplete((unused, error) -> {234 if (error != null) {235 IO.println("Something went wrong!");236 throw new RuntimeException(error);237 } else {238 IO.println("No more chunks!");239 }240 });241```242243Async streaming uses a dedicated per-client cached thread pool `Executor` to stream without blocking the current thread. To use a different `Executor`:244245```java246Executor executor = Executors.newFixedThreadPool(4);247client.async().messages().createStreaming(params).subscribe(248 chunk -> IO.println(chunk), executor249);250```251252Or configure the client globally using the `streamHandlerExecutor` method:253254```java255import com.anthropic.client.AnthropicClient;256import com.anthropic.client.okhttp.AnthropicOkHttpClient;257258AnthropicClient client = AnthropicOkHttpClient.builder()259 .fromEnv()260 .streamHandlerExecutor(Executors.newFixedThreadPool(4))261 .build();262```263264### Streaming with message accumulator265266A `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.267268For a synchronous response, add a `Stream.peek()` call to the stream pipeline to accumulate each event:269270```java271import com.anthropic.core.http.StreamResponse;272import com.anthropic.helpers.MessageAccumulator;273import com.anthropic.models.messages.Message;274import com.anthropic.models.messages.RawMessageStreamEvent;275276MessageAccumulator messageAccumulator = MessageAccumulator.create();277278try (StreamResponse<RawMessageStreamEvent> streamResponse =279 client.messages().createStreaming(createParams)) {280 streamResponse.stream()281 .peek(messageAccumulator::accumulate)282 .flatMap(event -> event.contentBlockDelta().stream())283 .flatMap(deltaEvent -> deltaEvent.delta().text().stream())284 .forEach(textDelta -> IO.print(textDelta.text()));285}286287Message message = messageAccumulator.message();288```289290For an asynchronous response, add the `MessageAccumulator` to the `subscribe()` call:291292```java293import com.anthropic.helpers.MessageAccumulator;294import com.anthropic.models.messages.Message;295296MessageAccumulator messageAccumulator = MessageAccumulator.create();297298client.async().messages()299 .createStreaming(createParams)300 .subscribe(event -> messageAccumulator.accumulate(event).contentBlockDelta().stream()301 .flatMap(deltaEvent -> deltaEvent.delta().text().stream())302 .forEach(textDelta -> IO.print(textDelta.text())))303 .onCompleteFuture()304 .join();305306Message message = messageAccumulator.message();307```308309A `BetaMessageAccumulator` is also available for the accumulation of a `BetaMessage` object. It is used in the same manner as the `MessageAccumulator`.310311## Structured outputs312313For complete structured outputs documentation including Java examples, see [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs).314315## Tool use316317[Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) 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.318319The 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.320321The 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.322323<Note>324 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.325</Note>326327### Defining tools with annotations328329```java330import com.fasterxml.jackson.annotation.JsonClassDescription;331import com.fasterxml.jackson.annotation.JsonPropertyDescription;332333enum Unit {334 CELSIUS,335 FAHRENHEIT;336337 public String toString() {338 return switch (this) {339 case CELSIUS -> "C";340 case FAHRENHEIT -> "F";341 };342 }343344 public double fromKelvin(double temperatureK) {345 return switch (this) {346 case CELSIUS -> temperatureK - 273.15;347 case FAHRENHEIT -> (temperatureK - 273.15) * 1.8 + 32.0;348 };349 }350}351352@JsonClassDescription("Get the weather in a given location")353static class GetWeather {354355 @JsonPropertyDescription("The city and state, e.g. San Francisco, CA")356 public String location;357358 @JsonPropertyDescription("The unit of temperature")359 public Unit unit;360361 public Weather execute() {362 double temperatureK = switch (location) {363 case "San Francisco, CA" -> 300.0;364 case "New York, NY" -> 310.0;365 case "Dallas, TX" -> 305.0;366 default -> 295;367 };368 return new Weather(String.format("%.0f%s", unit.fromKelvin(temperatureK), unit));369 }370}371372static class Weather {373374 public String temperature;375376 public Weather(String temperature) {377 this.temperature = temperature;378 }379}380```381382### Calling tools383384When 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.385386After calling the tool, use `BetaToolResultBlockParam.Builder.contentAsJson(Object)` to pass the tool's result back to the AI model:387388```java389import com.anthropic.client.AnthropicClient;390import com.anthropic.client.okhttp.AnthropicOkHttpClient;391import com.anthropic.models.beta.messages.*;392import com.anthropic.models.messages.Model;393394AnthropicClient client = AnthropicOkHttpClient.fromEnv();395396MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()397 .model(Model.CLAUDE_OPUS_5)398 .maxTokens(2048)399 .addTool(GetWeather.class)400 .addUserMessage("What's the temperature in New York?");401402client.beta().messages().create(createParamsBuilder.build()).content().stream()403 .flatMap(contentBlock -> contentBlock.toolUse().stream())404 .forEach(toolUseBlock -> createParamsBuilder405 // Add a message indicating that the tool use was requested.406 .addAssistantMessageOfBetaContentBlockParams(407 List.of(BetaContentBlockParam.ofToolUse(BetaToolUseBlockParam.builder()408 .name(toolUseBlock.name())409 .id(toolUseBlock.id())410 .input(toolUseBlock._input())411 .build())))412 // Add a message with the result of the requested tool use.413 .addUserMessageOfBetaContentBlockParams(414 List.of(BetaContentBlockParam.ofToolResult(BetaToolResultBlockParam.builder()415 .toolUseId(toolUseBlock.id())416 .contentAsJson(callTool(toolUseBlock))417 .build()))));418419client.beta().messages().create(createParamsBuilder.build()).content().stream()420 .flatMap(contentBlock -> contentBlock.text().stream())421 .forEach(textBlock -> IO.println(textBlock.text()));422423private static Object callTool(BetaToolUseBlock toolUseBlock) {424 if (!"get_weather".equals(toolUseBlock.name())) {425 throw new IllegalArgumentException("Unknown tool: " + toolUseBlock.name());426 }427428 GetWeather tool = toolUseBlock.input(GetWeather.class);429 return tool != null ? tool.execute() : new Weather("unknown");430}431```432433### Tool name conversion434435Tool names are derived from the camel case tool class names (for example, `GetWeather`) and converted to snake case (for example, `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.436437### Local tool JSON schema validation438439You 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:440441```java442MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()443 .model(Model.CLAUDE_OPUS_5)444 .maxTokens(2048)445 .addTool(GetWeather.class, JsonSchemaLocalValidation.NO)446 .addUserMessage("What's the temperature in New York?");447```448449### Annotating tool classes450451You can use annotations to add further information about tools to the JSON schemas:452453* `@JsonClassDescription` - Add a description to a tool class detailing when and how to use that tool.454* `@JsonTypeName` - Set the tool name to something other than the simple name of the class converted to snake case.455* `@JsonPropertyDescription` - Add a detailed description to a tool parameter.456* `@JsonIgnore` - Exclude a `public` field or getter method from the generated JSON schema for a tool's parameters.457* `@JsonProperty` - Include a non-`public` field or getter method in the generated JSON schema for a tool's parameters.458459## Message batches460461The SDK provides support for [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) under the `client.messages().batches()` namespace. See [Pagination](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#pagination) for how to list and paginate through batches.462463## File uploads464465The SDK defines methods that accept files through the `MultipartField` class:466467```java468import com.anthropic.core.MultipartField;469import com.anthropic.models.files.FileMetadata;470import com.anthropic.models.files.FileUploadParams;471472FileUploadParams params = FileUploadParams.builder()473 .file(474 MultipartField.<InputStream>builder()475 .value(Files.newInputStream(Paths.get("/path/to/file.pdf")))476 .contentType("application/pdf")477 .build()478 )479 .build();480481FileMetadata fileMetadata = client.files().upload(params);482```483484Or from an `InputStream`:485486```java487import com.anthropic.core.MultipartField;488import com.anthropic.models.files.FileMetadata;489import com.anthropic.models.files.FileUploadParams;490491FileUploadParams params = FileUploadParams.builder()492 .file(493 MultipartField.<InputStream>builder()494 .value(URI.create("https://example.com/path/to/file").toURL().openStream())495 .filename("document.pdf")496 .contentType("application/pdf")497 .build()498 )499 .build();500501FileMetadata fileMetadata = client.files().upload(params);502```503504Or from in-memory bytes:505506```java507import com.anthropic.core.MultipartField;508import com.anthropic.models.files.FileMetadata;509import com.anthropic.models.files.FileUploadParams;510511FileUploadParams params = FileUploadParams.builder()512 .file(513 MultipartField.<InputStream>builder()514 .value(new ByteArrayInputStream("content".getBytes()))515 .filename("document.txt")516 .contentType("text/plain")517 .build()518 )519 .build();520521FileMetadata fileMetadata = client.files().upload(params);522```523524### Binary responses525526The SDK defines methods that return binary responses for API responses that aren't necessarily parsed as JSON:527528```java529import com.anthropic.core.http.HttpResponse;530531HttpResponse response = client.files().download("file_abc123");532```533534To save the response content to a file:535536```java537import com.anthropic.core.http.HttpResponse;538539try (HttpResponse response = client.files().download(params)) {540 Files.copy(541 response.body(),542 Paths.get(path),543 StandardCopyOption.REPLACE_EXISTING544 );545} catch (Exception e) {546 IO.println("Something went wrong!");547 throw new RuntimeException(e);548}549```550551Or transfer the response content to any `OutputStream`:552553```java554import com.anthropic.core.http.HttpResponse;555556try (HttpResponse response = client.files().download(params)) {557 response.body().transferTo(Files.newOutputStream(Paths.get(path)));558} catch (Exception e) {559 IO.println("Something went wrong!");560 throw new RuntimeException(e);561}562```563564## Error handling565566The SDK throws custom unchecked exception types:567568* `AnthropicServiceException` - Base class for HTTP errors.569* `AnthropicIoException` - I/O networking errors.570* `AnthropicRetryableException` - Generic error indicating a failure that could be retried.571* `AnthropicInvalidDataException` - Failure to interpret successfully parsed data (for example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it).572* `AnthropicException` - Base class for all exceptions.573574### Status code mapping575576| Status | Exception |577| ------ | ------------------------------- |578| 400 | `BadRequestException` |579| 401 | `UnauthorizedException` |580| 403 | `PermissionDeniedException` |581| 404 | `NotFoundException` |582| 422 | `UnprocessableEntityException` |583| 429 | `RateLimitException` |584| 5xx | `InternalServerException` |585| others | `UnexpectedStatusCodeException` |586587`SseException` is thrown for errors encountered during SSE streaming after a successful initial HTTP response.588589```java590import com.anthropic.errors.*;591592try {593 Message message = client.messages().create(params);594} catch (RateLimitException e) {595 IO.println("Rate limited, retry after: " + e.headers());596} catch (UnauthorizedException e) {597 IO.println("Invalid API key");598} catch (AnthropicServiceException e) {599 IO.println("API error: " + e.statusCode());600} catch (AnthropicIoException e) {601 IO.println("Network error: " + e.getMessage());602}603```604605## Request IDs606607When using [raw responses](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#raw-response-access), you can access the `request-id` response header using the `requestId()` method:608609```java610import com.anthropic.core.http.HttpResponseFor;611import com.anthropic.models.messages.Message;612613HttpResponseFor<Message> message = client.messages().withRawResponse().create(params);614615Optional<String> requestId = message.requestId();616```617618This can be used to quickly log failing requests and report them back to Anthropic. For more information on debugging requests, see [Request ID](https://platform.claude.com/docs/en/api/errors#request-id).619620## Retries621622The SDK automatically retries 2 times by default, with a short exponential backoff between requests.623624Only the following error types are retried:625626* Connection errors (for example, because of a network connectivity problem)627* 408 Request Timeout628* 409 Conflict629* 429 Rate Limit630* 5xx Internal631632The API may also explicitly instruct the SDK to retry or not retry a request.633634To set a custom number of retries, configure the client using the `maxRetries` method:635636```java637import com.anthropic.client.AnthropicClient;638import com.anthropic.client.okhttp.AnthropicOkHttpClient;639640AnthropicClient client = AnthropicOkHttpClient.builder().fromEnv().maxRetries(4).build();641```642643## Timeouts644645Requests time out after 10 minutes by default.646647However, 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:648649```java650Duration.ofSeconds(651 Math.min(652 60 * 60, // 1 hour max653 Math.max(654 10 * 60, // 10 minute minimum655 60 * 60 * maxTokens / 128_000656 )657 )658)659```660661This results in a timeout of up to 60 minutes, scaled by the `maxTokens` parameter, unless overridden.662663For non-streaming requests, the dynamic timeout scales from a 30 second minimum up to a 10 minute maximum based on `maxTokens`.664665To set a custom timeout per-request:666667```java668import com.anthropic.models.messages.Message;669670Message message = client671 .messages()672 .create(params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build());673```674675Or configure the default for all method calls at the client level:676677```java678import com.anthropic.client.AnthropicClient;679import com.anthropic.client.okhttp.AnthropicOkHttpClient;680681AnthropicClient client = AnthropicOkHttpClient.builder()682 .fromEnv()683 .timeout(Duration.ofSeconds(30))684 .build();685```686687## Long requests688689<Warning>690 Consider using [streaming](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#streaming) for longer running requests.691</Warning>692693Avoid 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](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#timeouts) without receiving a response from Anthropic. The SDK periodically pings the API to keep the connection alive and reduce the impact of these networks.694695The SDK throws an error if a non-streaming request is expected to take longer than 10 minutes. Using a [streaming method](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#streaming) or [overriding the timeout](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#timeouts) at the client or request level disables the error.696697## Pagination698699The SDK provides convenient ways to access paginated results either one page at a time or item-by-item across all pages.700701### Auto-pagination702703To iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed.704705```java706import com.anthropic.models.messages.batches.BatchListPage;707import com.anthropic.models.messages.batches.MessageBatch;708709BatchListPage page = client.messages().batches().list();710711// Process as an Iterable712for (MessageBatch batch : page.autoPager()) {713 IO.println(batch);714}715716// Process as a Stream717page.autoPager()718 .stream()719 .limit(50)720 .forEach(batch -> IO.println(batch));721```722723When using the asynchronous client, the method returns an `AsyncStreamResponse`:724725```java726import com.anthropic.core.http.AsyncStreamResponse;727import com.anthropic.models.messages.batches.BatchListPageAsync;728import com.anthropic.models.messages.batches.MessageBatch;729730CompletableFuture<BatchListPageAsync> pageFuture = client.async().messages().batches().list();731732pageFuture.thenAccept(page -> page.autoPager().subscribe(batch -> {733 IO.println(batch);734}));735736// If you need to handle errors or completion of the stream737pageFuture.thenAccept(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() {738 @Override739 public void onNext(MessageBatch batch) {740 IO.println(batch);741 }742743 @Override744 public void onComplete(Optional<Throwable> error) {745 if (error.isPresent()) {746 IO.println("Something went wrong!");747 throw new RuntimeException(error.get());748 } else {749 IO.println("No more!");750 }751 }752}));753754// Or use futures755pageFuture.thenAccept(page -> page.autoPager()756 .subscribe(batch -> {757 IO.println(batch);758 })759 .onCompleteFuture()760 .whenComplete((unused, error) -> {761 if (error != null) {762 IO.println("Something went wrong!");763 throw new RuntimeException(error);764 } else {765 IO.println("No more!");766 }767 }));768```769770### Manual pagination771772To access individual page items and manually request the next page:773774```java775import com.anthropic.models.messages.batches.BatchListPage;776import com.anthropic.models.messages.batches.MessageBatch;777778BatchListPage page = client.messages().batches().list();779while (true) {780 for (MessageBatch batch : page.items()) {781 IO.println(batch);782 }783784 if (!page.hasNextPage()) {785 break;786 }787788 page = page.nextPage();789}790```791792## Type system793794### Immutability and builders795796Each 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.797798```java799MessageCreateParams params = MessageCreateParams.builder()800 .maxTokens(1024L)801 .addUserMessage("Hello, Claude")802 .model(Model.CLAUDE_OPUS_5)803 .build();804805// Create a modified copy using toBuilder()806MessageCreateParams modified = params.toBuilder().maxTokens(2048L).build();807```808809Because each class is immutable, builder modification never affects already built class instances.810811### Requests and responses812813To 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.814815For example, `client.messages().create(...)` should be called with an instance of `MessageCreateParams`, and it returns an instance of `Message`.816817### Undocumented parameters818819To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:820821```java822import com.anthropic.core.JsonValue;823import com.anthropic.models.messages.MessageCreateParams;824825MessageCreateParams params = MessageCreateParams.builder()826 .putAdditionalHeader("Secret-Header", "42")827 .putAdditionalQueryParam("secret_query_param", "42")828 .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))829 .build();830```831832These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.833834<Warning>835 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.836</Warning>837838To set undocumented parameters on nested headers, query params, or body classes:839840```java841import com.anthropic.core.JsonValue;842import com.anthropic.models.messages.MessageCreateParams;843import com.anthropic.models.messages.Metadata;844845MessageCreateParams params = MessageCreateParams.builder()846 .metadata(847 Metadata.builder().putAdditionalProperty("secretProperty", JsonValue.from("42")).build()848 )849 .build();850```851852These properties can be accessed on the nested built object later using the `_additionalProperties()` method.853854To set a documented parameter or property to an undocumented or not yet supported value, pass a `JsonValue` object to its setter:855856```java857import com.anthropic.core.JsonValue;858import com.anthropic.models.messages.MessageCreateParams;859import com.anthropic.models.messages.Model;860861MessageCreateParams params = MessageCreateParams.builder()862 .maxTokens(JsonValue.from(3.14))863 .addUserMessage("Hello, Claude")864 .model(Model.CLAUDE_OPUS_5)865 .build();866```867868### JsonValue creation869870The most straightforward way to create a `JsonValue` is using its `from(...)` method:871872```java873import com.anthropic.core.JsonValue;874875// Create primitive JSON values876JsonValue nullValue = JsonValue.from(null);877878JsonValue booleanValue = JsonValue.from(true);879880JsonValue numberValue = JsonValue.from(42);881882JsonValue stringValue = JsonValue.from("Hello World!");883884// Create a JSON array value equivalent to `["Hello", "World"]`885JsonValue arrayValue = JsonValue.from(List.of("Hello", "World"));886887// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`888JsonValue objectValue = JsonValue.from(Map.of("a", 1, "b", 2));889890// Create an arbitrarily nested JSON equivalent to:891// { "a": [1, 2], "b": [3, 4] }892JsonValue complexValue = JsonValue.from(Map.of("a", List.of(1, 2), "b", List.of(3, 4)));893```894895### Forcibly omitting required parameters896897Normally 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`:898899```java900import com.anthropic.core.JsonMissing;901import com.anthropic.models.messages.MessageCreateParams;902import com.anthropic.models.messages.Model;903904MessageCreateParams params = MessageCreateParams.builder()905 .addUserMessage("Hello, world")906 .model(Model.CLAUDE_OPUS_5)907 .maxTokens(JsonMissing.of())908 .build();909```910911### Response properties912913To access undocumented response properties, call the `_additionalProperties()` method:914915```java916import com.anthropic.core.JsonValue;917918Map<String, JsonValue> additionalProperties = client919 .messages()920 .create(params)921 ._additionalProperties();922923JsonValue secretPropertyValue = additionalProperties.get("secretProperty");924925String result = secretPropertyValue.accept(new JsonValue.Visitor<>() {926 @Override927 public String visitNull() {928 return "It's null!";929 }930931 @Override932 public String visitBoolean(boolean value) {933 return "It's a boolean!";934 }935936 @Override937 public String visitNumber(Number value) {938 return "It's a number!";939 }940941 // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`942 // The default implementation of each unimplemented method delegates to `visitDefault`,943 // which throws by default, but can also be overridden944});945```946947To access a property's raw JSON value, call its `_` prefixed method:948949```java950import com.anthropic.core.JsonField;951import com.anthropic.models.messages.StopReason;952953JsonField<StopReason> stopReason = client.messages().create(params)._stopReason();954955if (stopReason.isMissing()) {956 // The property is absent from the JSON response957} else if (stopReason.isNull()) {958 // The property was set to literal null959} else {960 // Check if value was provided as a string961 // Other methods include `asNumber()`, `asBoolean()`, etc.962 Optional<String> jsonString = stopReason.asString();963964 // Try to deserialize into a custom type965 MyClass myObject = stopReason.asUnknown().orElseThrow().convert(MyClass.class);966}967```968969### Response validation970971By 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.972973To check that the response is completely well-typed upfront, call `validate()`:974975```java976import com.anthropic.models.messages.Message;977978Message message = client.messages().create(params).validate();979```980981Or configure per-request:982983```java984import com.anthropic.models.messages.Message;985986Message message = client987 .messages()988 .create(params, RequestOptions.builder().responseValidation(true).build());989```990991Or configure the default for all method calls at the client level:992993```java994import com.anthropic.client.AnthropicClient;995import com.anthropic.client.okhttp.AnthropicOkHttpClient;996997AnthropicClient client = AnthropicOkHttpClient.builder()998 .fromEnv()999 .responseValidation(true)1000 .build();1001```10021003## HTTP client customization10041005### Proxy configuration10061007```java1008import com.anthropic.client.AnthropicClient;1009import com.anthropic.client.okhttp.AnthropicOkHttpClient;1010import java.net.Proxy;10111012AnthropicClient client = AnthropicOkHttpClient.builder()1013 .fromEnv()1014 .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https://example.com", 8080)))1015 .build();1016```10171018### HTTPS / SSL configuration10191020<Note>1021 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.1022</Note>10231024```java1025import com.anthropic.client.AnthropicClient;1026import com.anthropic.client.okhttp.AnthropicOkHttpClient;10271028AnthropicClient client = AnthropicOkHttpClient.builder()1029 .fromEnv()1030 .sslSocketFactory(yourSSLSocketFactory)1031 .trustManager(yourTrustManager)1032 .hostnameVerifier(yourHostnameVerifier)1033 .build();1034```10351036### Custom HTTP client10371038The SDK consists of three artifacts:10391040* `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.1041* `anthropic-java-client-okhttp` - Depends on OkHttp. Exposes `AnthropicOkHttpClient` and `AnthropicOkHttpClientAsync`.1042* `anthropic-java` - Depends on and exposes the APIs of both `anthropic-java-core` and `anthropic-java-client-okhttp`. Does not have its own logic.10431044This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies.10451046#### Customized OkHttpClient10471048<Tip>1049 Try the available [network options](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#retries) before replacing the default client.1050</Tip>10511052To use a customized `OkHttpClient`:105310541. Replace your `anthropic-java` dependency with `anthropic-java-core`.10552. Copy `anthropic-java-client-okhttp`'s `OkHttpClient` class into your code and customize it.10563. Construct `AnthropicClientImpl` or `AnthropicClientAsyncImpl` using your customized client.10571058#### Completely custom HTTP client10591060To use a completely custom HTTP client:106110621. Replace your `anthropic-java` dependency with `anthropic-java-core`.10632. Write a class that implements the `HttpClient` interface.10643. Construct `AnthropicClientImpl` or `AnthropicClientAsyncImpl` using your new client class.10651066## Platform integrations10671068<Note>1069 For detailed platform setup guides with code examples, see:10701071 * [Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock)1072 * [Amazon Bedrock (Opus 4.6 and earlier)](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy)1073 * [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws)1074 * [Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai)1075 * [Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry)1076</Note>10771078The Java SDK supports the following platforms through separate dependencies that provide platform-specific `Backend` implementations:10791080* **Agent Platform:** `com.anthropic:anthropic-java-vertex`: Use `VertexBackend.fromEnv()` or `VertexBackend.builder()`.1081* **Bedrock:** `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).1082* **Claude Platform on AWS:** `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.1083* **Foundry:** `com.anthropic:anthropic-java-foundry`: Use `FoundryBackend.fromEnv()` or `FoundryBackend.builder()`.10841085Use `BedrockMantleBackend` for new projects; `BedrockBackend` remains for existing applications using the Bedrock `InvokeModel` API.10861087The platform artifacts are add-ons to the base `com.anthropic:anthropic-java` dependency, which provides `AnthropicOkHttpClient`, so install both. 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.10881089## Advanced usage10901091### Raw response access10921093To access HTTP headers, status codes, and the raw response body, prefix any HTTP method call with `withRawResponse()`:10941095```java1096import com.anthropic.core.http.Headers;1097import com.anthropic.core.http.HttpResponseFor;1098import com.anthropic.models.messages.Message;1099import com.anthropic.models.messages.MessageCreateParams;1100import com.anthropic.models.messages.Model;11011102MessageCreateParams params = MessageCreateParams.builder()1103 .maxTokens(1024L)1104 .addUserMessage("Hello, Claude")1105 .model(Model.CLAUDE_OPUS_5)1106 .build();11071108HttpResponseFor<Message> message = client.messages().withRawResponse().create(params);11091110int statusCode = message.statusCode();11111112Headers headers = message.headers();1113```11141115You can still deserialize the response into an instance of a Java class if needed:11161117```java1118import com.anthropic.models.messages.Message;11191120Message parsedMessage = message.parse();1121```11221123### Logging11241125The SDK uses the standard OkHttp logging interceptor.11261127Enable logging by setting the `ANTHROPIC_LOG` environment variable to `info`:11281129```bash1130export ANTHROPIC_LOG=info1131```11321133Or to `debug` for more verbose logging:11341135```bash1136export ANTHROPIC_LOG=debug1137```11381139<Accordion title="Jackson compatibility">1140 The SDK depends on Jackson for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.19.4 by default.11411142 The SDK throws an exception if it detects an incompatible Jackson version at runtime (for example, if the default version was overridden in your Maven or Gradle config).11431144 If the SDK threw an exception, but you're certain the version is compatible, then disable the version check using `checkJacksonVersionCompatibility` on `AnthropicOkHttpClient` or `AnthropicOkHttpClientAsync`.11451146 <Warning>1147 There is no guarantee that the SDK works correctly when the Jackson version check is disabled.1148 </Warning>11491150 There are also bugs in older Jackson versions that can affect the SDK. The SDK doesn't work around all Jackson bugs and expects users to upgrade Jackson for those instead.1151</Accordion>11521153<Accordion title="ProGuard/R8 configuration">1154 Although the SDK uses reflection, it is still usable with ProGuard and R8 because `anthropic-java-core` is published with a configuration file containing keep rules.11551156 ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.1157</Accordion>11581159### Undocumented API functionality11601161The 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.11621163#### Undocumented request parameters11641165To set undocumented request parameters, use the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods as described in [Undocumented parameters](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#undocumented-parameters).11661167#### Undocumented response properties11681169To access undocumented response properties, use the `_additionalProperties()` method as described in [Response properties](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#response-properties).11701171#### New or unreleased enum values11721173Enum-like classes in the SDK, such as `Model` and `AnthropicBeta`, are not closed Java `enum` types. Each one provides an `of(String)` factory method that accepts any string, so you can use values that have not been added to the SDK yet, such as a model or beta header released after your SDK version:11741175```java1176import com.anthropic.models.beta.AnthropicBeta;1177import com.anthropic.models.messages.Model;11781179Model model = Model.of("some-new-model");1180AnthropicBeta beta = AnthropicBeta.of("some-new-beta-2026-01-01");1181```11821183Builder methods that take these types often also provide a `String` overload that calls `of(...)` for you:11841185```java1186import com.anthropic.models.messages.MessageCreateParams;11871188MessageCreateParams params = MessageCreateParams.builder()1189 .model("some-new-model") // same as .model(Model.of("some-new-model"))1190 .maxTokens(1024L)1191 .addUserMessage("Hello, Claude")1192 .build();1193```11941195Prefer the well-typed constants (for example, `Model.CLAUDE_OPUS_5`) so you get autocomplete and deprecation warnings. The `String` overloads and `of(...)` are primarily for setting the field to an undocumented or not yet supported value while waiting for an SDK release that includes it.11961197## Beta features11981199Beta 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](https://platform.claude.com/docs/en/build-with-claude/overview).12001201You can access most beta API features through the `beta()` method on the client. To enable a particular beta feature, add the appropriate [beta header](https://platform.claude.com/docs/en/api/beta-headers) with `.addBeta()` when building the message params.12021203For example, to enable [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing):12041205```java1206import com.anthropic.models.beta.AnthropicBeta;1207import com.anthropic.models.beta.messages.BetaMessage;1208import com.anthropic.models.beta.messages.MessageCreateParams;1209// ...1210void main() {1211 AnthropicClient client = AnthropicOkHttpClient.fromEnv();12121213 BetaMessage message = client.beta().messages().create(1214 MessageCreateParams.builder()1215 .model(Model.CLAUDE_OPUS_5)1216 .maxTokens(1024L)1217 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)1218 .addUserMessage("Hello, Claude")1219 .build());1220}1221```12221223## Frequently asked questions12241225<AccordionGroup>1226 <Accordion title="Why doesn't the SDK use plain enum classes?">1227 Java `enum` classes are not trivially forward compatible. Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.12281229 Because these classes are open, you can also construct them with any string value through their `of(String)` factory method. See [New or unreleased enum values](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java#new-or-unreleased-enum-values) if you need to use a value that isn't in your SDK version yet.1230 </Accordion>12311232 <Accordion title="Why are fields represented using JsonField<T> instead of just plain T?">1233 Using `JsonField<T>` enables a few features:12341235 * Allowing usage of undocumented API functionality1236 * Lazily validating the API response against the expected shape1237 * Representing absent vs explicitly null values1238 </Accordion>12391240 <Accordion title="Why doesn't the SDK use data classes?">1241 It is not backwards compatible to add new fields to a data class, and the SDK avoids introducing a breaking change every time a field is added to a class.1242 </Accordion>12431244 <Accordion title="Why doesn't the SDK use checked exceptions?">1245 Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.12461247 Checked exceptions:12481249 * Are verbose to handle1250 * Encourage error handling at the wrong level of abstraction, where nothing can be done about the error1251 * Are tedious to propagate because of the function coloring problem1252 * Don't play well with lambdas (also because of the function coloring problem)1253 </Accordion>1254</AccordionGroup>12551256## Semantic versioning12571258This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backward-incompatible changes may be released as minor versions:125912601. Changes to library internals which are technically public but not intended or documented for external use.12612. Changes that aren't expected to impact the vast majority of users in practice.12621263## Additional resources12641265* [GitHub repository](https://github.com/anthropics/anthropic-sdk-java)1266* [Javadocs](https://javadoc.io/doc/com.anthropic/anthropic-java)1267* [API reference](https://platform.claude.com/docs/en/api/overview)1268* [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming)1269* [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)1270