skip to content

Developing an OpenAI Java API Client

/ 2 min read

Last year in November, I took on the task of developing a Java API client for OpenAI’s ChatGPT Assistant API, as there was a notable absence of such a tool for Java developers. The result of this endeavor is hosted on GitHub - ainoya/openai-java-generated-client.

Utilizing OpenAI’s API Specification

The project was inspired by OpenAI’s publicly shared API specification on GitHub - openai/openai-openapi. This led me to explore the potential of automating the client generation using the OpenAPI Generator.

Encountered Challenges

Spec vs. Reality

A significant challenge arose from discrepancies between the OpenAI specification and its actual implementation. Mismatches in response key names necessitated direct API calls for correction, resulting in a modified API specification available at openapi.yaml. The Assistant API functions well now, though other parts may still require updates.

Mastering OpenAPI Generator Options

Deciphering the options available in openapi-generator required thorough research and understanding, aided by the official documentation.

The Effective Docker Command

Running the OpenAPI Generator in Docker proved most efficient. The finalized command for generating the client is:

docker run --rm -v ${PWD}:/local openapitools/openapi-generator-cli:v7.1.0 generate \
    -i /local/openapi.yaml --template-dir=/local/custom_template \
    -g java \
    --additional-properties=disallowAdditionalPropertiesIfNotPresent=false,artifactId=openai-java-generated-client,groupId=com.github.ainoya,invokerPackage=com.github.ainoya.client,modelPackage=com.github.ainoya.client.model,developmerName="Naoki Ainoya",developerEmail="xxx",developerOrganization="",developerOrganizationUrl="",artifactVersion=0.0.3 \
    --api-package com.github.ainoya.openai.client.api \
    -o /local/ && \
    ./gradlew test

Auto-Generated Unit Testing

The OpenAPI Generator’s capability to auto-generate unit tests was highly beneficial. The command includes running ./gradlew test after generation, enabling quick identification of any issues.

Opting for JitPack over GitHub Packages

While initially considering GitHub Packages, its constraints did not align with my usage requirements. Consequently, I opted for JitPack, which proved more suitable for my needs. The API client is available at JitPack - ainoya/openai-java-generated-client. The need for a Private Access Token (PAT) even for public packages on GitHub Packages was a deciding factor, as elaborated in GitHub Community Discussion #25629.