Generate Plain Old Java Objects (POJOs) from OpenAPI Model Definitions with Gradle

Featured image for sharing metadata for article

It's possible that you're using OpenAPI specifications to describe the format of your API.

If you're on a Java project, it may be that you're currently manually translating from OpenAPI data types to Plain Old Java Objects (POJOs), which is time consuming and has the risk of drifting between your definitions and implementations.

One of the benefits of using a very structured format like the format in OpenAPI specifications is that you can programmatically generate the contents of your Java models, or any other languages you may be using, for that matter.

Example OpenAPI specification

We'll base this on the OpenAPI specification demo from the Petstore, but this also works with OpenAPI specs that have $refs out to JSON schema documents, too!

Generating the POJOs

We can utilise the openapi-generator Gradle plugin to generate this for us, using the following Gradle configuration:

plugins {
  id 'java'
  id 'org.openapi.generator' version '5.4.0'

openApiGenerate {
  generatorName = "java"
  inputSpec = "$rootDir/specs/petstore.yaml"
  outputDir = "$buildDir/generated/sources/openapi"
  modelPackage = "io.swagger.petstore3.api.models"
  generateModelTests = false // personal preference, as it's JUnit 4
  globalProperties = [
    // force only the models
    apis: "false",
    invokers: "false",
    models: "",
  configOptions = [
    dateLibrary: "java8",

compileJava.dependsOn tasks.openApiGenerate += "$buildDir/generated/sources/openapi/src/main/java"

This is a bit stricter to only generate the classes for models, but we can also generate other API metadata such as an autogenerated client for interacting with the API!

This by default will generate a set of GSON models, but if you're i.e. using Spring Boot you'd want:

openApiGenerate {
  configOptions = [
    library: "resttemplate", // for example

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #gradle #java #openapi.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.