Overview
OpenClaw is an open‑source, self‑hosted AI agent that exposes a local gateway HTTP API (typically running on http://localhost:18789 or a similar endpoint). help.apiyi
To use it in a Spring Boot app, you treat OpenClaw as a remote REST service and call it via RestClient or WebClient (or RestTemplate if you prefer) from your Java backend. docs.spring
Step 1: Deploy and configure OpenClaw
Before integrating with Spring Boot, ensure OpenClaw is running and accessible:
- Install OpenClaw on your machine or VPS using the official installer (for example, via the provided shell script). codecademy
- Run the interactive setup and choose a model provider (e.g., OpenAI, Anthropic, Gemini, or an OpenRouter‑backed model). openrouter
- Note the gateway URL and auth token (usually via a config file like
~/.openclaw/openclaw.jsonor environment variables). docs.byteplus
Example gateway details:
- URL:
http://localhost:18789/v1/chat/completions - Auth header:
Authorization: Bearer <YOUR_GATEWAY_TOKEN>
Step 2: Set up a Spring Boot project
Create a new Spring Boot project (e.g. with spring-boot-starter-web). docs.spring
- Add
spring-boot-starter-web:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- Create a simple DTO for the OpenClaw request / response if you want strict typing:
public class OpenClawRequest {
private String model;
private List<Message> messages;
// Getters and setters
}
public class Message {
private String role;
private String content;
// Getters and setters
}
public class OpenClawResponse {
private String id;
private String model;
private Choice[] choices;
public static class Choice {
private Message message;
// getters/setters
}
// Getters and setters
}
Step 3: Call OpenClaw via RestClient
Spring Boot 3+ encourages using RestClient instead of RestTemplate. docs.spring
- Create a service bean:
@Service
@RequiredArgsConstructor
public class OpenClawService {
private final RestClient restClient;
public OpenClawResponse ask(String userMessage) {
OpenClawRequest req = new OpenClawRequest();
req.setModel("gpt-4o"); // or your model slug
List<Message> messages = new ArrayList<>();
messages.add(new Message("user", userMessage));
req.setMessages(messages);
return restClient
.post()
.uri("/v1/chat/completions")
.body(req)
.retrieve()
.body(OpenClawResponse.class);
}
}
- Configure the
RestClient.Builderin your config:
@Configuration
public class OpenClawConfig {
@Bean
@Primary
public RestClient.Builder openClawRestClient(
RestClient.Builder builder,
@Value("${openclaw.base-url:http://localhost:18789}") String baseUrl,
@Value("${openclaw.auth-token:}") String token
) {
return builder
.baseUrl(baseUrl)
.defaultHeaders(headers -> {
if (token != null && !token.isEmpty()) {
headers.add("Authorization", "Bearer " + token);
}
headers.add("Content-Type", "application/json");
});
}
@Bean
public OpenClawService openClawService(RestClient.Builder builder) {
RestClient restClient = builder.build();
return new OpenClawService(restClient);
}
}
- Add properties to
application.yml:
openclaw:
base-url: http://localhost:18789
auth-token: your-gateway-token
Step 4: Expose a Spring Boot endpoint
Expose a simple REST endpoint in your controller:
@RestController
@RequestMapping("/ai")
public class OpenClawController {
private final OpenClawService openClawService;
public OpenClawController(OpenClawService openClawService) {
this.openClawService = openClawService;
}
@PostMapping("/chat")
public ResponseEntity<String> chat(@RequestBody ChatRequest request) {
OpenClawResponse response = openClawService.ask(request.getMessage());
if (response.getChoices() != null && response.getChoices().length > 0) {
String content = response.getChoices()[0].getMessage().getContent();
return ResponseEntity.ok(content);
}
return ResponseEntity.status(500).body("No response from OpenClaw");
}
public static class ChatRequest {
private String message;
// getters/setters
}
}
Now you can call POST /ai/chat from your frontend or Postman and it will route through your Spring Boot app to OpenClaw’s gateway. stackoverflow
Step 5: Handling streaming / SSE (optional)
If you want to stream the OpenClaw response (e.g., for a chat‑style UI), you can:
- Use
application/stream+jsonif your OpenClaw gateway supports SSE‑style streaming. help.apiyi - In Spring Boot, expose the streaming endpoint using
SseEmitterorWebClient‑based streaming, depending on whether you want to proxy the stream or consume it as Java objects. youtube
A simple streaming‑style sketch:
@GetMapping("/stream")
public SseEmitter streamChat(@RequestParam String message) {
SseEmitter emitter = new SseEmitter(30_000L);
executor.submit(() -> {
// Use WebClient or direct HttpURLConnection to stream OpenClaw SSE
// For brevity, assume you already have a streaming mechanism in place.
});
return emitter;
}
Best‑practice notes
- Security: Do not expose the OpenClaw gateway directly to the public Internet; keep it internal and call it only from your backend or via a reverse proxy with auth. atlantic
-
Rate‑limiting / retries: Use
Resilience4jor Spring Retry aroundOpenClawServicecalls. reddit - Model‑agnostic usage: OpenClaw is designed to be model‑agnostic, so you can swap providers (OpenAI, Gemini, OpenRouter, etc.) without changing the Java code—only the gateway config and model name. reddit
Summary
To implement OpenClaw in a Spring Boot application:
- Deploy and configure OpenClaw locally or on a VPS, noting its HTTP gateway URL and auth token. codecademy
- In Spring Boot, use
RestClient(orWebClient) to call the OpenClaw/v1/chat/completions‑style endpoint. stackoverflow - Wrap the HTTP client in a service bean and expose a REST controller that your frontend can talk to.
This pattern lets you keep OpenClaw as a backend AI agent while your Spring Boot app remains the orchestration and security layer for your users. reddit
Mykola Bielousov
Top comments (0)