Spring Boot

Spring boot Swagger 2 example

Developing a REST API is hard. 

Not only because of the effort required to design and implementation, but also the effort required for documentation so that the developers who are going to use it have a clear understanding.

Swagger is a framework that helps in the documentation of APIs.

Therefore, In this tutorial, we will see how to document and test our REST services with Swagger

What is Swagger?

If you are looking for a framework to document your API, swagger is what you are looking for.

Swagger is a framework to document and visualize Rest APIs from very different sources.

Swagger 2 demo
Visualize REST API using Swagger 2

Swagger supports many frameworks including Node.js, Grails, Scala Play, Spring Boot, Symfony.

Before starting a demo, let’s me tell you what environment I’m using here to create this tutorial

Environment Details

This demo is developed using the following environment:

Hardware: i7 8650U CPU with 16 GB of RAM
Operating System: Windows 10
IDE: Eclipse
Swagger 2
and Spring Boot

Add Swagger 2 Dependencies in Spring Boot

SpringFox is a popular implementation for Swagger 2 specification. SpringFox supports both Swagger 1.2 and 2.

Let’s add Springfox dependency in pom.xml to bring it in our project.

In addition to Springfox, we need to add the dependency for swagger-ui. Let’s add springfox-swagger-ui in the pom file

Final pom.xml

Create REST APIs

Let’s create a CRUD API’s for this demo.

For this tutorial, we will expose a few REST APIs for a car showroom.

POST /api/car/add is to add the car into the car inventory database.

GET /api/car/get/{carId} is to get car details from the inventory. To retrieve car details you have to provide car id.

PUT /api/car/update/{carId}/{price:.+} is to update car’s price. To update the price of the car you have to provide id and updated price of the car.

DELETE /api/car/delete/{carId} is to delete car detail from the inventory.

Steps to create REST APIs in spring boot.

1.) Create an Entity class to define the table structure.

2.) Create a controller class to create and expose the REST apis.

3.) Create a service class that will act as a bridge between dao (repository) and controller.

4.) A repository interface that will extends Spring Data JPA’s CrudRepository interface.

Entity Class (Car.java)

Controller Class (CarController.java)

As you could see in the controller class that we have exposed few APIs for adding a car, finding a car by ID, updating a car and deleting a car by ID.

Service Class (CarService.java)

The service class acts as a bridge between the repository and the controller.

Service class gets the save request from the controller and it passes the same save the request to the repository and returns the result.

Repository Interface (CarRepository.java)

Crudrepository is is the main interface in spring data jpa that allows us to write simple crud operations without writing a single line of code

How to handle Error’s for RESTful APIs

Error Handling in REST APIs

A good REST API’s implementation should have proper error handling.

As you could see our current implementation doesn’t have code logic to handle error requests.

But still, spring boot provides the proper message when an error occurred.

Let’s hit the wrong request to see what kind of error messages we are getting now.

GET localhost:8080/api/cars/get

The response of the above request would be:

REST API's error - 404
REST API’s error – 404

From the above response from the spring boot, it is clear that we got a 404 response that means the server unable to find the requested resource.

How to customize the error message

As we are trying to customize error response for 404 error, let’s start by writing a custom exception called ResourceNotFoundError.

As you could see ResourceNotFoundError is extending exception class and has one parameterized constructor.

Now let’s create ErrorDetail.java class and declare all the properties that we want to show in the custom error message.

As you could see above we have defined timestamp, errorMessage, and errorDetails properties which will be shown in the custom error message.

Now let’s create a main exception handler. we are annotating this class with @ControllerAdvice so that exception handling will be applied globally for all controller automatically.

In the MainExceptionHandler class, we have created two methods resourceNotFoundException and globleExcpetionHandler.

If you notice both methods are annotated with @ExceptionHandler.

@ExceptionHandler provides the mechanism to treat exceptions that are thrown during the execution of controller operations.

Configure Swagger 2 in Spring Boot Application.

We have already added Swagger 2 dependencies earlier.

Let’s configure Swagger 2 now.

To configure Swagger 2, we will create a Docket bean in a Configuration file.

The docket is a builder pattern provided in the springfox framework that creates an interface between swagger and spring framework.

In the below class we have enabled the Swagger 2 by using @EnableSwagger2.

In addition to that, we have also provided controller base package details, API’s base URL, license details, etc.

Now let’s run the application and hit http://localhost:9000/swagger-ui.html#/ URL.

swagger spring boot demo
Swagger Demo

Swagger has visualized our Car Controller API’s.

Let’s add a few annotations to the controller class to make this visualization more informative.

In the car controller and addCar method, I have added @Api, @ApiOperation, and @ApiResponse to make APIs documentation more informative.

Restart the application to see the updated result.

 Swagger Informative Documentation
Swagger Informative Documentation
Swagger Add api
Swagger Add api
Swagger Get Response
Swagger Get Response


In this tutorial, we have seen that how Swagger 2 can be used to visualize REST API’s using Spring boot, Swagger 2 and SpringFox.