palkarrohan
palkarrohan

Reputation: 499

Can I define new mustache template variables in swagger-codegen?

I have developed a rest-api client (in java) customised to the needs of my product. I wanted to generate tests using my rest api client using swagger-codegen modules based on yaml-file.

I have already extended DefaultCodegenConfig & even tried implementing the CodegenConfig interface to build my custom jar. I have customized the api.mustache and api_test.mustache files and passing them in the constructor and processOpts() method of my CustomCodeGen that extends DefaultCodegenConfig.

However, I want to use the custom/new mustache template variables that I have added in my customised api.mustache.

For e.g. if refer to standard api.mustache, the template variables it typically uses are

 - {{classname}} 
 - {{#operation}} 
 - {{#contents}} 
 - {{#parameters}} 

etc.

Now, I want to introduce a new template variable, let's say {{custom_param}}. Now I am not clear how do I integrate this new template variable with the implementation.

Looks like from this Mustache-Template-Variables published here, swagger-codegen does not allow adding new template-variables and perhaps we are restricted to only the variables mentioned on this page.

So, is there some way to make the new template variables work ?

Upvotes: 3

Views: 2978

Answers (2)

Oleksandr Tsurika
Oleksandr Tsurika

Reputation: 980

The class DefaultCodegen contains a field additionalProperties and that is a map of additional properties that can be referenced by the mustache templates. So for example in maven project you may add custom template variables userAgent and userOs as following:

<plugin>
  <groupId>io.swagger.codegen.v3</groupId>
  <artifactId>swagger-codegen-maven-plugin</artifactId>
  <version>3.0.35</version>
  <executions>
    <execution>
      <goals>
         <goal>generate</goal>
      </goals>
      <configuration>
      ...
        <additionalProperties>userAgent=Postman,userOs=FreeBSD</additionalProperties>
      ...

And in any swagger codegen mustache template (eg., api.mustache) these new variables will be available using syntax {{userAgent}} and {{userOs}}

Upvotes: 0

Akshay
Akshay

Reputation: 198

Some time ago I added the uniqueItems parameter for bean validation as it was not getting processed by the engine even though it was a part of the implemented JSR.

So I believe codebase needs to be updated to use your own variable which is only possible if you fork the code.

In case it helps, these two were the PRs:

  1. For query parameters: https://github.com/swagger-api/swagger-codegen/pull/10154.
  2. For body parameters: https://github.com/swagger-api/swagger-codegen/pull/10490.

Upvotes: 1

Related Questions