Skip to content

About

A Java REST API built with Spring Boot that integrates OpenAI's GPT-4o-mini model to generate AI-powered chat responses through structured HTTP endpoints.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

Chatbot API — Spring Boot and OpenAI

A Java REST API that integrates OpenAI's GPT-4o-mini model to generate AI-powered conversational responses. Built with Spring Boot, the application exposes HTTP endpoints for chat interactions and API health checks.

Java 17 Spring Boot Maven OpenAI API

Overview

This project demonstrates how to integrate an external large language model into a Java backend application through a RESTful API.

The application receives a user message, forwards the request to OpenAI's API, and returns the generated response as structured JSON. Its codebase separates HTTP request handling, business logic, configuration, and data transfer objects.

Key Features

  • REST API: Expose endpoints for chat interactions.
  • OpenAI Integration: Generate responses using the GPT-4o-mini model.
  • Layered Code Organization: Separate controller, service, configuration, and DTO responsibilities.
  • Request and Response DTOs: Structure incoming messages and outgoing replies.
  • Health Check Endpoint: Verify that the application is responding.
  • CORS Configuration: Support cross-origin frontend integration, with production restrictions recommended.
  • Maven Build: Manage dependencies and run the application's test suite.

Technology Stack

Category Technology
Language Java 17
Backend Framework Spring Boot 3.4.12
HTTP API Spring Web
HTTP Client RestTemplate
AI Provider OpenAI API
Model GPT-4o-mini
Build Tool Maven
Testing Spring Boot Starter Test
Development Tools Spring Boot DevTools, optional Lombok

Architecture

Client / Frontend
       |
       | HTTP request
       v
ChatController
       |
       v
ChatService
       |
       | API request
       v
OpenAI API
       |
       | Generated response
       v
ChatService
       |
       v
ChatResponse DTO
       |
       v
Client / Frontend

The controller handles incoming HTTP requests, the service manages the chat integration, and DTOs define the API request and response structures.

API Endpoints

1. Send a chat message

Endpoint: POST /api/chat

Submit a message and receive an AI-generated response.

Request:

{
  "message": "What is Spring Boot?"
}

Example response:

{
  "reply": "Spring Boot simplifies the development of Java applications built with the Spring ecosystem."
}

Example request using cURL:

curl -X POST http://localhost:8080/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message":"Explain dependency injection in Java."}'

The response text is illustrative; actual responses are generated by the configured model.

2. Check API availability

Endpoint: GET /api/chat/ping

Returns a simple message indicating that the endpoint is reachable.

curl http://localhost:8080/api/chat/ping

This endpoint checks application responsiveness; it does not necessarily verify connectivity to OpenAI.

Getting Started

Prerequisites

  • Java 17 or a compatible JDK
  • Maven 3.8 or later
  • An OpenAI API key with access to the configured model

1. Clone the repository

git clone https://github.com/ELGHAD/chatbot.git
cd chatbot

Adjust the directory name if your local clone uses a different name.

2. Configure the API key

Set the API key as an environment variable instead of hardcoding it in the configuration file.

Windows PowerShell

$env:OPENAI_API_KEY = "your_api_key_here"

Linux or macOS

export OPENAI_API_KEY="your_api_key_here"

Configure the application to read the environment variable:

openai.api.key=${OPENAI_API_KEY}
openai.model=gpt-4o-mini
server.port=8080

Make sure the property names match the configuration used by the application's service and configuration classes.

3. Build the project

mvn clean install

4. Run the application

mvn spring-boot:run

The API should be available at:

http://localhost:8080

5. Run tests

mvn test

Project Structure

src/
├── main/
│   ├── java/com/example/chatbot/
│   │   ├── ChatbotApplication.java
│   │   ├── config/
│   │   │   └── RestTemplateConfig.java
│   │   ├── controller/
│   │   │   └── ChatController.java
│   │   ├── dto/
│   │   │   ├── ChatRequest.java
│   │   │   └── ChatResponse.java
│   │   └── service/
│   │       └── ChatService.java
│   └── resources/
│       └── application.properties
└── test/
    └── java/com/example/chatbot/
        └── ChatbotApplicationTests.java

Security and Reliability

Before exposing the API publicly, consider the following improvements:

  • Secret Management: Load API credentials from environment variables or a dedicated secrets manager.
  • Input Validation: Reject missing, blank, or excessively long messages.
  • Error Handling: Translate upstream API failures into appropriate HTTP responses without exposing internal details.
  • CORS Restrictions: Allow only trusted frontend origins in production.
  • Rate Limiting: Limit requests to control abuse and API costs.
  • Timeouts: Configure HTTP connection and response timeouts.
  • Logging: Avoid logging API keys, sensitive messages, or other confidential data.
  • Testing: Add tests for successful responses, invalid input, and OpenAI API failures using mocked HTTP responses.

The project is a starting point for AI integration in a Java backend, not a production-ready service without these additional controls.

Potential Improvements

  • Add request validation and centralized exception handling.
  • Introduce configurable timeouts and retry policies.
  • Add integration tests with mocked OpenAI responses.
  • Document API contracts using OpenAPI/Swagger.
  • Add Docker support and a reproducible deployment configuration.
  • Evaluate Spring's newer HTTP client options as an alternative to RestTemplate.

Author

ELGHAD

License

This project is provided for educational purposes. Add a LICENSE file if you intend to distribute it under a specific open-source license.

About

A Java REST API built with Spring Boot that integrates OpenAI's GPT-4o-mini model to generate AI-powered chat responses through structured HTTP endpoints.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages