Using Swagger in a Spring Boot Application (with Full Example)

2 min read

Using Swagger in a Spring Boot Application (with Full Example)

Swagger is a powerful tool for documenting RESTful APIs. It provides an interactive interface to explore and test endpoints, making it ideal for both development and client communication. In Spring Boot, Swagger can be integrated easily using the springdoc-openapi library.


Why Use Swagger?

  • Auto-generated API documentation
  • Interactive UI to test endpoints
  • Reduces need for manual documentation
  • Helps with team collaboration and onboarding

Step-by-Step Guide to Integrate Swagger in Spring Boot

Step 1: Create a Spring Boot Project

You can create a new Spring Boot project via Spring Initializr with the following dependencies:

  • Spring Web
  • Spring Boot DevTools (optional for hot reloading)

Or add manually to your Maven project:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 2: Add Swagger Dependency

Use springdoc-openapi for Swagger 3 (OpenAPI 3 spec).

For Maven, add to pom.xml:

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

For Gradle:

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'

Step 3: Create a Sample REST Controller

Create a sample controller to expose API endpoints.

package com.example.swaggerdemo.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @GetMapping("/{id}")
    public Product getProduct(@PathVariable Long id) {
        return new Product(id, "Laptop", 999.99);
    }

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return product;
    }
}

And the Product model:

package com.example.swaggerdemo.model;

public class Product {
    private Long id;
    private String name;
    private Double price;

    public Product() {}

    public Product(Long id, String name, Double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    // Getters and setters
}

Step 4: Run the Application

Run your application via main() or using mvn spring-boot:run.

Step 5: Access Swagger UI

Once the app is running, visit:

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

or (newer versions):

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

You’ll see a fully interactive API documentation UI


Optional: Customize Swagger Configuration

You can add metadata like API title, description, version, etc.

Create a configuration class:

package com.example.swaggerdemo.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .info(new Info()
                .title("Product API")
                .version("1.0")
                .description("API for managing products"));
    }

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
            .group("public")
            .packagesToScan("com.example.swaggerdemo.controller")
            .build();
    }
}

Bonus: Add Annotations for Better Docs

You can enhance model and endpoint documentation with annotations:

import io.swagger.v3.oas.annotations.media.Schema;

@Schema(description = "Product entity representing an item for sale")
public class Product {
    @Schema(description = "Unique identifier", example = "1")
    private Long id;

    @Schema(description = "Name of the product", example = "Laptop")
    private String name;

    @Schema(description = "Price of the product", example = "999.99")
    private Double price;

    // ...
}

Example Project Structure

src/
 └── main/
      ├── java/
      │   └── com.example.swaggerdemo/
      │         ├── controller/
      │         │     └── ProductController.java
      │         ├── model/
      │         │     └── Product.java
      │         └── config/
      │               └── SwaggerConfig.java
      └── resources/
            └── application.properties

Testing the API

You can test endpoints like:

  • GET /api/products/1
  • POST /api/products with JSON body:
{
  "id": 2,
  "name": "Smartphone",
  "price": 499.99
}

All this can be done directly from the Swagger UI.


Summary

StepDescription
1Create Spring Boot project
2Add springdoc-openapi dependency
3Create controllers/models
4Customize Swagger (optional)
5Access Swagger UI

🤞 Never miss a story from us, get weekly updates to your inbox!

Leave a Reply

Your email address will not be published. Required fields are marked *