Swagger Integration with Spring Boot Project

Swagger Integration with Spring Boot Project – Complete Step-by-Step Guide

Swagger is a powerful RESTful API documentation and testing tool. Integrating Swagger with a Spring Boot project allows you to automatically generate interactive API documentation and test your endpoints directly from the browser. In this complete guide, we will explore what Swagger is, why it matters, and how to integrate Swagger with a Spring Boot project step by step – including both Swagger 2 and Swagger 3 (OpenAPI).

Swagger Integration with Spring Boot Project

What Is Swagger?

Swagger is a complete ecosystem 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 different teams to understand how to use them:

  • Frontend developers
  • Mobile app developers
  • QA testers
  • Third-party clients and partners

Each team needs to understand how to call the API – what URL to hit, which parameters to pass, what the request body should look like, what response format comes 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 your code and automatically generating documentation for all your APIs and endpoints. You don’t need to write documentation separately – Swagger generates it like this:

Swagger UI dashboard showing auto-generated API documentation with endpoints, parameters, and response codes

Swagger UI automatically displays:

  • Request parameters
  • Request body format (JSON)
  • Response structure
  • HTTP status codes
  • Example inputs and outputs

Swagger turns your API into a live, interactive manual that anyone can browse and test directly from the browser.

Why Swagger Is Important for Spring Boot Projects

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 the backend team for API details every time
  • API changes require manual communication
  • Incorrect inputs cause failures
  • Testing depends only on external tools like Postman

With Swagger:

  • As soon as the 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 needed

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

How to Add Swagger in a Spring Boot Project

Spring Boot does not include Swagger by default. To integrate Swagger 2, two dependencies are added to your pom.xml:

Swagger 2 Dependencies (Legacy):


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

Understanding the Swagger 2 Configuration Class

After adding the dependencies, you need to create a configuration class. Best practice is to place this inside a config or configuration package.

SwaggerConfig.java (Swagger 2):


@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 the Swagger feature in the project
  • Docket object – core component of Swagger; tells Swagger what to scan
  • .apis() – specifies which package contains your REST controllers
  • .paths() – filters URLs so only APIs matching the pattern appear
  • apiInfo() – sets the project title, version, developer info, and license

This information appears at the top of Swagger UI. Swagger is not just documentation – it is also a digital contract containing your API metadata.

Swagger Annotations for Richer Documentation:

Annotation Purpose
@Api Describes the Controller class
@ApiOperation Describes the purpose of a specific API method
@ApiModel Describes an entity/model class
@ApiModelProperty Adds explanation to fields inside a model

Swagger 2 vs Swagger 3 (OpenAPI) – What Changed?

Swagger 2 (Springfox) was later replaced by Swagger 3 (OpenAPI 3), which uses a different library called Springdoc. The major changes are:

  • @EnableSwagger2 is no longer needed
  • The Maven dependency is different (Springdoc instead of Springfox)
  • The Swagger UI URL changes from /swagger-ui.html to /swagger-ui/index.html

Swagger 3 (OpenAPI) Dependency:


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

Key advantages of Swagger 3 over Swagger 2:

  • More accurate and detailed documentation
  • Better, modern UI
  • Support for advanced request/response structures
  • Active community support (Springfox is no longer maintained)

Swagger vs Postman – Clear Comparison

Many developers wonder whether Swagger replaces Postman. The answer is: they serve different purposes. Here’s a detailed comparison:

Feature Swagger Postman
Primary Purpose API documentation + testing API testing only
Auto-Generated Docs ✅ Yes – reads code automatically ❌ No – manual setup required
Integrated with Code ✅ Yes – lives inside the project ❌ No – separate tool
Auto-Updates on Code Change ✅ Yes ❌ No
Try It Out (Live Testing) ✅ Yes – built-in ✅ Yes – full-featured
Environment Variables ❌ No ✅ Yes – advanced support
Best For Backend teams + API consumers QA testers + developers

Bottom line: Even if you use Postman for testing, Swagger should still be integrated in every professional Spring Boot API project for automatic documentation and team collaboration.

Swagger Integration with Spring Boot Project (Step-by-Step)

If you’ve followed our previous tutorial on implementing CRUD operations in Spring Boot with Data JPA and MySQL, we will now add Swagger to that same project.

Step 1 – Add the Swagger 3 (OpenAPI) Dependency

Add the following dependency to your pom.xml file:

pom.xml:


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

Step 2 – Create SwaggerConfig.java

Create a SwaggerConfig.java class inside your configuration package in the Spring Boot application:

SwaggerConfig.java (Swagger 3 / OpenAPI):


@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 basic details about your API. This is what Swagger UI shows at the top of the documentation – title, description, version, and contact info. It helps developers understand what your project is about.

This is only for documentation purposes. It does not affect your API logic or security. If you remove it, 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.

Step 3 – Whitelist Swagger URLs in Spring Security (Optional)

If your project uses Spring Security, you need to whitelist Swagger URLs so they are accessible without authentication. Add this to your security config:

SecurityConfig.java:


@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(jwtAuthenticationEntryPoint, UsernamePasswordAuthenticationFilter.class)
            .build();
}

Step 4 – Run and Access Swagger UI

Now run your Spring Boot application and open this URL in your browser:

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

You will see the Swagger UI with all your API documentation – every endpoint, parameter, request body, and response structure will be displayed automatically:

Swagger UI running on localhost showing all Spring Boot REST API endpoints with Try It Out button for live testing

Frequently Asked Questions (FAQ)

Q1: What is the difference between Swagger 2 and Swagger 3?

Swagger 2 uses the Springfox library with @EnableSwagger2 annotation and the Docket bean. Swagger 3 uses the Springdoc library with OpenAPI bean and does not require any enable annotation. Swagger 3 also has a modern UI and better support for Spring Boot 3.x.

Q2: How do I access Swagger UI in a Spring Boot application?

After adding the Springdoc dependency and running your application, open http://localhost:8080/swagger-ui/index.html in your browser. For Swagger 2, the URL is http://localhost:8080/swagger-ui.html.

Q3: Can I use Swagger with JWT authentication in Spring Boot?

Yes. You need to add addSecurityItem() and addSecuritySchemes() in your Swagger config to define Bearer Token authentication. This adds an “Authorize” button in Swagger UI where you can paste your JWT token for testing protected endpoints.

Q4: Does Swagger replace Postman?

No. Swagger is primarily for automatic API documentation with built-in testing. Postman is a dedicated API testing tool with advanced features like environment variables, test scripts, and collections. Both tools complement each other in professional development.

Q5: Which Swagger dependency should I use for Spring Boot 3?

For Spring Boot 3.x, use the Springdoc OpenAPI dependency: springdoc-openapi-starter-webmvc-ui. The old Springfox library (Swagger 2) is no longer maintained and does not support Spring Boot 3.

Conclusion

Swagger integration with Spring Boot is one of the simplest and most impactful improvements you can make to any API project. By adding a single dependency and a small configuration class, you get clean, auto-generated documentation, built-in API testing, and better team collaboration – all without writing a single line of manual documentation.

Here’s a quick recap of the key steps:

  • Step 1: Add the Springdoc OpenAPI dependency to pom.xml
  • Step 2: Create SwaggerConfig.java with API info and security settings
  • Step 3: Whitelist Swagger URLs in Spring Security (if applicable)
  • Step 4: Run the app and access Swagger UI at /swagger-ui/index.html

Whether you’re building small services or large enterprise-level systems with microservices architecture, adding Swagger is essential for professional API development. If you’re new to Spring Boot, check out our guides on creating REST APIs and implementing CRUD operations to get started.

Leave a Comment