Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate OAS yaml file from sources annotations using swagger 3.x?

I've spend hours on searching how to generate the OAS spec yaml file using swagger codegen in Java and I give up. I'd like to provide all API spec data within the Java source as a code annotations. It would be great to expose it via maven.

AFAIK I should use swagger-codegen-maven-plugin, but I wasn't able to make it scan the source code to generate OAS yaml or JSON file.

I would appreciate a snippet of pom.xml with valid codegen plugin config.

Perhaps I should get back to the previous Swagger as this use case was handled straight forward in 2.x. Now i get frustrated of 3.x approach.

like image 860
Jakub Bejnarowicz Avatar asked Dec 06 '25 05:12

Jakub Bejnarowicz


1 Answers

Swagger Codegen generates code from an OpenAPI file. To do the opposite – generate an OpenAPI file from Java code annotations – you need Swagger Core e.g. its Maven plugin, swagger-maven-plugin.

Add following dependencies to your pom.xml:

<dependencies>
    <dependency>
        <groupId>io.swagger.core.v3</groupId>
        <artifactId>swagger-jaxrs2</artifactId>
        <version>2.0.9</version>
    </dependency>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
</dependencies>

Then utilise it in your build; example config:

   <plugins>
       <plugin>
           <groupId>io.swagger.core.v3</groupId>
           <artifactId>swagger-maven-plugin</artifactId>
           <version>2.0.9</version>
           <configuration>
               <outputFileName>openapi</outputFileName>
               <outputPath>${project.build.directory}/generatedtest</outputPath>
               <configurationFilePath>${project.basedir}/src/main/resources/configurationFile.yaml</configurationFilePath>
           </configuration>
           <executions>
               <execution>
                   <phase>compile</phase>
                   <goals>
                       <goal>resolve</goal>
                   </goals>
               </execution>
           </executions>
       </plugin>
   </plugins>
like image 111
Helen Avatar answered Dec 09 '25 20:12

Helen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!