Spring Boot Restful API Documentation With Swagger 2


APIs that you design are meant to be consumed by your probable clients or consumers. So, it becomes more important that they understand it quickly and put it into implementation. It is therefore essential to document your api. API documentation is a technical artifact where you learn about endpoints, authentication if any, parameters, what type of MIME-Types your endpoint consumes and produces, structure of the response, HTTP status code and many other useful information. Designing good quality restful api documentation not only helps other developers to integrate/consume it but also impacts the long-term success of an API.

Technologies Used

  • Spring Boot 2.1.2.RELEASE
  • Swagger 2
  • Maven 3.3
  • H2 In-Memory database
  • Eclipse Oxygen

What you will learn?

  • What is swagger and why use it?
  • CRUD Restful API development with spring boot + Swagger2

What is Swagger and why use it?

Swagger is a framework that allows you to describe the format/structure of your APIs. Based on some bunch of  annotations and configuration, Swagger generates YAML or JSON containing detailed description of your APIs. It automatically builds beautiful and interactive API documentation, with that you can visualize and test your APIs wihout writing the client code. This is the awesomeness of Swagger. With the help of Swagger-UI, you can visualize and interact with your API in your browser itself. We will use Swagger 2 specification for our project development.

Swagger Dependencies

Play with spring boot restful api documentation by visualizing it in your browser, just add a couple of swagger dependencies in your pom.xml and your are set to go.

Required Swagger Dependencies


CRUD Restful API development with spring boot + Swagger 2

Let’s start building the application straight away. We will build a crud restful api with spring boot and swagger. Here we will learn what are all the annotations needed to customize the swagger documentation and create a Docket Bean in our Spring Configuration class. Json is created as a part of Swagger documentation and with Swagger-UI, you can test your api in browser.

Bootstrap you application through SPRING INITIALIZR

Create your Spring-Boot project with the help of Spring Initializr. Provide the Project Metadata and Dependencies as shown below.

Click on the Generate Project button to download the project, extract it to any location and import in your favorite IDE. I am using Eclipse Oxygen for the same.

Standard Maven Project Structure

Following is the complete project structure that we will be developing step-by-step.

Pom.xml – Project Dependencies

@Entity class Account

Create Account.java which is an entity class with primary key accountId. The @Id annotation on accountId indicates the member field is the primary key of current entity. The @GeneratedValue annotation is to configure the way of increment of the specified column(field). In order to automatically generate all the boilerplate associated with our entity class, we have used Lombok. If you have noticed, we used Lombok dependecies for the same. @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together. @NoArgsConstructor will generate a constructor with no parameters. @AllArgsConstructor generates a constructor with 1 parameter for each field in your class.

Swagger Annotations used for Model Class – Account
Swagger Annotations for Model
@ApiModel : Use this annotation at class level to specify the metadata of a model i.e. to change the name of the model and add a description to it. This gets reflected in the Swagger Specification.

@ApiModel(value="Account", description="Resource on which different operations are performed.")

@ApiModelProperty : Use this to add a short description to the model property.

@ApiModelProperty(notes = "The database generated product ID")

Swagger Specification generated for Account

Database script file with insert scripts – data.sql

Create a database script file “data.sql” in “src/main/resources” folder with the following insert scripts that will be loaded in the In-Memory database table “Account” when the application is started.

Enable H2 Console

If you want to access the web-based H2 console in your browser, then enable the same in the following way in /src/main/resources/application.properties file.

# Enable web-based H2 Console

Now run the project “spring-boot-swagger2-demo” as Java Application and you will be able to access the H2 console in your browser with the following url. Remember to change the JDBC url to  jdbc:h2:mem:testdb.

H2 Console

Hit the “Connect” button and you will see the “Account” table already created. Run the select command to see the records for the insert scripts you kept in data.sql file.

JpaRepository – IAccountRepository

