It's easy to work with templates for codegen!

The generator workflow has transforming logic as well as templates for each generation of code.

Each generator will create a data structure from the OpenAPI document; OpenAPI 2.0 and OpenAPI 3.x documents are normalized into the same API model within the generator. This model is then applied to the templates. While generators do not need to perform transformations, it's often necessary in order to add more advanced support for your language or framework. You may need to refer to the generator implementation to understand some of the logic while creating or customizing templates (see ScalaFinchServerCodegen.java for an advanced example).

The transform logic needs to implement CodegenConfig.java and is most easily done by extending DefaultCodegen.java. Take a look at the various implementations as a guideline while the instructions get more complete.

Modifying Templates

OpenAPI Generator applies user-defined templates via options:

  • CLI: -t/—template CLI options
  • Maven Plugin: templateDirectory
  • Gradle Plugin: templateDir

Built-in templates are written in Mustache and processed by jmustache. Beginning with version 4.0.0, we support experimental Handlebars and user-defined template engines via plugins.

OpenAPI Generator supports user-defined templates. This approach is often the easiest when creating a custom template. Our generators implement a combination of language and framework features, and it's fully possible to use an existing generator to implement a custom template for a different framework. Suppose you have internal utilities which you'd like to incorporate into generated code (e.g. logging, monitoring, fault-handling)… this is easy to add via custom templates.

Note: You cannot use this approach to create new templates, only override existing ones. If you'd like to create a new generator to contribute back to the project, see new.sh in the repository root. If you'd like to create a private generator for more templating control, see the customization docs.

Custom Logic

For this example, let's modify a Java client to use AOP via jcabi/jcabi-aspects. We'll log API method execution at the INFO level. The jcabi-aspects project could also be used to implement method retries on failures; this would be a great exercise to further play around with templating.

The Java generator supports a library option. This option works by defining base templates, then applying library-specific template overrides. This allows for template reuse for libraries sharing the same programming language. Templates defined as a library need only modify or extend the templates concerning the library, and generation falls back to the root templates (the "defaults") when not extended by the library. Generators which support the library option will only support the libraries known by the generator at compile time, and will throw a runtime error if you try to provide a custom library name.

To get started, we will need to copy our target generator's directory in full. The directory will be located under modules/opeanpi-generator/src/main/resources/{generator}. In general, the generator directory matches the generator name (what you would pass to the generator option), but this is not a requirement— if you are having a hard time finding the template directory, look at the embeddedTemplateDir option in your target generator's implementation.

If you've already cloned openapi-generator, find and copy the modules/opeanpi-generator/src/main/resources/Java directory. If you have the Refined GitHub Chrome or Firefox Extension, you can navigate to this directory on GitHub and click the "Download" button. Or, to pull the directory from latest master:

  1. mkdir -p ~/.openapi-generator/templates/ && cd $_
  2. curl -L https://api.github.com/repos/OpenAPITools/openapi-generator/tarball | tar xz
  3. mv `ls`/modules/openapi-generator/src/main/resources/Java ./Java
  4. \rm -rf OpenAPITools-openapi-generator-*
  5. cd Java

Optional: Before modifying your templates, you may want to git init && git add . && git commit -am 'initial' so you can easily revert to the base templates.

