Swagger is a really awesome project that will allow you to document and interact with your API within an HTML5 webpage. The following screenshot illustrates the API documentation:
Swagger used to be big (written in Scala) and somewhat complicated to configure with a Spring setup. Since version 2.0, the library has been rewritten and a really neat project called spring-fox
will allow for easy integration.
Add the following dependencies to your build file:
compile 'io.springfox:springfox-swagger2:2.1.2' compile 'io.springfox:springfox-swagger-ui:2.1.2'
The first one will provide an annotation to enable Swagger in your application as well as an API to describe your resources with annotations. Swagger will then generate a JSON representation of your API.
The second is a WebJar that contains static resources consuming the generated JSON through a web client.
The only thing you need to do now is add the @EnableSwagger2
annotation to your WebConfiguration
class:
@Configuration
@EnableSwagger2
public class WebConfiguration extends WebMvcConfigurerAdapter {
}
The swagger-ui.jar
file we just added contains an HTML file in META-INF/resources
.
It will automatically be served by Spring Boot when you go to http://localhost:8080/swagger-ui.html
.
By default, Springfox will scan your whole classpath and show all the request mappings declared in your application.
In our case, we only want to expose the API:
@Bean public Docket userApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .paths(path -> path.startsWith("/api/")) .build(); }
Springfox works with groups of Docket
s that you have to define as beans in your configuration classes. They are logical grouping for RESTful resources. An application can have many of them.
Have a look at the documentation (http://springfox.github.io/springfox) to see all the different setups available.