Swagger Integration With Spring Boot

Swagger is a very popular service documentation tool. We can use this to generate robust service documentation with very minimal configuration. This is very useful when we need to share our APIs with others for integration.

In this article, we will learn about how to configure swagger on our spring boot application and also learn how to customize it according to our requirements.

We will create a JPA RESTful CRUD service for the Student entity. We will also use the H2 database to store the Student entity details. Finally, we will use the Spring Data JPA library to perform the CRUD operations.

Add the Maven dependencies

Create a new Spring Boot application and add spring-boot-starter-web, lombok(To reduce boilerplate code), spring-boot-starter-data-jpa, and h2 dependencies.

The next step is to add the Maven dependencies for swagger and swagger-ui libraries. Also, add the mentioned dependencies to the spring boot application’s pom.xml file.


This will add the required swagger java libraries into our application’s classpath.

Configure the Swagger

The next step is to set up the swagger by creating a swagger configuration class.

Create a class called SwaggerConfiguration.java and define the required beans.


package com.asb.example;

import java.time.LocalDate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

public class SwaggerConfiguration {
    public Docket asbApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .directModelSubstitute(LocalDate.class, String.class)
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .description("Student Service List")
                .title("Student Service")
                .license("ASB Notebook")
    public Contact contact() {
        return new Contact("Arun", "http://asbnotebook.com", "asbnotebook@gmail.com");

We have used @EnableSwagger2 annotation to enable swagger documentation in our application.

We have defined a Docket bean, which is a builder for swagger configuration. It provides different configuration options that can be used to set up the swagger documentation.

We have added some basic setup like API packages, API info details, etc. There are a lot of other options available, that can be used to customize the swagger documentation configuration.

We have also defined ApiInfo and Contact beans to setup information like API license details, contact details, etc.

Create required classes and configuration for JPA CRUD operation

As we are going to create a JPA CRUD operation to demonstrate this swagger integration example, we need to create required classes, interfaces, and configuration.

Setup H2 database configurations

Add the mentioned yml configuration details into application.yml(we can use application.properties file instead) file of the application.

    url: jdbc:h2:~/asbdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    data-username: sa
    data: classpath:/data.sql
      enabled: true
      path: /h2-db-console
        trace: true

Create a data.sql file under the src/main/resources/ directory, to create the required Student table on the H2 database on application startup.



Create a Student Entity class

Now, create a Student entity class. We are going to perform the CRUD operations using JPA.

package com.asb.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

@ApiModel(description="Student Model class",value="Student Model")
public class Student {

    @ApiModelProperty(dataType="Long", required=true, name="Student Id", value="1")
    private Long studntId;
    @ApiModelProperty(dataType="String", required=true, name="Student Name", value="Arun")
    private String name;
    @ApiModelProperty(dataType="String", required=true, name="Grade", value="XI")
    private String grade;

Swagger supports Model-level annotations, which we can see from the above Student.java class.


This class level annotation indicates that this class should be considered as API model type. This annotation also indicates that the class is used as the API request/response parameter in API operations.


This is a field-level swagger configuration annotation. We can also use this annotation to set the default value, datatype should be shown on the swagger document, etc.

Finally, the below image shows the result of our above swagger configuration.

swagger api model property example

Create a Student Repository interface

Create a StudentRepository interface as shown below. Since we are extending the JpaRepository interface, we get all the required CRUD functionalities out of the box.

package com.asb.example.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.asb.example.model.Student;

public interface StudentRepository extends JpaRepository<Student, Long> {

Create a service class

Create a StudentService class to implement the service layer.

package com.asb.example.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.asb.example.model.Student;
import com.asb.example.repository.StudentRepository;

public class StudentService {
    private StudentRepository studentRepository;
    public List<Student> getAllStudents(){
        return studentRepository.findAll();
    public Student saveStudent(Student student){
        return studentRepository.save(student);
    public Student updateStudent(Student student){
        return studentRepository.save(student);
    public Student deleteStudent(Long studentId){
        Student student = studentRepository.getOne(studentId);
        return student;

If you need more details about the JPA CRUD operation, check out this article.

Configuring Swagger for REST end points

We have configured API Model with swagger before. Now it is the major part of the swagger configuration. Since we are creating documentation for REST endpoints, we need to create a Restful controller layer and configure them with swagger annotations.

Set up swagger configuration messages

Update the application.yml file by adding these configuration properties. We are adding a few swagger messages to the configuration file(application.yml) and also setting the application context path to the path /students.

    context-path: /students
    findStudents: Find All Studen Details.
    saveStudent: Save Student Details.
    updateStudent: Update Student Details.
    deleteStudentById: Delete Student Details by ID.

Create a RestController class

Next, we will create a REST controller and add CRUD operation endpoints.

Create the StudentController java class and add the below content.

package com.asb.example.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.asb.example.model.Student;
import com.asb.example.service.StudentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

public class StudentController {

    private StudentService studentService;

    @ApiOperation(value = "Find Students", notes = "${StudentController.findStudents}")
    public ResponseEntity<List<Student>> getAllStudents() {
        return new ResponseEntity<>(studentService.getAllStudents(), HttpStatus.OK);

    @ApiOperation(value = "Save Student", notes = "${StudentController.saveStudent}")
    public ResponseEntity<Student> saveStudent(
            @ApiParam(name = "Save Student", value = "Student Details to be saved", required = true) @RequestBody Student student) {
        return new ResponseEntity<>(studentService.saveStudent(student), HttpStatus.CREATED);

    @ApiOperation(value = "Update Students", notes = "${StudentController.updateStudents}")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully Saved"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden"),
            @ApiResponse(code = 404, message = "The resource is not found") })
    public ResponseEntity<Student> updateStudent(
            @ApiParam(name = "Update Student", value = "Student Details to be updated", required = true) @RequestBody Student student) {
        return new ResponseEntity<>(studentService.updateStudent(student), HttpStatus.CREATED);

    @ApiOperation(value = "Delete Student By ID", notes = "${StudentController.deleteStudentById}")
    public ResponseEntity<Student> deleteStudent(
            @ApiParam(name = "Delete Student", value = "Id of Student to be deleted", required = true) @PathVariable(name = "student-id") Long studentId) {
        return new ResponseEntity<>(studentService.deleteStudent(studentId), HttpStatus.OK);

Here, we have used a few of the swagger configuration annotations. We will discuss the usage of them one by one.


This annotation can be used to describe a particular endpoint’s operation. We have set the value and notes fields of the API. Notice that we are reading the notes field values from the application.yml configuration file.

This is also reflected in the swagger documentation as shown in the below image.

swagger ui api operation example


This annotation can be used to define the required API parameters of a particular API endpoint.

We can also set the name, value, and other supported parameters.

Finally, the below image shows the result of our swagger API param configuration.

swagger ui api param example


We can specify expected response details for a particular API by using this annotation.

We can also pass multiple @ApiResponse annotations as a value field as shown in the above example.

Also, the below image shows the generated swagger documentation for the above configuration.

swagger ui api response example

Testing the application

Run the spring boot application. Visit the given URL in the image.

spring boot swagger

We can also test the application endpoints by clicking on the Try it out button.

swagger example

Enter the student details and click on the Execute button.

spring boot swagger

Finally, we can see the student details saved successfully in the response.

spring boot swagger

Congratulations! We have successfully configured Swagger documentation for our Spring boot application.


In this article, we learned how to configure swagger for spring boot applications.

We also learned about different API operation-level and API model-level annotations.

Finally, we learned how to use Swagger UI to test the endpoints.

Also, the complete working code is available on GitHub.

Swagger Integration With Spring Boot
Scroll to top

Discover more from ASB Notebook

Subscribe now to keep reading and get access to the full archive.

Continue reading