At this point, you have every Java library's template locally. Let's delete all libraries except the resteasy library we'll be extending:

  1. ls -d libraries/* | grep -v resteasy | xargs rm -rf

Execute tree in this Java directory and inspect the mustache files and directory structure. You'll notice there are quite a few templates in the directory root, but extending this root to support resteasy only requires modifying a handful of files:

  1. tree libraries/resteasy/
  2. libraries/resteasy/
  3. ├── ApiClient.mustache
  4. ├── JSON.mustache
  5. ├── api.mustache
  6. ├── build.gradle.mustache
  7. ├── build.sbt.mustache
  8. └── pom.mustache
  9. 0 directories, 6 files

NOTE: Some generators may be sensitive to which files exist. If you're concerned with redundant files like pom.mustache and build.sbt.mustache, you can try deleting them. If the generator you're customizing fails at runtime, just touch these files to create an empty file.

First, let's add our new dependency to libraries/resteasy/build.gradle.mustache:

  1. diff --git a/libraries/resteasy/build.gradle.mustache b/libraries/resteasy/build.gradle.mustache
  2. index 3b40702..a6d12e0 100644
  3. --- a/libraries/resteasy/build.gradle.mustache
  4. +++ b/libraries/resteasy/build.gradle.mustache
  5. @@ -134,6 +134,7 @@ ext {
  6. }
  7. dependencies {
  8. + compile "com.jcabi:jcabi-aspects:0.22.6"
  9. compile "io.swagger:swagger-annotations:$swagger_annotations_version"
  10. compile "org.jboss.resteasy:resteasy-client:$resteasy_version"
  11. compile "org.jboss.resteasy:resteasy-multipart-provider:$resteasy_version"

Then, we'll add the necessary import to api.mustache. This file is the template which becomes the API invoking class (e.g. PetApi or StoreApi).

  1. diff --git a/libraries/resteasy/api.mustache b/libraries/resteasy/api.mustache
  2. index a4d0f9f..49b17c7 100644
  3. --- a/libraries/resteasy/api.mustache
  4. +++ b/libraries/resteasy/api.mustache
  5. @@ -1,5 +1,6 @@
  6. package {{package}};
  7. +import com.jcabi.aspects.Loggable;
  8. import {{invokerPackage}}.ApiException;
  9. import {{invokerPackage}}.ApiClient;
  10. import {{invokerPackage}}.Configuration;

Next, we'll find the code which generates API methods. You'll see {{#operations}}{{#operation}} which is a mustache "loop" which executes the template logic if the model applied to the template has an operations array, and a non-null operation instance in that array. You can pass -DdebugOpenAPI when generating via CLI to inspect the full object model.

Further down in api.mustache, find implementation of the method call, and add the @Loggable annotation. This template is easy because it has a single method implementation.

  1. diff --git a/libraries/resteasy/api.mustache b/libraries/resteasy/api.mustache
  2. index 49b17c7..16ee191 100644
  3. --- a/libraries/resteasy/api.mustache
  4. +++ b/libraries/resteasy/api.mustache
  5. @@ -57,6 +57,7 @@ public class {{classname}} {
  6. {{#isDeprecated}}
  7. @Deprecated
  8. {{/isDeprecated}}
  9. + @Loggable(Loggable.INFO)
  10. public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
  11. Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};
  12. {{#allParams}}{{#required}}

Finally, because our new dependency relies on AspectJ and code weaving, let's modify the build.gradle.mustache again to set this up.

  1. diff --git a/build.gradle.mustache b/build.gradle.mustache
  2. index 04a9d55..7a93c50 100644
  3. --- a/build.gradle.mustache
  4. +++ b/build.gradle.mustache
  5. @@ -1,5 +1,6 @@
  6. apply plugin: 'idea'
  7. apply plugin: 'eclipse'
  8. +apply plugin: 'aspectj'
  9. group = '{{groupId}}'
  10. version = '{{artifactVersion}}'
  11. @@ -12,6 +13,7 @@ buildscript {
  12. dependencies {
  13. classpath 'com.android.tools.build:gradle:2.3.+'
  14. classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
  15. + classpath "net.uberfoo.gradle:gradle-aspectj:2.2"
  16. }
  17. }
  18. @@ -140,9 +142,18 @@ ext {
  19. jersey_version = "1.19.4"
  20. jodatime_version = "2.9.9"
  21. junit_version = "4.12"
  22. + aspectjVersion = '1.9.0'
  23. }
  24. +sourceCompatibility = '1.8'
  25. +targetCompatibility = '1.8'
  26. +
  27. dependencies {
  28. + compile "com.jcabi:jcabi-aspects:0.22.6"
  29. + aspectpath "com.jcabi:jcabi-aspects:0.22.6"
  30. + // usually, client code leaves logging implementation to the consumer code
  31. + compile "org.apache.logging.log4j:log4j-slf4j-impl:2.8.2"
  32. + compile "org.apache.logging.log4j:log4j-core:2.8.2"
  33. compile "io.swagger:swagger-annotations:$swagger_annotations_version"
  34. compile "com.sun.jersey:jersey-client:$jersey_version"
  35. compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"

NOTE: This example includes log4j-slf4j-impl to demonstrate that our new code is working. Generally you'll want to leave logging implementations up to your consumers.

And because the java client generates with an outdated Gradle 2.6, let's update the gradle version in the default template (Java/gradle-wrapper.properties.mustache):

  1. diff --git a/gradle-wrapper.properties.mustache b/gradle-wrapper.properties.mustache
  2. index b7a3647..3d9d088 100644
  3. --- a/gradle-wrapper.properties.mustache
  4. +++ b/gradle-wrapper.properties.mustache
  5. @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
  6. distributionPath=wrapper/dists
  7. zipStoreBase=GRADLE_USER_HOME
  8. zipStorePath=wrapper/dists
  9. -distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip
  10. +distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-bin.zip

Now we're ready to generate the client with our simple changes. When we pass the template directory option to our toolset, we must pass the generator's root directory and not the library-only directory.

  1. openapi-generator generate -g java --library resteasy \
  2. -t ~/.openapi-generator/templates/Java \
  3. -o ~/.openapi-generator/example \
  4. -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/2_0/petstore.yaml

Make sure your custom template compiles:

  1. cd ~/.openapi-generator/example
  2. gradle assemble
  3. # or, regenerate the wrapper
  4. gradle wrapper --gradle-version 4.8 --distribution-type all
  5. ./gradlew assemble

You should see a log message showing our added dependency being downloaded:

  1. Download https://jcenter.bintray.com/com/jcabi/jcabi-aspects/0.22.6/jcabi-aspects-0.22.6.pom

And for the sake of verifying our AOP modifications work, let's create a src/main/resources/log4j2.properties file in our new client code:

  1. status = error
  2. dest = err
  3. name = PropertiesConfig
  4. property.filename = target/rolling/rollingtest.log
  5. filter.threshold.type = ThresholdFilter
  6. filter.threshold.level = debug
  7. appender.console.type = Console
  8. appender.console.name = STDOUT
  9. appender.console.layout.type = PatternLayout
  10. appender.console.layout.pattern = %m%n
  11. appender.console.filter.threshold.type = ThresholdFilter
  12. appender.console.filter.threshold.level = error
  13. appender.rolling.type = RollingFile
  14. appender.rolling.name = RollingFile
  15. appender.rolling.fileName = ${filename}
  16. appender.rolling.filePattern = target/rolling2/test1-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
  17. appender.rolling.layout.type = PatternLayout
  18. appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
  19. appender.rolling.policies.type = Policies
  20. appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
  21. appender.rolling.policies.time.interval = 2
  22. appender.rolling.policies.time.modulate = true
  23. appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
  24. appender.rolling.policies.size.size=100MB
  25. appender.rolling.strategy.type = DefaultRolloverStrategy
  26. appender.rolling.strategy.max = 5
  27. logger.rolling.name = org.openapitools.client.api.PetApi
  28. logger.rolling.level = debug
  29. logger.rolling.additivity = false
  30. logger.rolling.appenderRef.rolling.ref = RollingFile
  31. rootLogger.level = info
  32. rootLogger.appenderRef.stdout.ref = STDOUT

Execute ./gradlew build and then cat target/rolling/rollingtest.log. You should see messages logged for every call in PetApi with a stubbed unit test.

Congratulations! You've now modified one of the built-in templates to meet your client code's needs.

Adding/modifying template logic simply requires a little bit of mustache, for which you can use existing templates as a guide.

Custom Engines

Custom template engine support is experimental

If Mustache or the experimental Handlebars engines don't suit your needs, you can define an adapter to your templating engine of choice. To do this, you'll need to define a new project which consumes the openapi-generator-core artifact, and at a minimum implement TemplatingEngineAdapter.

This example:

  • creates an adapter providing the fundamental logic to compile Pebble Templates
  • will be implemented in Kotlin to demonstrate ServiceLoader configuration specific to Kotlin (Java will be similar)
  • requires Gradle 5.0+
  • provides project setup instructions for IntelliJTo begin, create a new Gradle project with Kotlin support. To do this, go to FileNewProject, choose "Gradle" and "Kotlin". Specify groupId org.openapitools.examples and artifactId pebble-template-adapter.

Ensure the new project uses Gradle 5.0. Navigate to the newly created directory and execute:

  1. gradle wrapper --gradle-version 5.0

In build.gradle, we'll add a dependency for OpenAPI Tools core which defines the interface and an abstract helper type for implementing the adapter. We'll also pull in the Pebble artifact. We'll be evaluating this new artifact locally, so we'll also add the Maven plugin for installing to the local maven repository. We'll also create a fatjar using the shadow plugin to simplify our classpath.

Modifications to the new project's build.gradle should be made in the plugins and dependencies nodes:

  1. plugins {
  2. id 'org.jetbrains.kotlin.jvm' version '1.3.11'
  3. id "com.github.johnrengelman.shadow" version "5.0.0"
  4. }
  5. dependencies {
  6. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
  7. compile "org.openapitools:openapi-generator-core:4.0.0-SNAPSHOT"
  8. compile "io.pebbletemplates:pebble:3.0.8"
  9. }

The above configuration for the shadow plugin is strictly optional. It is not needed, for instance, if you plan to publish your adapter and consume it via the Maven or Gradle plugins.

Next, create a new class file called PebbleTemplateEngineAdapter under src/kotlin. We'll define the template adapter's name as pebble and we'll also list this as the only supported file extension. We'll implement the adapter by extending AbstractTemplatingEngineAdapter, which includes reusable logic, such as retrieving a list of all possible template names for our provided template extensions(s).

The class in its simplest form looks like this (with inline comments):

  1. // Allows specifying engine by class name
  2. // e.g. -e org.openapitools.examples.templating.PebbleTemplateAdapter
  3. @file:JvmName("PebbleTemplateAdapter")
  4. package org.openapitools.examples.templating
  5. // imports
  6. class PebbleTemplateAdapter : AbstractTemplatingEngineAdapter() {
  7. // initialize the template compilation engine
  8. private val engine: PebbleEngine = PebbleEngine.Builder()
  9. .cacheActive(false)
  10. .loader(DelegatingLoader(listOf(FileLoader(), ClasspathLoader())))
  11. .build()
  12. // allows targeting engine by id/name: -e pebble
  13. override fun getIdentifier(): String = "pebble"
  14. override fun compileTemplate(
  15. generator: TemplatingGenerator?,
  16. bundle: MutableMap<String, Any>?,
  17. templateFile: String?
  18. ): String {
  19. // This will convert, for example, model.mustache to model.pebble
  20. val modifiedTemplate = this.getModifiedFileLocation(templateFile).first()
  21. // Uses generator built-in template resolution strategy to find the full template file
  22. val filePath = generator?.getFullTemplatePath(modifiedTemplate)
  23. val writer = StringWriter()
  24. // Conditionally writes out the template if found.
  25. if (filePath != null) {
  26. engine.getTemplate(filePath.toAbsolutePath().toString())?.evaluate(writer, bundle)
  27. }
  28. return writer.toString()
  29. }
  30. override fun getFileExtensions(): Array<String> = arrayOf("pebble")
  31. }

Lastly, create a file resources/META-INF/services/org.openapitools.codegen.api.TemplatingEngineAdapter, containing the full class path to the above class:

  1. org.openapitools.examples.templating.PebbleTemplateAdapter

This allows the adapter to load via ServiceLoader, and to be referenced via the identifier pebble. This is optional; if you don't provide the above file and contents, you'll only be able to load the engine via full class name (explained in a bit).

Now, build the fatjar for this new adapter:

  1. ./gradlew shadowJar

To test compilation of some templates, we'll need to first create one or more template files. Create a temp directory at /tmp/pebble-example/templates and add the following files.

api.pebble

  1. package {{packageName}}
  2. import (
  3. "net/http"
  4. {% for item in imports %}
  5. "{{item.import}}"
  6. {% endfor %}
  7. )
  8. type Generated{{classname}}Servicer
  9. // etc

model.pebble

  1. package {{packageName}}
  2. {% for item in models %}
  3. {% if item.isEnum %}
  4. // TODO: enum
  5. {% else %}
  6. {% if item.description is not empty %}// {{item.description}}{% endif %}
  7. type {{item.classname}} struct {
  8. {% for var in item.model.vars %}
  9. {% if var.description is not empty %}// {{var.description}}{% endif %}
  10. {{var.name}} {% if var.isNullable %}*{% endif %}{{var.dataType}} `json:"{{var.baseName}}{% if var.required == false %},omitempty{% endif %}"{% if var.withXml == true %} xml:"{{var.baseName}}{% if var.isXmlAttribute %},attr{% endif %}"{% endif %}`
  11. {% endfor %}
  12. }
  13. {% endif %}
  14. {{model.name}}
  15. {% endfor %}

Find object structures passed to templates later in this document's Structures section.

Finally, we can compile some code by explicitly defining our classpath and jar entrypoint for CLI (be sure to modify /your/path below)

  1. java $JAVA_OPTS -cp /your/path/build/libs/pebble-template-adapter-1.0-SNAPSHOT-all.jar:modules/openapi-generator-cli/target/openapi-generator-cli.jar \
  2. org.openapitools.codegen.OpenAPIGenerator \
  3. generate \
  4. -g go \
  5. -i https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/json/petstore-minimal.json \
  6. -e pebble \
  7. -o /tmp/pebble-example/out \
  8. -t /tmp/pebble-example/templates \
  9. -Dmodels -DmodelDocs=false -DmodelTests=false -Dapis -DapiTests=false -DapiDocs=false

Notice how we've targeted our custom template engine adapter via -e pebble. If you don't include the SPI file under META-INF/services, you'll need to specify the exact classpath: org.openapitools.examples.templating.PebbleTemplateAdapter. Notice that the target class here matches the Kotlin class name. This is because of the @file:JvmName annotation.

Congratulations on creating a custom templating engine adapter!

Structures

Aside from transforming an API document, the implementing class gets to decide how to apply the data structure to templates. We can decide which data structure to apply to which template files. You have the following structures at your disposal.

Examples for the following structures will be presented using the following spec document:

  1. swagger: "2.0"
  2. info:
  3. version: "1.0.0"
  4. title: "Swagger Petstore"
  5. description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification"
  6. termsOfService: "http://swagger.io/terms/"
  7. contact:
  8. name: "Swagger API Team"
  9. license:
  10. name: "MIT"
  11. host: "petstore.swagger.io"
  12. basePath: "/api"
  13. schemes:
  14. - "http"
  15. consumes:
  16. - "application/json"
  17. produces:
  18. - "application/json"
  19. paths:
  20. /pets:
  21. get:
  22. description: "Returns all pets from the system that the user has access to"
  23. produces:
  24. - "application/json"
  25. responses:
  26. "200":
  27. description: "A list of pets."
  28. schema:
  29. type: "array"
  30. items:
  31. $ref: "#/definitions/Pet"
  32. definitions:
  33. Pet:
  34. type: "object"
  35. required:
  36. - "id"
  37. - "name"
  38. properties:
  39. id:
  40. type: "integer"
  41. format: "int64"
  42. name:
  43. type: "string"
  44. tag:
  45. type: "string"

Operations

Inspect operation structures passed to templates with system property -DdebugOpenAPI

Example:

  1. openapi-generator generate -g go \ -o out \ -i petstore-minimal.yaml \ -DdebugOpenAPI

There is a data structure which represents all the operations that are defined in the OpenAPI specification. A single API file is created for each OperationGroup, which is essentially a grouping of different operations. See the addOperationToGroup in DefaultCodegen.java for details on this operation.

You can have many files created for each OperationGroup by processing multiple templates and assigning a different file naming pattern to them. So for a single file per operation:

  1. // process the `api.mustache` template and output a single file with suffix `.java`:
  2. apiTemplateFiles.put("api.mustache", ".java");

For C-like languages which also require header files, you may create two files per operation.

  1. // create a header and implementation for each operation group:
  2. apiTemplateFiles.put("api-header.mustache", ".h");
  3. apiTemplateFiles.put("api-body.mustache", ".m");

Here, an Operation with tag Pet will generate two files: SWGPetApi.h and SWGPetApi.m. The SWG prefix and Api suffix are options specific to the Objective-C geneator.

Models

Inspect models passed to templates with system property -DdebugModels

Execute:

  1. openapi-generator generate -g go \ -o out \ -i petstore-minimal.yaml \ -DdebugModels

Each model identified inside the generator will be passed into the Models data structure and will generate a new model file (or files) for each model.

A Pet model with three properties will provide a lot of information about the type and properties. The output from -DdebugModels is presented in truncated format here.

  1. [ {
  2. "importPath" : "openapi.Pet",
  3. "model" : {
  4. "name" : "Pet",
  5. "classname" : "Pet",
  6. "classVarName" : "Pet",
  7. "modelJson" : "{\n \"required\" : [ \"id\", \"name\" ],\n \"type\" : \"object\",\n \"properties\" : {\n \"id\" : {\n \"type\" : \"integer\",\n \"format\" : \"int64\"\n },\n \"name\" : {\n \"type\" : \"string\"\n },\n \"tag\" : {\n \"type\" : \"string\"\n }\n }\n}",
  8. "dataType" : "map[string]interface{}",
  9. "classFilename" : "model_pet",
  10. "isAlias" : false,
  11. "isString" : false,
  12. "isInteger" : false,
  13. "vars" : [ {
  14. "baseName" : "id",
  15. "getter" : "getId",
  16. "setter" : "setId",
  17. "dataType" : "int64",
  18. "datatypeWithEnum" : "int64",
  19. "dataFormat" : "int64",
  20. "name" : "Id",
  21. "defaultValueWithParam" : " = data.id;",
  22. "baseType" : "int64",
  23. "example" : "null",
  24. "jsonSchema" : "{\n \"type\" : \"integer\",\n \"format\" : \"int64\"\n}",
  25. "exclusiveMinimum" : false,
  26. "exclusiveMaximum" : false,
  27. "hasMore" : true,
  28. "required" : true,
  29. "secondaryParam" : false,
  30. "hasMoreNonReadOnly" : true,
  31. "isPrimitiveType" : true,
  32. "isModel" : false,
  33. "isContainer" : false,
  34. "isNotContainer" : true,
  35. "isString" : false,
  36. "isNumeric" : true,
  37. "isInteger" : false,
  38. "isLong" : true,
  39. "isNumber" : false,
  40. "isFloat" : false,
  41. "isDouble" : false,
  42. "isByteArray" : false,
  43. "isBinary" : false,
  44. "isFile" : false,
  45. "isBoolean" : false,
  46. "isDate" : false,
  47. "isDateTime" : false,
  48. "isUuid" : false,
  49. "isEmail" : false,
  50. "isFreeFormObject" : false,
  51. "isListContainer" : false,
  52. "isMapContainer" : false,
  53. "isEnum" : false,
  54. "isReadOnly" : false,
  55. "isWriteOnly" : false,
  56. "isNullable" : false,
  57. "vendorExtensions" : { },
  58. "hasValidation" : false,
  59. "isInherited" : false,
  60. "nameInCamelCase" : "Id",
  61. "nameInSnakeCase" : "ID",
  62. "isXmlAttribute" : false,
  63. "isXmlWrapped" : false,
  64. "datatype" : "int64",
  65. "iexclusiveMaximum" : false
  66. }, {
  67. "baseName" : "name",
  68. "getter" : "getName",
  69. "setter" : "setName",
  70. "dataType" : "string",
  71. "datatypeWithEnum" : "string",
  72. "name" : "Name",
  73. "defaultValueWithParam" : " = data.name;",
  74. "baseType" : "string",
  75. "example" : "null",
  76. "jsonSchema" : "{\n \"type\" : \"string\"\n}",
  77. "exclusiveMinimum" : false,
  78. "exclusiveMaximum" : false,
  79. "hasMore" : true,
  80. "required" : true,
  81. "secondaryParam" : false,
  82. "hasMoreNonReadOnly" : true,
  83. "isPrimitiveType" : true,
  84. "isModel" : false,
  85. "isContainer" : false,
  86. "isNotContainer" : true,
  87. "isString" : true,
  88. "isNumeric" : false,
  89. "isInteger" : false,
  90. "isLong" : false,
  91. "isNumber" : false,
  92. "isFloat" : false,
  93. "isDouble" : false,
  94. "isByteArray" : false,
  95. "isBinary" : false,
  96. "isFile" : false,
  97. "isBoolean" : false,
  98. "isDate" : false,
  99. "isDateTime" : false,
  100. "isUuid" : false,
  101. "isEmail" : false,
  102. "isFreeFormObject" : false,
  103. "isListContainer" : false,
  104. "isMapContainer" : false,
  105. "isEnum" : false,
  106. "isReadOnly" : false,
  107. "isWriteOnly" : false,
  108. "isNullable" : false,
  109. "vendorExtensions" : { },
  110. "hasValidation" : false,
  111. "isInherited" : false,
  112. "nameInCamelCase" : "Name",
  113. "nameInSnakeCase" : "NAME",
  114. "isXmlAttribute" : false,
  115. "isXmlWrapped" : false,
  116. "datatype" : "string",
  117. "iexclusiveMaximum" : false
  118. }, {
  119. "baseName" : "tag",
  120. "getter" : "getTag",
  121. "setter" : "setTag",
  122. "dataType" : "string",
  123. "datatypeWithEnum" : "string",
  124. "name" : "Tag",
  125. "defaultValueWithParam" : " = data.tag;",
  126. "baseType" : "string",
  127. "example" : "null",
  128. "jsonSchema" : "{\n \"type\" : \"string\"\n}",
  129. "exclusiveMinimum" : false,
  130. "exclusiveMaximum" : false,
  131. "hasMore" : false,
  132. "required" : false,
  133. "secondaryParam" : false,
  134. "hasMoreNonReadOnly" : false,
  135. "isPrimitiveType" : true,
  136. "isModel" : false,
  137. "isContainer" : false,
  138. "isNotContainer" : true,
  139. "isString" : true,
  140. "isNumeric" : false,
  141. "isInteger" : false,
  142. "isLong" : false,
  143. "isNumber" : false,
  144. "isFloat" : false,
  145. "isDouble" : false,
  146. "isByteArray" : false,
  147. "isBinary" : false,
  148. "isFile" : false,
  149. "isBoolean" : false,
  150. "isDate" : false,
  151. "isDateTime" : false,
  152. "isUuid" : false,
  153. "isEmail" : false,
  154. "isFreeFormObject" : false,
  155. "isListContainer" : false,
  156. "isMapContainer" : false,
  157. "isEnum" : false,
  158. "isReadOnly" : false,
  159. "isWriteOnly" : false,
  160. "isNullable" : false,
  161. "vendorExtensions" : { },
  162. "hasValidation" : false,
  163. "isInherited" : false,
  164. "nameInCamelCase" : "Tag",
  165. "nameInSnakeCase" : "TAG",
  166. "isXmlAttribute" : false,
  167. "isXmlWrapped" : false,
  168. "datatype" : "string",
  169. "iexclusiveMaximum" : false
  170. } ],
  171. "requiredVars" : [ /* id, name */ ],
  172. "optionalVars" : [ /* tag */ ],
  173. "readOnlyVars" : [ ],
  174. "readWriteVars" : [ /* lists metadata for all three properties */ ],
  175. "allVars" : [ /* lists all properties */],
  176. "parentVars" : [ ],
  177. "mandatory" : [ "id", "name" ],
  178. "allMandatory" : [ "id", "name" ],
  179. "imports" : [ ],
  180. "hasVars" : true,
  181. "emptyVars" : false,
  182. "hasMoreModels" : false,
  183. "hasEnums" : false,
  184. "isEnum" : false,
  185. "hasRequired" : true,
  186. "hasOptional" : true,
  187. "isArrayModel" : false,
  188. "hasChildren" : false,
  189. "isMapModel" : false,
  190. "hasOnlyReadOnly" : false,
  191. "vendorExtensions" : { }
  192. }
  193. } ]

