DEV Community

Cover image for How to Implement OpenClaw in a Spring Boot Application (Java)
Mykola Bielousov
Mykola Bielousov

Posted on

How to Implement OpenClaw in a Spring Boot Application (Java)


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:

  1. Install OpenClaw on your machine or VPS using the official installer (for example, via the provided shell script). codecademy
  2. Run the interactive setup and choose a model provider (e.g., OpenAI, Anthropic, Gemini, or an OpenRouter‑backed model). openrouter
  3. Note the gateway URL and auth token (usually via a config file like ~/.openclaw/openclaw.json or 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

  1. Add spring-boot-starter-web:
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
Enter fullscreen mode Exit fullscreen mode
  1. 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
   }
Enter fullscreen mode Exit fullscreen mode

Step 3: Call OpenClaw via RestClient

Spring Boot 3+ encourages using RestClient instead of RestTemplate. docs.spring

  1. 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);
       }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Configure the RestClient.Builder in 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);
       }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Add properties to application.yml:
   openclaw:
     base-url: http://localhost:18789
     auth-token: your-gateway-token
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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+json if your OpenClaw gateway supports SSE‑style streaming. help.apiyi
  • In Spring Boot, expose the streaming endpoint using SseEmitter or WebClient‑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;
}
Enter fullscreen mode Exit fullscreen mode

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 Resilience4j or Spring Retry around OpenClawService calls. 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:

  1. Deploy and configure OpenClaw locally or on a VPS, noting its HTTP gateway URL and auth token. codecademy
  2. In Spring Boot, use RestClient (or WebClient) to call the OpenClaw /v1/chat/completions‑style endpoint. stackoverflow
  3. 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)