Swagger Integration with Spring Boot Project

Swagger Integration with Spring Boot Project

Swagger is powerful RESTful APIs testing and documenting tool. Integrating Swagger with Spring Boot project allows us to easily visualize APIs documentation and test our apis. In this article, we will explore what is Swagger and how to integrate Swagger with Spring Boot project step by step.

Swagger Integration with Spring Boot Project

What is Swagger?

Swagger is a complete ecosystem that is used to document, visualize, and test REST APIs. When APIs are created in the backend (for example in Spring Boot), there must be a way for :

  • Frontend developers Mobile
  • App developers
  • Testers
  • Third-party clients

to understand how to call the API – what URL to hit, which parameters to pass, what request body should look like, what response format will come back, and what status codes are returned. If documentation is written manually, it becomes:

  • Time-consuming
  • Hard to update when code changes
  • Prone to mistakes

Swagger solves this problem by reading the code and automatically generating documentation according to our apis and endpoints. So while building APIs, you do not need to write documentation separately. Swagger takes the code and generates documentation like:

Swagger documentation UI Example

It also shows:

  • Request parameters
  • Request body format (JSON)
  • Response structure
  • Status codes

Example inputs and outputs Swagger turns your API into a live online manual, available for anyone to browse and test.

Why Swagger is important

Imagine an organization where:

  • Backend developers create APIs
  • Frontend team consumes APIs
  • Mobile team consumes APIs
  • Testers test APIs
  • External clients use APIs to integrate

Without Swagger:

  • Everyone keeps asking backend team for API details every time
  • API changes require manual communication
  • Incorrect inputs cause failures
  • Testing depends only on tools like Postman

With Swagger:

  • As soon as backend runs the project, documentation appears automatically
  • Anyone can test the API without contacting backend developers
  • If backend code changes, Swagger updates itself automatically
  • No manual documentation effort

So Swagger becomes the single source of truth for all API details.

How Swagger is added in Spring Boot

Spring Boot does not provide Swagger by default. To integrate Swagger, two dependencies are added:


<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

How Swagger is configured – Understanding the Configuration Class

After adding the dependencies, a configuration class is needed to create. Best practice is to create this configuration class inside the “config” or “configuration” package.


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors
                        .basePackage("com.nt.controller"))
                .paths(PathSelectors.regex("/tourist.*"))
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact(
                "Aman Gupta",
                "engineerscodinghub@gmail.com"
        );

        return new ApiInfo(
                "Students API",
                "Gives Information About Students API",
                "3.4 RELEASE",
                "https://www.engineerscodinghub.com",
                contact,
                "GNU Public",
                "https://apache.org",
                new ArrayList<>()
        );
    }
}

Let’s break this down line by line:

  • @Configuration – tells Spring this is a configuration class
  • @EnableSwagger2 – activates Swagger feature in the project
  • Docket object – core component of Swagger; tells Swagger what to scan
  • .apis() – specifies which package contains REST controllers
  • .paths() – filters URLs so only APIs starting with /tourist appear
  • apiInfo() – sets project title, version, developer info, license, etc.

This information appears on top of Swagger UI. So Swagger is not just documentation its also a digital contract containing API metadata.

Swagger supports annotations to add human-readable descriptions.

  • @Api Describes Controller
  • @ApiOperation Describes purpose of a method
  • @ApiModel Describes an entity/model class
  • @ApiModelProperty Adds explanatio n to fields inside a model

Swagger UI displays:

  • URL
  • HTTP method (GET/POST/PUT/DELETE)
  • Parameters
  • Request body sample
  • Response JSON
  • HTTP Status codes

Swagger 2 to Swagger 3 Upgrade (OpenAPI)

Later Swagger 2 was replaced by Swagger 3 (OpenAPI 3).

The major change is that:

  • @EnableSwagger2 is no longer used
  • Dependency is different
  • URL changes

New dependency (Swagger 3):


<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.5.0</version>
</dependency>

Swagger 3 offers:

  • More accurate documentation
  • Better UI
  • Support for advanced request/response structures

Swagger vs Postman (Clear Logical Comparison)

Postman is only a testing tool while Swagger is documentation + testing + client guide. So even if you use Postman, Swagger should still be used in professional API development.

Swagger is extremely important in real API development because it:

  • Eliminates manual documentation
  • Keeps API information updated automatically with code
  • Allows every team (frontend, mobile, testers) to test APIs easily
  • Helps external clients integrate without contacting backend team
  • Improves collaboration and reduces communication gaps
  • Boosts productivity and reduces mistakes

Swagger Integration with Spring Boot Project

Please check our last article about Implement CRUD Operations in Spring boot, Data JPA and MySQL

https://engineerscodinghub.com/implement-crud-operations-using-spring-boot/

In this Application will integrate swagger so for this First need to add the following Swagger dependency in your spring boot application pom.xml file


<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.5.0</version>    
</dependency>

Create SwaggerConfig.java class inside configuration package in your spring boot application


@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("Student Management API")
                        .description("API documentation for the Student Management System")
                        .version("1.0")
                        .contact(new Contact()
                                .name("Aman Gupta")
                                .email("contact@engineerscodinghub.com")
                        )
                )
                // Add security requirement for JWT
                .addSecurityItem(new SecurityRequirement().addList("BearerAuth"))

                // Define the security scheme
                .components(new Components()
                        .addSecuritySchemes("BearerAuth",
                                new SecurityScheme()
                                        .name("Authorization")
                                        .type(SecurityScheme.Type.HTTP)
                                        .scheme("bearer")
                                        .bearerFormat("JWT")
                        )
                );
    }
}

What does the info() section do?

The info() part contains the basic details about your API. This is what Swagger UI shows at the top of the documentation. It helps developers understand what your project is about.

This is only for documentation. It does not affect your API or security. If you remove this, Swagger still works, but the documentation looks incomplete.

What does addSecurityItem() and components do?

These lines are needed only when your Spring Boot application uses JWT Authentication. Swagger does not know about your token system automatically. So you must tell Swagger that your API needs a Bearer Token for protected endpoints.

In simple words:

  • addSecurityItem() tells Swagger “This API uses authentication, so show the Authorize button.”
  • components().addSecuritySchemes() defines “This authentication uses a Bearer Token in the Authorization header.”

After adding this, Swagger UI shows the Authorize button. You enter your JWT token once and Swagger sends it automatically with every request.

Secure Swagger with Spring Security (Optional)

If your project uses security, you may need to whitelist Swagger URLs. Add this to your security config:


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {

    return httpSecurity
            .csrf(csrf -> csrf.disable()) // disable csrf
            .authorizeHttpRequests(auth -> auth
                    .requestMatchers(
                            "/auth/**",
                            "/swagger-ui/**",
                            "/v3/api-docs/**"
                    ).permitAll()
                    .anyRequest().authenticated()
            )
            .sessionManagement(session -> session
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthenticationEntiryPoint, UsernamePasswordAuthenticationFilter.class)
            .build();
}

Now just run your Spring Boot application and hit this url in the browser: http://localhost:8080/swagger-ui/index.html you will see the Swagger UI with all your APIs document that you have created inside you application.

Swagger documentation UI Example

Conclusion

Swagger integration with Spring Boot is one of the simplest improvements you can make to any API project. It gives you clean documentation, easier testing, and better developer collaboration.

Whether you’re building small services or large enterprise-level systems, adding Swagger is worth it.

Leave a Comment