Open In App

Generate Swagger UI for Spring Boot REST APIs

Last Updated : 03 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

REST (Representational State Transfer) is an architectural style that uses HTTP methods. Swagger is a framework in which we can test our REST APIs for different HTTP requests, like:

  • GET: It is used to read data
  • POST: It is used to create data
  • PUT: It is used to update data
  • DELETE: It is used to remove data

In this article, we will be discussing generating Swagger UI for Spring Boot REST APIs.

What is Swagger?

Swagger is an open-source API Documentation framework used for documenting REST APIs. It provides the HTML view of the API documentation with JSON support and detailed information on the HTTP methods. REST APIs are designed to be used in some kinds of applications.

Steps to Generate Swagger UI in Spring Boot

Step 1: Maven Project:

Spring
output
  • Extract the project and open with VS Code (Or any IDE you prefer), you can see a similar project structure (as shown below)
Spring
output
  • Now, open a terminal and run using the below command:

mvn-install

  • To install the dependency and then run follow the below command:

mvn spring-boot:run

Now start the application:

Spring
output


Step 2: Create a model class:

Now let’s create a controller class which handles the HTTP request and return a response.

  • Create a controller class(model class) that will be sent as a JSON response.

Tweet.java

Java
package xyz.bijit.swagger;
public class Tweet {

    // Unique identifier for the tweet
    private Integer id;

    // Title or headline of the tweet
    private String title;

    // Content/message of the tweet
    private String msg;

    // Getter method for tweet ID
    public Integer getId() { return id; }

    // Setter method for tweet ID
    public void setId(Integer id) { this.id = id; }

    // Getter method for tweet title
    public String getTitle() { return title; }

    // Setter method for tweet title
    public void setTitle(String title)
    {
        this.title = title;
    }

    // Getter method for tweet message/content
    public String getMsg() { return msg; }

    // Setter method for tweet message/content
    public void setMsg(String msg) { this.msg = msg; }
}

Explanation of the code:

  • Model Class represents a tweet with id, title, and msg fields.
  • Encapsulation uses private fields with public getters/setters.
  • JSON Binding is used for JSON input/output in REST APIs.
  • Swagger Integration  Auto-documented in Swagger UI.
  • Reusable DTO  Acts as a data transfer object across layers.
  • Spring Compatible. Easily serialized by Spring Boot using Jackson.

Step 3: Create Service class: Now create a service class to perform addTweet and getTweet.

Java
package xyz.bijit.swagger;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

@Service // Marks this class as a Spring service component
         // (auto-detected by component scanning)
         public class TweetService {

    // In-memory list to store tweet objects
    private List<Tweet> tweetList = new ArrayList<>();

    public void addTweet()
    {
        // First dummy tweet
        Tweet tweet = new Tweet();
        tweet.setId(1);
        tweet.setTitle("My first tweet");
        tweet.setMsg(
            "This is a dummy tweet for demonstration purposes.");
        tweetList.add(tweet); // Add to list

        // Second dummy tweet
        Tweet tweet2 = new Tweet();
        tweet2.setId(2);
        tweet2.setTitle("My second tweet");
        tweet2.setMsg(
            "This is the second dummy tweet for demonstration purposes.");
        tweetList.add(tweet2); // Add to list
    }

    /**
     * Returns the list of all tweets.
     * @return List of Tweet objects
     */
    public List<Tweet> getTweets() { return tweetList; }
}

Explanation of the code:

  • @Service Annotation Marks the class as a Spring-managed service component.
  • In-Memory List tweetList stores tweets without a database.
  • addTweet() Method: Adds two hardcoded dummy tweets.
  • Tweet Object Creation uses setters to set properties for each Tweet.
  • getTweets() Method Returns the full list of tweets.
  • Used in the Controller, called by REST endpoints to manage data.

Step 4: Create RestController Class. This class is used to define end-point

Java
package xyz.bijit.swagger;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

// Marks this class as a REST controller that can handle
// HTTP requests
@RestController
public class TweetController {

    // Injects the TweetService bean to use its business
    // logic methods
    @Autowired private TweetService tweetService;

    // Handles HTTP POST requests to /add and adds a tweet
    // using TweetService
    @PostMapping("/add") public void addTweet()
    {
        tweetService.addTweet(); // Delegates to the service
                                 // to add a sample tweet
    }

    // Handles HTTP GET requests to /view and returns the
    // list of tweets
    @GetMapping("/view") public List<Tweet> viewTweets()
    {
        return tweetService
            .getTweets(); // Delegates to the service to
                          // retrieve tweets
    }

    // Handles HTTP GET requests to /hello and returns a
    // simple greeting message
    @GetMapping("/hello") public String hello()
    {
        return "Hello World!"; // Returns a static string
    }
}

Explanation of the code:

  • @RestController marks the class as a REST API controller.
  • The @Autowired annotation Injects TweetService to use its methods.
  • @PostMapping("/add") adds dummy tweets when /add is called.
  • @GetMapping("/view") returns a list of tweets at /view.
  • TweetService holds logic to create and return tweets using an in-memory list.
  • Tweet class: A simple model (POJO) with id, title, and msg fields.

Step 5: Run the application: Run application and type this URL in your browser:

http://localhost:8080/view

output:

Spring
output

Setting up Swagger

Step 1: Adding Maven Dependency

To enable the Swagger in Spring Boot application with maven dependency, add the following dependencies in build configuration (pom.xml) file and refress project.

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.7.0</version>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.7.0</version>

</dependency>

Step 2: Configure Main Class:

Enable main application file to use Swagger.

@EnableSwagger2 is used for it and after enabling it, main application file should like as follows:

Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

// Marks this class as the main Spring Boot application
@SpringBootApplication

// Enables Swagger 2 for API documentation generation
@EnableSwagger2

// Enables Spring MVC explicitly (sometimes required for
// Swagger UI with SpringFox)
@EnableWebMvc

public class SwaggerApplication {

    // Entry point of the Spring Boot application
    public static void main(String[] args)
    {
        SpringApplication.run(SwaggerApplication.class,
                              args);
    }
}

Step 4: Configure Swagger

Java
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;

@Configuration
public class SwaggerConfig {

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

Output: run application and type this url on browser:

http://localhost:8080/v2/api-docs

Spring
output

Accessing Swagger UI

Type below url on browser:

http://localhost:8080/swagger-ui/index.html

Output:

Spring
output


This opens the interactive Swagger UI, where you can test all your API endpoints like /add, /view, etc., directly from your browser.


Article Tags :

Similar Reads