Skip to content
javahacks.dev
Spring MVC

OpenAPI Generator Java Clients From Specs With Maven

Generate a Java client or server interfaces from an OpenAPI spec with OpenAPI Generator in Maven and Gradle, and keep generated code out of git.

6 min read
Summarize in AI
Flat illustration of a dependency tree and build phases, with the Apache Maven and OpenJDK logos.

Writing a client for someone else's API by hand is repetitive, and it drifts as the API changes. When the provider publishes an OpenAPI description, a generator can produce the client from it, and when the spec changes you regenerate instead of editing. The tool also works in the other direction: from a spec you own, it can produce server interfaces so the contract lives in one file. This post uses the Maven plugin and mentions Gradle, with OpenAPI Generator 7.

The Maven plugin

XML
<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>7.12.0</version>
  <executions>
    <execution>
      <goals><goal>generate</goal></goals>
      <configuration>
        <inputSpec>${project.basedir}/src/main/openapi/payments.yaml</inputSpec>
        <generatorName>java</generatorName>
        <library>native</library>
        <apiPackage>dev.javahacks.payments.api</apiPackage>
        <modelPackage>dev.javahacks.payments.model</modelPackage>
        <invokerPackage>dev.javahacks.payments</invokerPackage>
        <configOptions>
          <useJakartaEe>true</useJakartaEe>
          <dateLibrary>java8</dateLibrary>
          <openApiNullable>false</openApiNullable>
          <hideGenerationTimestamp>true</hideGenerationTimestamp>
        </configOptions>
      </configuration>
    </execution>
  </executions>
</plugin>

The plugin binds to the generate-sources phase, writes into target/generated-sources/openapi and adds that folder to the compile path, so mvn compile produces the client. inputSpec accepts a URL as well, but a file in the repository that you update on purpose is reproducible, and a URL that changes under you makes a build fail for reasons unrelated to your change. hideGenerationTimestamp keeps the output stable between runs, which matters if you ever diff it. openApiNullable=false avoids a dependency on the jackson-databind-nullable library, at the cost of the three-state null handling it provides.

Pick the HTTP library

The library setting chooses what the generated code uses to talk HTTP.

libraryHTTP stackNotes
nativejava.net.http.HttpClientNo extra HTTP dependency, JDK 11 or later
restclientSpring RestClientFits Spring Boot 3.2 and later
resttemplateSpring RestTemplateOlder Spring code
webclientSpring WebClientReactive stacks
okhttp-gson, jersey3, apache-httpclientThe named libraryPick one you already run

Choose the one that matches the stack you already operate, so pooling, timeouts and metrics come from infrastructure you have already tuned. The generated code still needs its supporting libraries, usually Jackson and the Jakarta annotations, in your pom.xml. A missing one shows up as a pile of compile errors, and the way to read them is in cannot find symbol.

The Gradle plugin

groovy
plugins { id 'org.openapi.generator' version '7.12.0' }

openApiGenerate {
    generatorName = 'java'
    library = 'native'
    inputSpec = "$projectDir/src/main/openapi/payments.yaml"
    outputDir = layout.buildDirectory.dir('generated/openapi').get().asFile.path
    apiPackage = 'dev.javahacks.payments.api'
    modelPackage = 'dev.javahacks.payments.model'
    configOptions = [useJakartaEe: 'true', dateLibrary: 'java8']
}

sourceSets.main.java.srcDir "$buildDir/generated/openapi/src/main/java"
compileJava.dependsOn tasks.openApiGenerate

The last two lines are the ones people forget. Without them the code is generated and then not compiled, or compiled before it exists.

Wrap the generated client

java
ApiClient client = new ApiClient();
client.updateBaseUri("https://api.payments.example.com");
PaymentsApi payments = new PaymentsApi(client);

Payment payment = payments.getPayment("pay_123");

Do not let generated types spread through your code. Put your own class around the client that adds what the generator does not decide for you: timeouts, authentication, retries and error mapping.

java
@Component
class PaymentGateway {

    private final PaymentsApi api;

    PaymentGateway(PaymentsApi api) {
        this.api = api;
    }

    Payment find(String id) {
        try {
            return api.getPayment(id);
        } catch (ApiException e) {
            throw new GatewayException("payment lookup failed for " + id, e);
        }
    }
}

When the provider changes its API and you regenerate, the compiler tells you exactly which calls in PaymentGateway broke, and nothing else in the application has to change. That containment is worth more than any option in the plugin.

Generate the server side instead

With generatorName set to spring and interfaceOnly set to true, you receive controller interfaces annotated with the Spring MVC mappings and the model classes, and you implement the interface yourself. The contract stays in the YAML and the compiler enforces that your controller matches it. This is the design-first approach from documenting an API with OpenAPI. Add useSpringBoot3 for Jakarta packages and delegatePattern if you prefer to keep the controller out of your code entirely.

Habits that save time

Do not commit generated code. Regenerate in the build so the spec is the single source of truth, and add the output directory to .gitignore. Pin the plugin version, because defaults and formatting change between releases and an unpinned build produces diffs nobody asked for. Skip what you do not need: generateApiTests=false and a .openapi-generator-ignore file cut the noise. When the generated code is wrong, fix the spec rather than the output. A missing operationId gives you ugly method names, a vague schema gives you Object, and a wrong nullable flag gives you a NullPointerException at runtime. If the spec belongs to a vendor, report the issue to them and apply a local overlay in the meantime.

Validate a spec before generating from it:

Shell
openapi-generator-cli validate -i src/main/openapi/payments.yaml

When the generated code does not fit

Three problems account for most disappointment with generated clients. The first is naming. Method names come from operationId, and a spec without them produces names assembled from the path and the verb, such as paymentsIdGet. Add an operationId to every operation in the spec, or ask the provider to. The second is types. A schema defined as a bare object becomes Object in Java, and a field marked nullable incorrectly becomes either a surprise null or a failed deserialisation. The third is dates: the default maps date-time values to OffsetDateTime, and dateLibrary changes that, so a mismatch with the rest of your codebase is a one line option, not a reason to give up.

For a type the generator cannot know about, map it yourself:

XML
<typeMappings>
  <typeMapping>DateTime=java.time.Instant</typeMapping>
</typeMappings>
<importMappings>
  <importMapping>Instant=java.time.Instant</importMapping>
</importMappings>

Mappings are blunt tools, and they apply to every use of the type, so test the result against a real response before relying on one. If a vendor spec is so loose that you spend more time bending the generator than writing code, write the client by hand and generate only the model classes, or use the spec as documentation and nothing more.

In a multi-module build

Put the generated client in its own module and depend on it from the services that use it. That compiles the client once, keeps the dependencies it needs in one place, and gives you a single module to bump when the provider releases a new version. The layout is described in multi-module projects.

Keeping a vendor spec current

A spec you check in is a snapshot. Decide who refreshes it and how. A simple routine is a scheduled CI job that downloads the vendor's latest spec, regenerates the client and opens a pull request when the compiled result differs. Reviewers then see in one place what the vendor changed and which of your wrapper methods must follow. Without this, the client ages quietly until a field you rely on is removed and production finds out first.

When a hand-written client is better

For a single endpoint, a few lines of RestClient are simpler than a generator and its configuration. A poor spec produces poor code, and some vendor specs are poor. Read the generated models before you commit to the approach. The options for every generator are listed in the OpenAPI Generator documentation, and the plugins page covers the Maven and Gradle settings.

Also inDevOps
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.