Integrate OpenAI's API with a Spring Boot application
Here’s an example of how to integrate OpenAI's API with a Spring Boot application. This involves setting up a RESTful API endpoint in Spring Boot that uses OpenAI's API to generate responses.
1. Set Up Your Spring Boot Project
1. Use Spring Initializr to create a new project.
- Dependencies: Spring Web, Spring Boot DevTools, and Spring Configuration Processor.
2. Add the required dependencies in pom.xml for HTTP client support, if not already included:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> </dependency> </dependencies>
2. Add OpenAI Configuration
Create an application.properties file and include your OpenAI API key:
openai.api.key=your-api-key-here openai.api.url=https://api.openai.com/v1/chat/completions
3. Create a Service to Call OpenAI API
Create a service class to handle the interaction with OpenAI's API.
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; @Service public class OpenAIService { @Value("${openai.api.key}") private String apiKey; @Value("${openai.api.url}") private String apiUrl; private final WebClient webClient; public OpenAIService(WebClient.Builder webClientBuilder) { this.webClient = webClientBuilder.baseUrl(apiUrl).build(); } public Mono<String> getChatResponse(String prompt) { String requestBody = """ { "model": "gpt-3.5-turbo", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "%s"} ] } """.formatted(prompt); return webClient.post() .header("Authorization", "Bearer " + apiKey) .header("Content-Type", "application/json") .bodyValue(requestBody) .retrieve() .bodyToMono(String.class); } }
4. Create a REST Controller
Create a controller to expose an API endpoint for clients to send prompts.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; @RestController @RequestMapping("/api/openai") public class OpenAIController { @Autowired private OpenAIService openAIService; @PostMapping("/chat") public Mono<String> chat(@RequestBody ChatRequest chatRequest) { return openAIService.getChatResponse(chatRequest.getPrompt()); } } class ChatRequest { private String prompt; // Getters and Setters public String getPrompt() { return prompt; } public void setPrompt(String prompt) { this.prompt = prompt; } }
5. Run the Application
- Start your Spring Boot application.
- Use a tool like Postman or curl to test the endpoint. Example:
curl -X POST http://localhost:8080/api/openai/chat \ -H "Content-Type: application/json" \ -d '{"prompt": "Tell me a joke"}'
6. Example Response
If the setup is correct, OpenAI will respond with a chat completion. The service will return the response as JSON, which you can parse or display as needed.
Notes
- Replace "gpt-3.5-turbo" with the desired model name.
- If you're using Spring Boot 3 or newer, consider leveraging WebClient (reactive HTTP client) for better async handling, as demonstrated above. If not, you can use RestTemplate instead.
- Ensure your API key remains secure and never hardcode it directly into your code. Use environment variables or secure property files.

Comments
Post a Comment