JAVA — CHAPTER 19

Building API-Based Java Generative AI Applications · Cheat Sheet
OpenAI APIs Chat Completions Speech Image Generation Moderation
1 WORKING WITH OpenAI-STYLE APIS FROM JAVA

Typical setup

  • Get an API key from the provider's dashboard
  • Store it as an environment variable — never hard-code it in source
  • Use an HTTP client (java.net.http.HttpClient) or an official/community Java SDK
HttpClient client = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder() .uri(URI.create("https://api.openai.com/v1/chat/completions")) .header("Authorization", "Bearer " + apiKey) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build();
2 TEXT GENERATION VIA CHAT COMPLETIONS
{ "model": "gpt-4", "messages": [ { "role": "user", "content": "Explain recursion in one sentence." } ] }

The request/response cycle

Send a JSON body with a list of role-tagged messages (system, user, assistant) → get back a JSON response containing the generated text → parse it (Ch.11's JSON techniques) to extract the answer.

3 SPEECH SYNTHESIS & SPEECH RECOGNITION

Text-to-Speech (synthesis)

Send text to a speech endpoint → receive an audio file back (e.g. MP3 bytes) → play it or save it with Java I/O.

Speech-to-Text (recognition)

Send an audio file to a transcription endpoint → receive the transcribed text in the JSON response.

4 IMAGE & VIDEO GENERATION

Image generation

Send a text prompt describing the desired image → the API responds with a URL or base64 data for the generated image, which you download/decode with standard Java I/O.

Video

Similar request/response pattern for emerging video-generation endpoints — typically returns a job ID you poll until the video is ready to download.

5 MODERATION

Before displaying AI-generated or user-submitted content, many apps send it through a moderation endpoint that flags unsafe categories (violence, hate, self-harm, etc.) so the application can filter or block it.

⚠️ Always check moderation results and handle flagged content responsibly before showing it to end users.
6 CLASS OpenAIUtilities — PATTERN

A recurring design pattern: wrap repetitive HTTP + JSON boilerplate (auth headers, request building, response parsing) into a small reusable utility class with static helper methods — e.g. OpenAIUtilities.chat(prompt) — so the rest of the app's code stays clean and focused on business logic.