JavaAPI Documentation in Spring with Swagger

API Documentation in Spring with Swagger

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Documenting an application is an essential point of any project that is often overlooked. When working as a team, poor documentation can make the work of other developers very hard.

Documenting APIs, in turn, is no different. Spring Boot, one of the most used frameworks in Java for API development, presents an easy way to integrate with Swagger.

From the official website definition: Swagger is a powerful yet easy-to-use suite of API developer tools for teams and individuals, enabling development across the entire API lifecycle, from design and documentation, to testing and deployment.

In this article, we’ll show you how to document a Spring Boot API with Swagger.

Project Setup

To make things simple and straightforward, we’re going to make use of Spring Initializr, a web tool that the Spring project provides to easily create a Spring project with your selected facets.

Be sure to match the settings displayed on the image below:

Creating a Spring Boot web application

Click the Generate button and download the zipped project file. Then, make sure to open the project folder within your favorite IDE. For this article, I’ll be using the IntelliJ IDEA CE, because it’s powerful and flexible.

Wait for the IDE to load all the Gradle dependencies and then open the build.gradle file. You may add the following dependency within the dependencies object:


implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'

This is the SpringFox dependency that will allow the autoconfiguration of Swagger to our Spring application.

We also need the following dependency to add Swagger UI capabilities, otherwise we won’t be able to check the web version of our docs:


implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'

That will import a bunch ofl Swagger annotations we’re going to use to set up Swagger to watch all of our REST endpoints. For this, create a new class called SwaggerConfig into the project’s main folder and add the following content to it:


package com.developer.springdocswagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

  @Bean
  public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build();
  }
}

Note that we’re explicitly adding the @EnableSwagger2 annotation in order to ask Swagger to autoconfigure itself within the Spring context.

The Docket object is basically a builder, which is intended to be the primary interface into the Springfox framework. It provides sensible defaults and convenient methods for auto-configuration.

Configuration test

This is pretty much the configs we need for Swagger. However, in order to test them, we also need some API endpoints within the Spring Boot application. Let’s create them.

First, create a new folder called controller and then a new class called User. You may add the following code into it:


package com.developer.springdocswagger.controller;

public class User {

  private int id;
  private String name;
  private double age;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public double getAge() {
    return age;
  }

  public void setAge(double age) {
    this.age = age;
  }
}

It’s a simple POJO to support the subsequent endpoints of our API. Go ahead and create a new class called UserController to which you may add the following content:

package com.developer.springdocswagger.controller;

import java.util.Collections;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

  @RequestMapping(value = "/users", method = RequestMethod.GET)
  public List getUsers() {
    return Collections.emptyList();
  }

  @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
  public ResponseEntity getById(@PathVariable(value = "id") int id) {
    return new ResponseEntity<>(new User(), HttpStatus.OK);
  }

  @RequestMapping(value = "/users", method = RequestMethod.POST)
  public ResponseEntity addUser(@Validated @RequestBody User user) {
    return new ResponseEntity<>(new User(), HttpStatus.CREATED);
  }

  @RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
  public ResponseEntity updateUser(@PathVariable(value = "id") int id, @Validated @RequestBody User newUser) {
    return new ResponseEntity<>(newUser, HttpStatus.NO_CONTENT);
  }

  @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
  public ResponseEntitydeleteUser(@PathVariable(value = "id") int id) {
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
  }
}

We’re creating a very basic API controller here, making sure to create one method for each of the usual CRUD operations, as well as the right HTTP verbs and response codes.

Now let’s start the project on IntelliJ. Watch out for the logs to check if anything went wrong.

When the application is up, the Swagger UI endpoint is available at http://localhost:8080/swagger-ui.html/.

When you access it, you may see the following screen:

The Swagger API documentation page

Go ahead and open the controllers to explore them. Under the user-controller tab, you will find all the relevant CRUD endpoint operations, as well as the ability to test them out, as shown below:

Testing the GET users endpoint

Conclusion

This is just a quick demonstration of how you can quickly have your Swagger set up and running within a Spring Boot application. However, Swagger offers integration for pretty much any tech stack and framework you may be using.

There are also some other customizations available at the core of Swagger that are very much recommended. Good luck with your docs!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories