Build a Chatbot Using Spring Boot, React JS, and ChatGPT API – A Step-by-Step Guide

🚀 Learn how to integrate OpenAI’s ChatGPT API with a Spring Boot backend and React JS frontend to build a fully functional AI-powered chatbot.

🔹 Introduction: Why Build a Chatbot Using Spring Boot, React JS, and ChatGPT?

With the rise of AI-powered chatbots, integrating OpenAI’s ChatGPT API with a Spring Boot backend and React JS frontend allows you to create intelligent applications that:
✔️ Enhance user engagement by providing real-time AI-powered responses.
✔️ Automate customer support and handle user queries efficiently.
✔️ Use advanced AI models (GPT-4, GPT-3.5, etc.) for dynamic conversation generation.
✔️ Integrate with real-world applications such as e-commerce support, personal assistants, and automated chat systems.

📌 What You Will Learn

✅ How to set up a Spring Boot backend to interact with OpenAI’s API.
✅ How to build a REST API using RestClient to connect with OpenAI.
✅ How to create a React JS frontend using Bootstrap and Axios.
✅ How to connect React JS with the Spring Boot API to send and receive messages.

By the end of this tutorial, you will have a fully functional AI chatbot built with Spring Boot, React JS, and ChatGPT API! 🚀

🔹 Prerequisites

Before starting, make sure you have the following installed:

✔️ Java 23 or higher (Java 23 recommended)
✔️ Spring Boot 3.x
✔️ Node.js (v16 or higher)Download Here
✔️ npm or yarn (for package management)
✔️ An OpenAI API Key – Get it from OpenAI API
✔️ Postman for API testing

🚀 Backend: Build the Spring Boot ChatGPT API

Step 1: Set Up a Spring Boot Project

Use Spring Initializr and configure the project:

  • Project Type: Maven
  • Language: Java
  • Spring Boot Version: 3.x
  • Package Name: com.springboot.chatgpt
  • Dependencies:
    Spring Web (For REST API)

Click "Generate", download the project, and open it in IntelliJ IDEA or VS Code.

Step 2: Add Dependencies to pom.xml

Ensure you have the required dependencies in your pom.xml:

<dependencies>
    <!-- Spring Boot Web Starter for building REST APIs -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Step 3: Configure OpenAI API in application.properties

Open src/main/resources/application.properties and add the OpenAI API details:

openai.api.key=YOUR_API_KEY
openai.api.url=https://api.openai.com/v1/chat/completions
openai.api.model=gpt-4o-mini

✔️ Why store API keys in properties?

  • Keeps credentials secure.
  • Makes it easy to switch between different AI models (GPT-3.5, GPT-4, etc.).

Step 4: Create OpenAI API Configuration (OpenAIConfig.java)

📌 Create OpenAIConfig.java in com.springboot.chatgpt.config

package com.springboot.chatgpt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;

@Configuration
public class OpenAIConfig {

    @Value("${openai.api.url}")
    private String apiUrl;

    @Bean
    public RestClient restClient() {
        return RestClient.builder()
                .baseUrl(apiUrl)
                .build();
    }
}

✔️ This class configures RestClient to interact with OpenAI’s API.
✔️ Dynamically loads API URL from application.properties.

Step 5: Create DTOs for API Requests and Responses

📌 Create ChatGPTRequest.java in com.springboot.chatgpt.dto

package com.springboot.chatgpt.dto;

import java.util.List;

public record ChatGPTRequest(String model, List<Message> messages) {
    public static record Message(String role, String content) {}
}

📌 Create ChatGPTResponse.java in com.springboot.chatgpt.dto

package com.springboot.chatgpt.dto;

import java.util.List;

public record ChatGPTResponse(List<Choice> choices) {
    public static record Choice(Message message) {
        public static record Message(String role, String content) {}
    }
}

📌 Create PromptDTO.java in com.springboot.chatgpt.dto

package com.springboot.chatgpt.dto;

public record PromptDTO(String prompt) {
}

Step 6: Implement ChatGPT Service (ChatGPTService.java)

📌 Create ChatGPTService.java in com.springboot.chatgpt.service

package com.springboot.chatgpt.service;

import com.springboot.chatgpt.dto.ChatGPTRequest;
import com.springboot.chatgpt.dto.ChatGPTResponse;
import com.springboot.chatgpt.dto.PromptDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.util.List;

@Service
public class ChatGPTService {

    private final RestClient restClient;

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

    @Value("${openai.api.model}")
    private String model;

    public ChatGPTService(RestClient restClient) {
        this.restClient = restClient;
    }

    public String getChatResponse(PromptDTO userInput) {
        ChatGPTRequest request = new ChatGPTRequest(
                model,
                List.of(new ChatGPTRequest.Message("user", userInput.prompt()))
        );

        ChatGPTResponse response = restClient.post()
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(request)
                .retrieve()
                .body(ChatGPTResponse.class);

        return response.choices().get(0).message().content();
    }
}

✔️ This service sends user input to OpenAI and retrieves AI-generated responses.

Step 7: Create ChatGPT Controller (ChatGPTController.java)

📌 Create ChatGPTController.java in com.springboot.chatgpt.controller

package com.springboot.chatgpt.controller;

