Maven How To Generate Swagger Documents

Do you like this?

Summary:
This article shows you how to generate Swagger static documents such as HTML from Maven.


Content:

The end result of this is to be able to run a command like:

mvn exec:exec -Pdoc
To do this you need to have swagger dependencies in your pom.xml

<dependency>
	<groupId>com.mangofactory</groupId>
	<artifactId>swagger-springmvc</artifactId>
	<version>${swagger.version}</version>
</dependency>

<dependency>
	<groupId>com.wordnik</groupId>
	<artifactId>swagger-codegen</artifactId>
	<version>${swagger_codegen.version}</version>
</dependency>

<profiles>
	<profile>
		<id>doc</id>
		<build>
			<plugins>
				<plugin>
					<groupId>org.codehaus.mojo</groupId>
					<artifactId>exec-maven-plugin</artifactId>
					<version>${exec-maven-plugin.version}</version>
					<executions>
						<execution>
							<goals>
								<goal>java</goal>
							</goals>
						</execution>
					</executions>
					<dependencies>

					</dependencies>
					<configuration>
						<executable>java</executable>
						<arguments>
							<argument>-classpath</argument>
							<classpath />
							<argument>com.wordnik.swagger.codegen.Codegen</argument>
							<argument>generate</argument>
							<argument>-i</argument>
							<argument>http://localhost:8080/your_app/api-docs</argument>
							<argument>-l</argument>
							<argument>html</argument>
							<argument>-o</argument>
							<argument>docs/html</argument>
						</arguments>
					</configuration>
				</plugin>
			</plugins>
		</build>
	</profile>
</profiles>
Please make sure you change the URL to your swagger json document. You will also need to put Swagger style documentation in your java code. Below is an example.
@RestController
@RequestMapping(value = "/users")
@Api(value = "User", description = "User API")
public class UserController {

    @RequestMapping(method = RequestMethod.POST)
    @ApiOperation(value = "create a new user", produces = "application/json",
                        response = User.class)
    @ApiResponses(value = {
            @ApiResponse(code = 201, message = "success", response = User.class)
    })
    public ResponseEntity createFittingStation(
            @RequestBody 
			@ApiParam(value = "user", required = true) final UserDTO user) {
        return new ResponseEntity(userService.createUser(user), HttpStatus.CREATED);

    }
}

@ApiModel
public class User {

    @NotNull
    private Long id;

    @ApiModelProperty(required = true)
    @NotEmpty
    private String firstName;

    @ApiModelProperty(required = true)
    @NotEmpty
    private String lastName;
	
}

 
comments powered by Disqus