Templates are passed redundant properties, depending on the semantics of the array. For example:

  • vars lists all defined model properties
  • requiredVars lists all model properties marked with required in the spec document
  • optionalVars lists all model properties not marked with required in the spec document
  • readWriteVars lists all model properties not marked with readonly in the spec document
  • readOnlyVars lists all model properties marked with readonly in the spec document
  • allVars lists all model properties. This may include the same set as vars, but may also include generator-defined propertiesWe expose the same properties in multiple sets because this allows us to conditionally iterate over properties based on some condition ("is it required" or "is it readonly"). This is driven by the use of the logic-less Mustache templates. It is possible that models passed to the templating engine may be cleaned up as we support more template engines, but such an effort will go through a deprecation phase and would be communicated at runtime through log messages.

supportingFiles

Inspect supportingFiles passed to templates with system property -DdebugSupportingFiles

Execute:

  1. openapi-generator generate -g go \ -o out \ -i petstore-minimal.yaml \ -DdebugSupportingFiles

This is a "catch-all" which gives you the entire structure—operations, model, etc—so you can create "single-file" code from them.

Supporting files can either be processed through the templating engine or copied as-is. When creating your own templates, you're limited to the files and extensions expected by the generator implementation. For more control over the supporting files produced by a generator, see our customization documentation.