import com.springboot.chatgpt.dto.PromptDTO;
import com.springboot.chatgpt.service.ChatGPTService;
import org.springframework.web.bind.annotation.*;

@CrossOrigin("*")
@RestController
@RequestMapping("/api/chat")
public class ChatGPTController {
    private final ChatGPTService chatGPTService;

    public ChatGPTController(ChatGPTService chatGPTService) {
        this.chatGPTService = chatGPTService;
    }

    @PostMapping
    public String chat(@RequestBody PromptDTO userInput) {
        return chatGPTService.getChatResponse(userInput);
    }
}

✔️ Handles the /api/chat endpoint for chatbot interactions.

Build the React Frontend for the ChatGPT Chatbot

Now that we have completed the Spring Boot backend, it's time to build the React JS frontend. This React app will provide a chat interface for users to interact with the ChatGPT API through our Spring Boot backend.

🚀 Step 8: Create the React App Using Vite.js

We will use Vite.js to create a fast and modern React application.

📌 Run the following commands in your terminal:
# Create a new React project using Vite
npm create vite@latest chatgpt-react --template react

# Move into the project directory
cd chatgpt-react

# Install dependencies
npm install

🚀 Step 9: Install Required Dependencies

Install Bootstrap (for styling) and Axios (for API communication):

npm install bootstrap axios

🔹 Bootstrap - Provides prebuilt UI components.
🔹 Axios - Makes API requests to our Spring Boot backend.

🚀 Step 10: Configure Bootstrap in React

To enable Bootstrap styling in our React app, open src/main.jsx and add:

import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

🚀 Step 11: Create the Chatbot Component (ChatBot.js)

📌 Inside src/components/, create a new file ChatBot.js

import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";

const ChatBot = () => {
    const [input, setInput] = useState("");  // Stores user input
    const [messages, setMessages] = useState([]);  // Stores chat messages
    const chatEndRef = useRef(null);  // Used to auto-scroll chat to the latest message

    // Function to send user message to ChatGPT API
    const sendMessage = async () => {
        if (!input.trim()) return;

        const userMessage = { text: input, sender: "user" };
        setMessages([...messages, userMessage]);

        setInput(""); // Clear input after sending message

        try {
            const res = await axios.post("http://localhost:8080/api/chat", { prompt: input }, {
                headers: { "Content-Type": "application/json" },
            });

            const botMessage = { text: res.data, sender: "bot" };
            setMessages([...messages, userMessage, botMessage]);
        } catch (error) {
            console.error("Error fetching response", error);
            setMessages([...messages, userMessage, { text: "Error retrieving response", sender: "bot" }]);
        }
    };

    // Scroll chat to bottom automatically when new messages arrive
    useEffect(() => {
        chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }, [messages]);

    return (
        <div className="container mt-5">
            <div className="card shadow-lg">
                <div className="card-header bg-primary text-white text-center">
                    <h4>ChatGPT Chatbot</h4>
                </div>

                <div className="card-body chat-box" style={{ height: "400px", overflowY: "auto" }}>
                    {messages.map((msg, index) => (
                        <div key={index} className={`d-flex ${msg.sender === "user" ? "justify-content-end" : "justify-content-start"} mb-2`}>
                            <div className={`p-3 rounded shadow ${msg.sender === "user" ? "bg-primary text-white" : "bg-light text-dark"}`} style={{ maxWidth: "75%" }}>
                                {msg.text}
                            </div>
                        </div>
                    ))}
                    <div ref={chatEndRef} />
                </div>

                <div className="card-footer">
                    <div className="input-group">
                        <input
                            type="text"
                            className="form-control"
                            placeholder="Type your message..."
                            value={input}
                            onChange={(e) => setInput(e.target.value)}
                            onKeyDown={(e) => e.key === "Enter" && sendMessage()} 
                        />
                        <button className="btn btn-primary" onClick={sendMessage}>
                            Send
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ChatBot;

🚀 Step 12: Add ChatBot to App.js

Modify App.js to include the chatbot component:

import React from "react";
import ChatBot from "./components/ChatBot";

function App() {
    return (
        <div className="d-flex justify-content-center align-items-center vh-100">
            <ChatBot />
        </div>
    );
}

export default App;

🚀 Step 13: Run the React Application

Start the React frontend using:

npm run dev

🔹 Open http://localhost:5173 in your browser.

Run the Backend and Test the Chatbot

1️⃣ Run the Spring Boot API

Ensure your Spring Boot backend is running:

mvn spring-boot:run

2️⃣ Test the Chatbot

  • Open http://localhost:5173
  • Type a message in the chatbot UI and press Enter
  • The bot should respond using OpenAI’s API! 🎉
Build a Chatbot Using Spring Boot, React JS, and ChatGPT API

🎯 Summary: What We Achieved

✔️ Built a Spring Boot backend that integrates with OpenAI’s ChatGPT API.
✔️ Created a REST API (/api/chat) to process chatbot requests.
✔️ Developed a React JS frontend with Bootstrap for a clean UI.
✔️ Connected React JS to the Spring Boot backend using Axios.
✔️ Implemented features like auto-scrolling, error handling, and chat history.

🎉 Your AI Chatbot is Now Fully Functional! 🚀

Now, take it to the next level by adding user authentication, chat history, or even multi-language support!

Let me know if you need more improvements or want to deploy this project! 🚀

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare