Backend Development 11 min read

Integrating OpenAI ChatGPT API with Spring Boot: A Step‑by‑Step Guide

This guide walks you through building a Spring Boot application that calls the OpenAI ChatGPT API, covering prompt concepts, API request details, required dependencies, configuration of RestTemplate with authentication, DTO definitions, controller implementation, and example use cases.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Integrating OpenAI ChatGPT API with Spring Boot: A Step‑by‑Step Guide

In this tutorial we explore how to call the OpenAI ChatGPT API from a Spring Boot application, aiming to generate responses for given prompts.

1. What is ChatGPT?

ChatGPT is a generative AI model that accepts user prompts and returns human‑like text, images or video. It currently runs on the GPT‑3.5 model, with a premium GPT‑4 version offering faster responses and additional capabilities.

2. OpenAI ChatGPT API

We will use the create chat completion endpoint:

POST https://api.openai.com/v1/chat/completions

The request must include the model, a list of messages (each with a role and content ), and optional parameters such as n , temperature , and max_tokens . An API key is required for authentication.

3. Creating an OpenAI API Key

Register on the OpenAI platform and generate your own API key, then store it in the Spring Boot configuration.

4. Project Structure

Add the following dependencies to pom.xml :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

Create DTO classes in the dtos package:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ChatBotRequest {
    private String model;
    private List<Message> messages;
    private int n;
    private double temperature;
    private int max_tokens;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChatBotResponse {
    private List<Choice> choices;
    public static class Choice {
        private int index;
        private Message message;
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Message {
    private String role;
    private String content;
}

Add the following properties to application.properties :

openai.chatgtp.model=gpt-3.5-turbo
openai.chatgtp.api.key=REPLACE_WITH_YOUR_API_KEY
openai.chatgtp.api.url=https://api.openai.com/v1/chat/completions
openai.chatgtp.max-completions=1
openai.chatgtp.temperature=0
openai.chatgtp.max_tokens=100

5. RestTemplate Configuration

Create a configuration class that injects the API key and adds an interceptor to attach the Authorization: Bearer <apiKey> header to every request:

@Configuration
public class OpenAIChatGtpConfig {
    @Value("${openai.chatgtp.api.key}")
    private String openaiApiKey;

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().add("Authorization", "Bearer " + openaiApiKey);
            return execution.execute(request, body);
        });
        return restTemplate;
    }
}

6. API Controller

Implement a REST controller that receives a prompt parameter, builds a ChatBotRequest , and posts it to the OpenAI endpoint:

@RestController
public class ChatBotController {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${openai.chatgtp.model}")
    private String model;
    @Value("${openai.chatgtp.max-completions}")
    private int maxCompletions;
    @Value("${openai.chatgtp.temperature}")
    private double temperature;
    @Value("${openai.chatgtp.max_tokens}")
    private int maxTokens;
    @Value("${openai.chatgtp.api.url}")
    private String apiUrl;

    @PostMapping("/chat")
    public BotResponse chat(@RequestParam("prompt") String prompt) {
        BotRequest request = new BotRequest(model,
            List.of(new Message("user", prompt)),
            maxCompletions, temperature, maxTokens);
        BotResponse response = restTemplate.postForObject(apiUrl, request, BotResponse.class);
        return response;
    }
}

After building and running the application, you can test the /chat endpoint to obtain ChatGPT responses.

7. Possible Applications of the ChatGPT Completion API

Natural language generation (content creation, creative writing)

Text summarization

Language translation

Text completion

Question‑answering

Conversational agents (chatbots, virtual assistants)

Code generation and explanation

Data entry and form filling

Creative writing (poetry, stories)

Sentiment and intent analysis

Role‑play simulations for games

Educational assistance

Content recommendation

Email or document drafting

User behavior simulation for testing

The full source code is available at https://github.com/zees007/chatgpt-springboot-integration .

JavaBackend DevelopmentChatGPTSpring BootRESTOpenAI API
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.