Swagger Codegen use existing class

Derrops picture Derrops · Jun 18, 2017 · Viewed 9.8k times · Source

How can I get the swagger codegen to use an existing class instead of creating a new class? Is this possible? For instance I want to use org.springframework.data.domain.Page instead of swagger creating another page class.

Answer

moondaisy picture moondaisy · Jun 18, 2017

You could use --import-mappings, as it is explained here:

Sometimes you don't want a model generated. In this case, you can simply specify an import mapping to tell the codegen what not to create. When doing this, every location that references a specific model will refer back to your classes.

You call this on swagger-codegen-cli generate, with the example you included it would be

--import-mappings Page=org.springframework.data.domain.Page

Although importMappings hasn't been included in the general configuration parameters here if you look at the code here you can see it's a List<String>. I haven't used it with the maven plugin but looking at the doc and the code I'm guessing this should work:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.2-SNAPSHOT</version>
    <executions>
        <execution>
            ...
            <configuration>
                ...
                <importMappings>
                   <importMapping>Page=org.springframework.data.domain.Page</importMapping>
                </importMappings>
            </configuration>
        </execution>
    </executions>
</plugin> 

But this was recently changed, so it might be different if you're using an older version of the plugin. Before that changed it seems to be like this:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.2-SNAPSHOT</version>
    <executions>
        <execution>
            ...
            <configuration>
                ...
                <configOptions>
                   <import-mappings>Page=org.springframework.data.domain.Page;Some=org.example.Some</import-mappings>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

According to the comment in that commit the old version should be supported too, but I haven't tried any of this so let me know if it works.