Skip to content

Building your own Templates

wing328 edited this page Oct 1, 2015 · 2 revisions

It's easy to build new templates for codegen! Here are a few steps you should follow to do so.

First off, the codegen project has transforming logic as well as templates for each generation of code. The transforming logic lives here:

https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages

Each template does a few things, namely generate a data structure from the swagger specification (note: the codegen project will transform previous versions of the swagger spec into a 2.0 specification before performing the transformation. See the Swagger-Parser project for details). While you do not necessarily need to perform transformations, it's likely necessary, or every programming language would have roughly the same syntax.

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.

Aside from transforming, the implementing class gets to decide "what to do" with the data structure. Namely, which data structures to apply to which template files. You have the following at your disposal:

  1. Operations. There is a data structure which represents all the operations that are defined in the swagger specification. A single 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:

// process the `api.mustache` template and output a single file with suffix `.java`:
apiTemplateFiles.put("api.mustache", ".java");
// create a header and implementation for each operation group:
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-body.mustache", ".m");
  1. Models. 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.

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