Document an API with Swagger ☕

When creating a web API, good documentation is important for people to learn about your API, and how to use it without any headaches! Swagger provides a specification that generates documentation dynamically based on your code, and allows you to test it in the browser.

I will use it with Spring Boot and Springfox. Springfox allows you to use the spring data repositories as the basis for your documentation, which is important because with Spring Data REST, it is optional to create Controllers and this is usually the basis of the documentation.

Choose a project

If you already have a suitable project, use it. If not, you can grab my Library example.

Maven Dependencies

You need to include these 3 dependencies to include the Swagger and the UI for displaying the documentation.

XML
        <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>2.8.0</version>
</dependency>

Configure your project

You just need to add a few annotations in your application class like below.

Java
@SpringBootApplication
@EnableSwagger2
@Import(SpringDataRestConfiguration.class)
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
}

The Output

When you run Spring Boot, you should be able to view the Swagger documentation of your Spring Data REST API by accessing http://localhost:8080/swagger-ui.html in your browser. The result should look something like the image below.

swagger ui

Customize Documentation

You can customize each aspect of what appears in the UI. You can some methods
to your LibraryApplication.

Customize Resources

You use the Docket bean for configuration.

We would like to control the resources (endpoints) shown in the documentation. We do this by:

  1. Defining a Docket bean.
  2. Use select() to get an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.
  3. You can restrict what Swagger displays by passing parameters to apis() and paths(). I wanted to restrict by the URL, with paths(), you can do this by only including the repositories that are available by a pattern such as “/api/.*”, this then excludes the basic-error-controller and home-controller .

swagger ui

Java
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(regex("/api/.*"))
.build();
}

Customize Metadata

To change the metadata that goes on the top of the API page, you use Docket.apiInfo(ApiInfo apiInfo).

swagger ui

Java
//configure what Swagger will be interested in when creating documentation
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(regex("/api/.*"))
.build();
}

//create api metadata that goes at the top of the generated page
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Rob's Library")
.description("Library application to show Spring Data Rest and Swagger.")
.contact(new Contact("Rob OLeary", "http://roboleary.design", ""))
.license("Apache License Version 2.0")
.version("1.0")
.build();
}

Embed in our own page

I wanted to have the contents from swagger UI in the body of my own page.

Download (or clone) the Swagger UI repository. You’ll need the following files from the dist folder:

swagger-ui.css
swagger-ui-bundle.js
swagger-ui-standalone-preset.js

In the <head> section of your web page, add:

<link rel="stylesheet" type="text/css" href="swagger-ui.css">

Inside the <body>, write the code below. The url parameter is pointed to where Swagger generates the JSON of your API, I supply a relative path here.

HTML
<script src="js/swagger-ui-bundle.js"></script>
<script src="js/swagger-ui-standalone-preset.js"></script>

<script>
window.onload = function() {
const ui = SwaggerUIBundle({
url: "/v2/api-docs",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
docExpansion: true
})

window.ui = ui;
}
</script>

If you want to customize the display, you can provide parameters to SwaggerUIBundle, the list is here.

This is the result for my World Cup website. It doesn’t look perfect, but it works well.

swagger ui

Source code

This version of the Libary example had Swagger UI added.

References

Tagged