Search code examples
mavenswaggerswagger-uiswagger-2.0swagger-maven-plugin

How to set overriding models in swagger-maven-plugin 3.1.0


How to set overriding models in swagger-maven-plugin 3.1.0 and Swagger UI 2.0 (or newer versions)?

Recently we've upgraded Swagger UI from 1.2 to 2.0 and swagger-maven-plugin from 2.3 to 3.1.0.

It appears, that swagger-maven-plugin version 3.1.0 is missing the overridingModels option, that was present in version 2.3.

The option enabled us to customize schema description for certain data types, as described in: https://github.com/swagger-api/swagger-core/wiki/overriding-models.


Solution

  • Here is how I eventually solved the problem (I'm using swagger-maven-plugin version 3.1.1):

    Let's assume you want to map java.util.Date as this arbitrary structure:

    {
      "year": "string",
      "month": "string",
      "day": "string"
    }
    

    Step 1: Create a class describing the above model:

    package com.example;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    
    @ApiModel
    public class MyDate {
    
        @ApiModelProperty
        public String year;
    
        @ApiModelProperty
        public String month;
    
        @ApiModelProperty
        public String day;
    }
    

    Note: The class name and the package name are arbitrary, they just need to be on the classpath, so the class is visible to the plugin like the rest of your model.

    Step 2: In the pom.xml add this line to the configuration of the swagger-maven-plugin:

    <plugin>
      <groupId>com.github.kongchen</groupId>
      <artifactId>swagger-maven-plugin</artifactId>
      <version>3.1.1</version>
      <configuration>
        <apiSources>
          <apiSource>
            ...
            <modelSubstitute>/model-substitute.csv</modelSubstitute>
          </apiSource>
        </apiSources>
      </configuration>
      ...
    </plugin>
    

    Step 3: Create a file model-substitute.csv with the following mapping:

    java.util.Date : com.example.MyDate
    

    Put the file in the same maven module as the plugin, in directory src/main/resources.
    Note: The name of the file is arbitrary, but it should match the value in the pom.xml.