Skip to content

Software Development at Program Tom LTD

Place for coding, programming, development and software in general.

Menu
  • Blog
  • PDF Booklets
  • Dev Utils & Content
  • Java Spring Boot Or Web Apps
  • English
    • български
    • English
    • Español
    • Português
    • हिन्दी
    • Русский
    • Deutsch
    • Français
    • Italiano
    • العربية
  • About Us
Menu
Integrating xAI Grok API with Spring Boot

Integrating xAI Grok API with Spring Boot

Posted on November 9, 2025 by Toma Velev

This guide walks you through integrating the xAI Grok API into a Spring Boot application. The Grok API is a RESTful service compatible with OpenAI’s API structure, making it straightforward to use for chat completions, text generation, and more. It powers models like grok-beta, grok-2-latest, and advanced ones like grok-3 or grok-4 (availability depends on your subscription tier). As of November 2025, the API emphasizes real-time knowledge integration and multimodal capabilities.

Note: For official pricing, usage limits, and full documentation, visit https://x.ai/api or the xAI Developer Docs. This guide assumes basic familiarity with Spring Boot and Java.

Prerequisites

  • Java 17+ (Spring Boot 3.x compatible)
  • Maven or Gradle for dependency management
  • An xAI account and API key (steps below)
  • Spring Boot project (use Spring Initializr to generate one with the “Spring Web” dependency)

Step 1: Obtain Your xAI API Key

  1. Visit the xAI Developer Portal (sign in with your X/Twitter, Google, or email account).
  2. Click “Start building now” to access the API console.
  3. Navigate to “Manage API keys” under your dashboard.
  4. Click “Create API key,” provide a name, select endpoints (e.g., /chat/completions), and choose models (e.g., grok-beta for starters).
  5. Copy the generated key (format: xai-...) and store it securely—never commit it to version control. Use environment variables or Spring’s configuration for production.

Security Tip: Treat your API key like a password. It grants access to billable requests.

Note: – to make requests work – you will need to send some funds to xAI, otherwise will fail.

Step 2: Set Up Your Spring Boot Project

  1. Create a new Spring Boot project via Spring Initializr:
  • Group: com.example
  • Artifact: grok-api-demo
  • Dependencies: Spring Web
  • Java: 17+
  1. Add any additional dependencies if needed (e.g., for JSON handling, but Spring Boot includes Jackson by default). Your pom.xml should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version> <!-- Use latest stable -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>grok-api-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Optional: For reactive WebClient -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
    </dependencies>
</project>
  1. In src/main/resources/application.properties, add your API key:
xai.api.key=your_xai_api_key_here
grok.model=grok-beta  # Or grok-3, grok-4 based on access

Step 3: Create a Grok API Service

We’ll use Spring’s RestTemplate for simplicity (or WebClient for reactive apps). This service will handle the /chat/completions endpoint, which generates responses from a conversation.

First, define data classes for requests/responses (OpenAI-compatible):

// src/main/java/com/example/grokapidemo/model/GrokMessage.java
package com.example.grokapidemo.model;

public class GrokMessage {
    private String role;
    private String content;

    public GrokMessage(String role, String content) {
        this.role = role;
        this.content = content;
    }

    // Getters and setters
    public String getRole() { return role; }
    public void setRole(String role) { this.role = role; }
    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
}
// src/main/java/com/example/grokapidemo/model/GrokChatRequest.java
package com.example.grokapidemo.model;

import java.util.List;

public class GrokChatRequest {
    private String model;
    private List<GrokMessage> messages;
    private double temperature; // Optional: 0.0-2.0 for creativity

    public GrokChatRequest(String model, List<GrokMessage> messages) {
        this.model = model;
        this.messages = messages;
        this.temperature = 0.7; // Default
    }

    // Getters and setters
    public String getModel() { return model; }
    public void setModel(String model) { this.model = model; }
    public List<GrokMessage> getMessages() { return messages; }
    public void setMessages(List<GrokMessage> messages) { this.messages = messages; }
    public double getTemperature() { return temperature; }
    public void setTemperature(double temperature) { this.temperature = temperature; }
}
// src/main/java/com/example/grokapidemo/model/GrokChatResponse.java
package com.example.grokapidemo.model;

import com.fasterxml.jackson.annotation.JsonProperty;

public class GrokChatResponse {
    private GrokChoice[] choices;

    // Inner class for choices
    public static class GrokChoice {
        @JsonProperty("message")
        private GrokMessage message;

        public GrokMessage getMessage() { return message; }
        public void setMessage(GrokMessage message) { this.message = message; }
    }

    public GrokChoice[] getChoices() { return choices; }
    public void setChoices(GrokChoice[] choices) { this.choices = choices; }
}

Now, the service class:

// src/main/java/com/example/grokapidemo/service/GrokService.java
package com.example.grokapidemo.service;

