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.
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.
- 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.
| 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 |
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.
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.
Endpoint: GET /api/chat/ping
Returns a simple message indicating that the endpoint is reachable.
curl http://localhost:8080/api/chat/pingThis endpoint checks application responsiveness; it does not necessarily verify connectivity to OpenAI.
- Java 17 or a compatible JDK
- Maven 3.8 or later
- An OpenAI API key with access to the configured model
git clone https://github.com/ELGHAD/chatbot.git
cd chatbotAdjust the directory name if your local clone uses a different name.
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=8080Make sure the property names match the configuration used by the application's service and configuration classes.
mvn clean installmvn spring-boot:runThe API should be available at:
http://localhost:8080
mvn testsrc/
├── 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
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.
- 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.
ELGHAD
- GitHub: https://github.com/ELGHAD
- Portfolio: https://elghad.github.io/hamza-elrhadiouini-portfolio
This project is provided for educational purposes. Add a LICENSE file if you intend to distribute it under a specific open-source license.