Skip to content

Swagger2 with Spring Boot

Furkan Kürşat Danışmaz edited this page Jan 3, 2019 · 4 revisions

Problems Solved

  • REST API documentation.

Swagger Configuration in a Spring Boot App

Adding Dependencies

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox-swagger2.version}</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox-swagger2.version}</version>
</dependency>

Docket Bean Configuration

@Bean
public Docket producApi() {
    Docket productApi = new Docket(DocumentationType.SWAGGER_2)
				.select()
				.apis(RequestHandlerSelectors.basePackage(this.swaggerDocumentationBase))
				.paths(regex(this.swaggerApiBase))
				.build();

    if (this.swaggerApiInfoEnabled) {
        productApi = productApi.apiInfo(this.metaInfo());
    }

    return productApi;
}

@Bean
public ApiInfo metaInfo() {
    return new ApiInfo(
        this.title,
	this.description,
	this.version,
	this.termsOfServiceUrl,
	new Contact(this.contactName, this.contactUrl, this.contactEmail),
            this.licenseName,
            this.licenseUrl, Collections.emptyList());
}
swagger.doc.base=com.myapp.myapi
swagger.api.base=/.*
swagger.api.info.enabled=false
swagger.api.info.title=...
swagger.api.info.description"=...
swagger.api.info.version=...
swagger.api.info.terms_of_service_url=...
swagger.api.info.contact.name=...
swagger.api.info.contact.url=...
swagger.api.info.contact.email=...
swagger.api.info.license.name=...
swagger.api.info.license.url=...

Enrich Default Documentation

Other than configuring the swagger, you don't need to do anything else for your API documentation to be created. However, you can enrich it if you want to with swagger annotations:

  • @ApiOperation
  • @ApiResponses
  • @ApiParam
  • @ApiModelProperty
@RestController
@RequestMapping("/ticket")
@Api("Ticket Resources REST Endpoints")
public class TicketController extends RestApiController {
 
 
    @ApiOperation(value = "Get the list of the tickets related to a specific customer",
        response = RestApiResponseBody.class)
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully retrieved ticket list"),
        @ApiResponse(code = 401, message = "You are not authorized to view the resources"),
        @ApiResponse(code = 404, message = "Not found")
    })
    @GetMapping("/{customerId}")
    public ResponseEntity<Resources<Ticket>> list(
        @ApiParam(value = "The ID of the customer", type = "int", defaultValue = "0", example = "1", required = true)
        @PathVariable int customerId) {
        ...
    }
  
    ...
}
@Data
public class Ticket {
    @ApiModelProperty(notes = "The title of the ticket")
    private String title;
    ...
}