Variables

This is a very limited list of variable name explanations. Feel free to open a pull request to add to this documentation!

  • complexType: stores the name of the model (e.g. Pet)
  • isContainer: true if the parameter or property is an array or a map.
  • isPrimitiveType: true if the parameter or property type is a primitive type (e.g. string, integer, etc) as defined in the spec.

Mustache Lambdas

Many generators (those extending DefaultCodegen) come with a small set of lambda functions available under the key lambda:

  • lowercase - Converts all of the characters in this fragment to lower case using the rules of the ROOT locale.
  • uppercase - Converts all of the characters in this fragment to upper case using the rules of the ROOT locale.
  • titlecase - Converts text in a fragment to title case. For example once upon a time to Once Upon A Time.
  • camelcase - Converts text in a fragment to camelCase. For example Input-text to inputText.
  • indented - Prepends 4 spaces indention from second line of a fragment on. First line will be indented by Mustache.
  • indented_8 - Prepends 8 spaces indention from second line of a fragment on. First line will be indented by Mustache.
  • indented_12 - Prepends 12 spaces indention from second line of a fragment on. First line will be indented by Mustache.
  • indented_16 -Prepends 16 spaces indention from second line of a fragment on. First line will be indented by Mustache.Lambda is invoked by lambda.[lambda name] expression. For example: {{#lambda.lowercase}}FRAGMENT TO LOWERCASE{{/lambda.lowercase}} to lower case text between lambda.lowercase.

Extensions

OpenAPI supports a concept called "Extensions". These are called "Specification Extensions" in 3.x and "Vendor Extensions" in 2.0.You'll see them referred to as "Vendor Extensions" in most places in this project.

Vendor extensions allow you to provide vendor-specific configurations to your specification document.

For example, suppose you use your specification document for code generation with a (hypothetical) C# OpenAPI generator supporting a desired operationId prefix where the extension is x-csharp-operationid, you can define this property alongside the object you'd like to extend (which would be a Path Object in this case). You could then apply additional extensions alongside this property, whether they're for another language or other tooling.

Well-defined vendor extensions don't cause conflicts with other tooling.

The following are vendor extensions supported by OpenAPI Generator. The list may not be up-to-date, the best way is to look for "x-" in the built-in mustache templates.

All generators (core)

Enum

x-enum-varnames can be used to have an other enum name for the corresponding value.This is used to define names of the enum items.

x-enum-descriptions can be used to provide an individual description for each value.This is used for comments in the code (like javadoc if the target language is java).

x-enum-descriptions and x-enum-varnames are each expected to be list of items containing the same number of items as enum.The order of the items in the list matters: their position is used to group them together.

Example:

  1. WeatherType:
  2. type: integer
  3. format: int32
  4. enum:
  5. - 42
  6. - 18
  7. - 56
  8. x-enum-descriptions:
  9. - 'Blue sky'
  10. - 'Slightly overcast'
  11. - 'Take an umbrella with you'
  12. x-enum-varnames:
  13. - Sunny
  14. - Cloudy
  15. - Rainy

In the example for the integer value 42, the description will be Blue sky and the name of the enum item will be Sunny (some generators changes it to SUNNY to respect some coding convention).

ObjC

x-objc-operationId

To customize the method name, you can provide a different name in x-objc-operationId, e.g.

  1. summary: Add a new pet to the store
  2. description: ''
  3. operationId: addPet
  4. x-objc-operationId: CreateNewPet

Java (Feign)

x-accepts

A single Accepts value as the Feign API client needs a single value for Accepts header, e.g.

  1. consumes:
  2. - application/json
  3. - application/xml
  4. x-accepts: application/json

x-content-type

A single "Content-Type" value as the Feign API client needs a single value for Content-Type header, e.g.

  1. produces:
  2. - application/xml
  3. - application/json
  4. x-content-type: application/json

Rust-server

x-responseId

Each response may specify a unique x-responseId. rust-server will use this to name the corresponding enum variant in the code. e.g.

  1. paths:
  2. /ping:
  3. get:
  4. responses:
  5. 200:
  6. description: OK
  7. x-responseId: Pong

MySQL Schema

x-mysqlSchema

MySQL schema generator creates vendor extensions based on openapi dataType and dataFormat. When user defined extensions with same key already exists codegen accepts those as is. It means it won't validate properties or correct it for you. Every model in definitions can contain table related and column related extensions like in example below:

  1. definitions:
  2. Order:
  3. description: This should be most common InnoDB table
  4. type: object
  5. properties:
  6. id:
  7. description: >-
  8. This column should be unsigned BIGINT with AUTO_INCREMENT
  9. type: integer
  10. format: int64
  11. x-mysqlSchema:
  12. columnDefinition:
  13. colName: id
  14. colDataType: DECIMAL
  15. colDataTypeArguments:
  16. - argumentValue: 16
  17. isString: false
  18. hasMore: true
  19. - argumentValue: 4
  20. isString: false
  21. hasMore: false
  22. colUnsigned: true
  23. colNotNull: true
  24. colDefault:
  25. defaultValue: AUTO_INCREMENT
  26. isString: false
  27. isNumeric: false
  28. isKeyword: true
  29. colComment: >-
  30. Column comment. This column should be unsigned BIGINT with AUTO_INCREMENT
  31. x-mysqlSchema:
  32. tableDefinition:
  33. tblName: orders
  34. tblStorageEngine: InnoDB
  35. tblComment: >-
  36. Table comment. This should be most common InnoDB table

There are properties that are not implemented by now(tblStorageEngine), but you can see how generator can be enhanced in future.

Mustache Tips

Here are a few tips we've found useful for new template authors.For more details on Mustache see mustache.5. See also samskivert/jmustache for implementation-specific details.

First/Last

To access the first or last element in a list using Mustache:

  1. {{#vars}}{{#-first}} this is the first element {{.}} {{/-first}}{{/vars}}
  2. {{#vars}}{{#-last}} this is the last element {{.}} {{/-last}}{{/vars}}

This

Mustache evaluates template variables contextually. If the variable isn't found in the immediate object, mustache will search the parent. This is similar to JavaScript's prototype object (if you're familiar with the concept).

You can inspect this entire context by outputting {{this}}. For example:

  1. {{#operations}}{{this}}{{/operations}}

Index

If you'd like a 1-based index in your array traversal, you can use {{-index}}:

  1. {{#enums}}{{-index}} {{enum}}{{/enums}}