Build a Spring Boot App that Calls OpenAI’s ChatGPT API

This tutorial walks through creating a Spring Boot application that integrates the OpenAI ChatGPT API, covering prompt concepts, API endpoint details, required request parameters, project setup, necessary dependencies, DTO definitions, RestTemplate configuration, and a REST controller to generate AI‑driven responses.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
Build a Spring Boot App that Calls OpenAI’s ChatGPT API

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 that accepts prompts and returns human‑like text, images, or video. It currently runs on the GPT‑3.5 model, with GPT‑4 available in the Plus version, offering faster responses and advanced 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 (e.g., gpt-3.5-turbo) and a messages array where each message has a role (user or assistant) and content. Optional parameters include n, temperature, and max_tokens. An API key is required for authentication.

3. Create OpenAI API Key

Register on the OpenAI platform and generate your own API key.

4. Project Setup

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;
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Choice {
        private int index;
        private Message message;
    }
}

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

Add configuration 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

@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

@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;
    }
}

The application can now send prompts to OpenAI and receive AI‑generated replies.

7. What Can You Build with the Completion API?

Natural language generation for content creation.

Text summarization.

Language translation.

Text completion.

Question‑answering.

Conversational agents and chatbots.

Code generation and assistance.

Data entry automation.

Creative writing.

Sentiment and intent analysis.

Role‑play simulations.

Educational assistance.

Content recommendation.

Email or document drafting.

User behavior simulation.

Source code: https://github.com/zees007/chatgpt-springboot-integration

JavaBackend DevelopmentChatGPTSpring BootrestOpenAI API
Java High-Performance Architecture
Written by

Java High-Performance Architecture

Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.

0 followers
Reader feedback

How this landed with the community

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.