Claude API Java Spring Boot Example: Full Guide
If you're building a Spring Boot backend and want to call Claude from Java, the core work is wiring a reactive HTTP client to Anthropic's Messages API, modeling the request/response as DTOs, and exposing a controller endpoint your frontend or mobile app can call. This article walks through a complete, working example using Spring WebFlux's WebClient, plus the configuration, error handling, and streaming considerations you'll actually hit in production.
There's no official Anthropic Java SDK maintained at the same pace as the Python/TypeScript ones, so most Spring Boot teams either hand-roll a thin HTTP client (what we do below) or sit behind a gateway like SubToAPI that exposes the same request/response shape over a stable HTTPS endpoint with API keys and usage tracking built in. We'll show both.
Project Setup
Add the WebFlux and Jackson dependencies to your pom.xml — you don't need the full reactive stack, just WebClient:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
If your app is otherwise a standard MVC (spring-boot-starter-web) project, that's fine. WebClient works inside blocking controllers too — you just call .block() on the returned Mono when you need a synchronous response.
Configuration
Store your key in application.yml, never hardcoded:
claude:
api-key: ${CLAUDE_API_KEY}
base-url: https://api.anthropic.com/v1
model: claude-sonnet-4-5-20250929
Bind it to a config class:
@ConfigurationProperties(prefix = "claude")
public record ClaudeProperties(String apiKey, String baseUrl, String model) {}
Enable it with @EnableConfigurationProperties(ClaudeProperties.class) on your main application class.
Request and Response DTOs
Claude's Messages API expects a JSON body with model, max_tokens, and a messages array. Model the minimum you need:
public record ChatMessage(String role, String content) {}
public record MessageRequest(
String model,
int max_tokens,
List<ChatMessage> messages
) {}
public record ContentBlock(String type, String text) {}
public record MessageResponse(
String id,
String role,
List<ContentBlock> content,
String stop_reason,
Usage usage
) {
public record Usage(int input_tokens, int output_tokens) {}
}
Building the Client Service
@Service
public class ClaudeService {
private final WebClient webClient;
private final ClaudeProperties props;
public ClaudeService(ClaudeProperties props) {
this.props = props;
this.webClient = WebClient.builder()
.baseUrl(props.baseUrl())
.defaultHeader("x-api-key", props.apiKey())
.defaultHeader("anthropic-version", "2023-06-01")
.defaultHeader("content-type", "application/json")
.build();
}
public Mono<MessageResponse> sendMessage(String userPrompt) {
MessageRequest body = new MessageRequest(
props.model(),
1024,
List.of(new ChatMessage("user", userPrompt))
);
return webClient.post()
.uri("/messages")
.bodyValue(body)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError,
resp -> resp.bodyToMono(String.class)
.map(msg -> new IllegalArgumentException("Claude request error: " + msg)))
.onStatus(HttpStatusCode::is5xxServerError,
resp -> Mono.error(new RuntimeException("Claude service unavailable")))
.bodyToMono(MessageResponse.class)
.timeout(Duration.ofSeconds(30))
.retryWhen(Retry.backoff(2, Duration.ofSeconds(1))
.filter(ex -> ex instanceof RuntimeException));
}
}
Exposing a Controller Endpoint
@RestController
@RequestMapping("/api/chat")
public class ChatController {
private final ClaudeService claudeService;
public ChatController(ClaudeService claudeService) {
this.claudeService = claudeService;
}
@PostMapping
public Mono<ResponseEntity<String>> chat(@RequestBody ChatRequest request) {
return claudeService.sendMessage(request.prompt())
.map(resp -> {
String text = resp.content().stream()
.filter(c -> "text".equals(c.type()))
.map(ContentBlock::text)
.collect(Collectors.joining());
return ResponseEntity.ok(text);
})
.onErrorResume(ex -> Mono.just(
ResponseEntity.status(502).body("Upstream error: " + ex.getMessage())
));
}
public record ChatRequest(String prompt) {}
}
This gives you a working /api/chat endpoint that accepts a prompt and returns Claude's text response. Add @Valid and bean validation on ChatRequest for input length limits before shipping to production.
Handling Streaming Responses
Anthropic's API supports server-sent events when you set "stream": true. In Spring, the cleanest way to forward that to a browser is Flux<ServerSentEvent<String>> from a controller, parsing each SSE chunk from the upstream response. This is more involved than the blocking example above because you need to handle partial JSON chunks and content_block_delta events incrementally — worth a dedicated implementation if your UI needs token-by-token output.
Where This Gets Harder
The code above works, but a few things aren't covered:
- Key rotation and per-environment keys — you'll want separate keys for staging/production and a way to revoke one without redeploying.
- Usage visibility — tracking tokens per request to budget costs across teams or customers.
- Rate limit backoff — Anthropic enforces per-minute token and request limits; retry logic needs to respect
retry-afterheaders. - Team access control — if multiple engineers or services need Claude access, sharing one raw key isn't great practice.
This is where routing through SubToAPI can simplify the Spring Boot setup rather than complicate it. You get a sub_live_... application key per project, a dashboard showing usage per key, and the same Messages-style endpoint, so the ClaudeService above only needs its baseUrl and header changed:
.baseUrl("https://api.subtoapi.app/v1")
.defaultHeader("Authorization", "Bearer " + props.apiKey())
A quick sanity check with curl before wiring it into Spring:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Say hello in one sentence."}]
}'
Request and response shapes match the Messages API docs, so the DTOs and service class from this guide don't need rewriting — you're swapping an endpoint, not an architecture. Streaming works the same way too, documented at /docs/streaming, and tool use follows /docs/tools if your Spring app needs function calling. For teams, seats and per-member usage are handled in the dashboard instead of custom code — see /pricing for plan details, or start with a free trial at /signup.
Testing Locally
Mock the WebClient call in unit tests with WireMock or by injecting a stubbed ExchangeFunction, so your test suite doesn't make real API calls on every build. For integration tests against a live key, gate them behind a Maven profile (-Pintegration) so they don't run in CI by default.
Questions
Does Anthropic provide an official Java SDK for Spring Boot? Not with the same first-class support as the Python and TypeScript SDKs. Most Java teams call the REST API directly with WebClient or RestTemplate, as shown above, or use a gateway that exposes a Java-friendly HTTP interface.
Can I use RestTemplate instead of WebClient? Yes. RestTemplate works fine for simple blocking calls, but it's deprecated in favor of WebClient or the newer RestClient in Spring 6+. For streaming responses, WebClient with Flux is the practical choice.
How do I avoid putting the Claude API key in version control? Inject it via environment variables and Spring's ${CLAUDE_API_KEY} placeholder, never commit it to application.yml directly. For multi-environment or multi-team setups, a managed key dashboard like SubToAPI's can replace manual .env handling across services.