import com.example.grokapidemo.model.GrokChatRequest;
import com.example.grokapidemo.model.GrokChatResponse;
import com.example.grokapidemo.model.GrokMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

@Service
public class GrokService {
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Value("${xai.api.key}")
    private String apiKey;

    @Value("${grok.model:grok-beta}")
    private String model;

    private static final String BASE_URL = "https://api.x.ai/v1/chat/completions";

    public String generateResponse(String userPrompt) {
        // Build request
        GrokMessage systemMsg = new GrokMessage("system", "You are Grok, a helpful and witty AI built by xAI.");
        GrokMessage userMsg = new GrokMessage("user", userPrompt);
        GrokChatRequest request = new GrokChatRequest(model, List.of(systemMsg, userMsg));

        // Headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        HttpEntity<GrokChatRequest> entity = new HttpEntity<>(request, headers);

        try {
            ResponseEntity<GrokChatResponse> response = restTemplate.postForEntity(BASE_URL, entity, GrokChatResponse.class);
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null && response.getBody().getChoices().length > 0) {
                return response.getBody().getChoices()[0].getMessage().getContent();
            } else {
                throw new RuntimeException("API request failed: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("Error calling Grok API: " + e.getMessage(), e);
        }
    }
}

Step 4: Create a Test Controller

Expose an endpoint to test the integration:

// src/main/java/com/example/grokapidemo/controller/GrokController.java
package com.example.grokapidemo.controller;

import com.example.grokapidemo.service.GrokService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/grok")
public class GrokController {

    @Autowired
    private GrokService grokService;

    @GetMapping("/chat")
    public String chat(@RequestParam String prompt) {
        return grokService.generateResponse(prompt);
    }
}

Step 5: Run and Test

  1. Run the app: mvn spring-boot:run or via IDE.
  2. Test with curl:
   curl "http://localhost:8080/api/grok/chat?prompt=What is the meaning of life?"

Expected response: A witty Grok-generated answer, e.g., “42, but let’s discuss why that’s hilariously profound.”

This mirrors the official curl example:

curl -X POST https://api.x.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-beta",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What are the key features of the Grok API?"}
    ]
  }'

Advanced Tips

  • Error Handling: Add try-catch for rate limits (e.g., 429 status) and retry logic with Spring Retry.
  • Streaming: For real-time responses, use WebClient with Server-Sent Events (SSE). Set "stream": true in the request.
  • Models: List available models via GET /v1/models (authenticate similarly).
  • Reactive Option: Replace RestTemplate with WebClient for non-blocking calls:
  // In service
  private final WebClient webClient = WebClient.builder()
      .baseUrl("https://api.x.ai/v1")
      .defaultHeader("Authorization", "Bearer " + apiKey)
      .build();
  // Then: webClient.post().uri("/chat/completions").bodyValue(request).retrieve().bodyToMono(GrokChatResponse.class)
  • Monitoring: Track usage in the xAI console. Start with free tiers if available.

If you encounter issues, check the xAI API Reference for updates. Happy building—may your prompts be maximally truthful and minimally boring!

  • Jenkins SCP File Upload to Remote Server
  • Essential Programming Books – Principles & Flutter
  • Social Media Platforms 🌍
  • Strategies to prevent review regressions
  • How to set Google Map Theme in a Flutter App

Categories

  • Apps (22)
  • ChatGPT (23)
  • Choosing a Framework (38)
  • Flutter (269)
  • Graphical User Interface (14)
  • Marketing (117)
  • Software Development (286)
  • Spring (45)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (15)

Tags

Algorithms (9) crypto (29) flutterdev (39) General (86) Java (7) QR & Bar Codes (3) Software Dev Choices (33) Spring Boot (1) standards (1) Theme (3) User Authentication & Authorization (9) User Experience (10) Utilities (19) WordPress (11)

Product categories

  • All Technologies (84)
    • Flutter Apps (24)
    • GPT (4)
    • Java (38)
    • Native Android (3)
    • PHP (9)
    • Spring (Boot) / Quarkus (35)
    • Utils (15)
    • Vaadin 24+ (27)
    • Vaadin 8 (1)
  • Apps (18)
    • Employees DB (1)
    • Notes (6)
    • Personal Budget (1)
    • Recipes Book (1)
    • Stuff Organizer (1)
    • To-Do (2)
  • PDF Books (3)
  • Source Code Generators (8)

Recent Posts

  • Jenkins SCP File Upload to Remote Server
  • Essential Programming Books – Principles & Flutter
  • Social Media Platforms 🌍
  • Strategies to prevent review regressions
  • How to set Google Map Theme in a Flutter App

Post Categories

  • Apps (22)
  • ChatGPT (23)
  • Choosing a Framework (38)
  • Flutter (269)
  • Graphical User Interface (14)
  • Marketing (117)
  • Software Development (286)
  • Spring (45)
  • StartUp (22)
  • Uncategorized (14)
  • Uncategorized (4)
  • Vaadin (15)