Swagger is an open source project used to generate the REST API documents for RESTful web services.
Add swagger and swagger-ui dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
Add Swagger Config class
@PropertySource("classpath:swagger.properties")
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Bean
public Docket api() {
log.info("setting up Docket..");
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.folaukaveinga"))
.paths(PathSelectors.any()).build().apiInfo(getApiInfo());
log.info("docket setup!");
return docket;
}
private ApiInfo getApiInfo() {
Contact contact = new Contact("Folau Kaveinga", "folaukaveinga.org", "folaukaveinga@gmail.com");
return new ApiInfoBuilder()
.title("Spring Data Tutorial")
.description("Spring Data API")
.version("1.0.0")
.contact(contact)
.build();
}
}
Anotate controller classes
- Anotate Controller class with @Api
- Anotate methods with @ApiOperation
- Use @ApiParam to describe parameters
@Api(value = "users", produces = "Rest API for User operations", tags = "User Controller")
@RestController
@RequestMapping("/users")
public class UserController {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserService userService;
@ApiOperation(value = "Get Member By Id")
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@ApiParam(name = "id", required = true, value = "id of member") @PathVariable("id") Long id) {
log.info("get user by id: {}", id);
return new ResponseEntity<>(userService.getById(id), HttpStatus.OK);
}
}
Source code on Github