Skip to content

Getting Started: Java

Use Java (11+) with HttpClient to call the BetterPrompt API.

java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
  public static void main(String[] args) throws Exception {
    String apiKey = System.getenv().getOrDefault("BETTERPROMPT_API_KEY", "YOUR_API_KEY");
    String promptVersionId = System.getenv().getOrDefault("BP_PROMPT_VERSION_ID", "YOUR_PROMPT_VERSION_ID");

    String json = "{" +
        "\"promptVersionId\":\"" + promptVersionId + "\"," +
        "\"inputs\":{\"textInputs\":{\"yourField\":\"value\"}}" +
        "}";

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://api.betterprompt.me/v1/runs"))
        .header("Authorization", "Bearer " + apiKey)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();

    HttpClient client = HttpClient.newHttpClient();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.body());
  }
}