Artificial Intelligence is rapidly becoming a core part of modern applications. If you’re a Java developer, integrating AI into your application might sound complex—but it’s actually very simple with the OpenAI API.
In this guide, we’ll walk through how to call the OpenAI API in Java step-by-step, using Maven and clean, beginner-friendly code.
By the end of this tutorial, you’ll be able to:
- Connect Java with OpenAI
- Send prompts and receive AI responses
- Build your own AI-powered features

⚙️ Prerequisites
Before we start, make sure you have:
- Java 8 or above installed
- Maven installed
- An OpenAI API key
👉 You can get your API key from the OpenAI platform.
📦 Step 1: Add Maven Dependency
We will use Java’s built-in HTTP client (no external SDK needed).
Add this dependency if you’re using Java 11+ (for HTTP client support):
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<dependencies> <!-- JSON Processing --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20240303</version> </dependency> </dependencies> |
🏗️ Step 2: Create Java Class
Create a class in package:
|
1 2 3 4 |
package com.kscodes.ai; |
💻 Step 3: Write Code to Call OpenAI API
Here’s a simple example to call the OpenAI API:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package com.kscodes.ai; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import org.json.JSONArray; import org.json.JSONObject; public class OpenAIExample { private static final String API_KEY = "YOUR_API_KEY"; public static void main(String[] args) throws IOException, InterruptedException { String prompt = "Explain Java in simple terms"; JSONObject requestBody = new JSONObject(); requestBody.put("model", "gpt-4o-mini"); JSONArray messages = new JSONArray(); JSONObject message = new JSONObject(); message.put("role", "user"); message.put("content", prompt); messages.put(message); requestBody.put("messages", messages); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.openai.com/v1/chat/completions")) .header("Content-Type", "application/json") .header("Authorization", "Bearer " + API_KEY) .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString())) .build(); HttpClient client = HttpClient.newHttpClient(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); JSONObject jsonResponse = new JSONObject(response.body()); String result = jsonResponse .getJSONArray("choices") .getJSONObject(0) .getJSONObject("message") .getString("content"); System.out.println("AI Response: " + result); } } |
▶️ Step 4: Run the Application
- Replace
"YOUR_API_KEY"with your actual API key - Run the program
You will see an AI-generated response printed in your console 🎉
🔍 How It Works
Here’s what’s happening behind the scenes:
- We create a JSON request with:
- Model name (
gpt-4o-mini) - User prompt
- Model name (
- We send an HTTP POST request to OpenAI API
- OpenAI processes the request and sends back a response
- We extract and print the AI-generated text
💡 Tips & Best Practices
- 🔐 Never hardcode API keys in production (use environment variables)
- ⚡ Handle exceptions properly for production apps
- 📊 Add logging for debugging API responses
- 💰 Monitor API usage to control cost
🎯 Conclusion
Calling the OpenAI API in Java is surprisingly simple. With just a few lines of code, you can integrate powerful AI features into your applications.
This “OpenAI API Java Example” is a great starting point for building:
- Chatbots
- Content generators
- Smart automation tools