JpaRepository is the pre-defined core repository interface in Spring Data JPA enabling the basic CRUD functions on a repository. Create IAccountRepository interface extending from JpaRepository that will manage the Account entity with a primary key of type Integer.

Error Handling

We will handle errors specific to our application. Create a class called “ErrorConstants.java” where we will define some constants that we will use in our application.

Similarly create a class “ErrorResponse.java” that we will use to respond in case resource is not found or in case of failures in our application. This class is also annotated with swagger annotations used for model class.

Create a controller class that exposes resources to the web.

Now create AccountController class annotated with @RestController that will expose web methods so that we can consume it. These web methods are capable of handling different HTTP-Methods for performing CRUD operations. The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. This annotation maps HTTP requests to handler methods of MVC and REST controllers.

Swagger 2 Annotations for REST Endpoints – AccountController
Swagger Annotations for REST Endpoints
@Api : This is used to declare a swagger resource API along with the description of this resource.

@Api(value="AccountOperations", description="Contains operations related to Account")

@ApiOperation : It is used to declare the endpoint within an API resource. The value of the annotation is a short description on the endpoint and response is the return type of the method.

@ApiOperation(value = "Get account details on the basis of account ID",response = ResponseEntity.class)

@ApiResponses, @ApiResponse : The @ApiResponse describes possible response. It cannot be used directly on the method and needs to be included in the array value of @ApiResponses (whether there’s one response or more). code represents HTTP-STATUS code, message represents the short description.

@ApiResponses(value = {
  @ApiResponse(code = 200, message = "Successfully retrieved list"),
  @ApiResponse(code = 400, message = "Oops! Account you are looking for does not exist. Try with other Account ID"),
  @ApiResponse(code = 404, message = "The resource you were looling for is not found")

Spring Swagger Configuration – Docket Bean

We need to add few Spring configuration in order to generate Swagger Documentation. Define a Docket Bean which is the main bean used to configure SpringFox for creating the Swagger Docs. @EnableSwagger2 enables SpringFox support for Swagger 2.

Above configuration is described below briefly. Know more about the Docket bean here.

  • @Configuration: Represents Spring Configuration class used by the Spring IoC container as a source of bean definitions.
  • @EnableSwagger2: Enables supports for Swagger 2 documentation.
  • DocumentationType.SWAGGER_2: Specifies to the Docket bean about the version of Swagger Specification being used.
  • apiInfo(): Sets the meta information of the API like title, description, version, license, license url, default contact information etc.
  • select(): Returns a builder for api selection. Specifies which controllers and their handler methods to be included in the generated documentation.
  • apis(): Used to defines the classes (controller and model classes) to be included. Here we have specified basePackage for controller class.
  • paths(): Used to define which controller’s methods should be included based on their path mappings. PathSelectors.any() will make documentation for your entire API available through Swagger. You can even limit it using regex and more.

Use @SwaggerDefinition to expose meta API information like description, title, version, contact information, license, schemes etc. in generated Swagger Docs.

Spring Boot Application class

SpringBootSwagger2DemoApplication.java” acts as an entry point for our application. This class is responsible for creating in-memory tomcat container and deploying this application.

Generate Swagger Documentation for your API

You are now very close to generate a swagger documentation for your API. Just run the above “SpringBootSwagger2DemoApplication.java” as Java Application. Hit the following URL in order to get the api docs.

URL to get Swagger API Docs

Click Me to see the generated Swagger Api Docs.

Visualizing Your API With Swagger-UI

URL to get Swagger-UI

Expand the account-controller and Models

Test GET /account/api/showAllAccounts

I will be testing only one endpoint. Kindly you test it all while creating the project yourself. Click on “GET /account/api/showAllAccounts” to get all account details available.

Final Words

This is all about integrating swagger2 with spring boot application. As you see above, Swagger provides visual representation for your API and you can test your api then and there in your browser itself. I would be happy to assist you if you find any problem in the implementation, just tell me in the comment section below. Happy Koding…..Keep Learning.


Leave a Reply