Spring Boot + Swagger: A Step-by-Step Guide to Interactive API Documentation
Tags: webdev, springboot, beginners, programming
Published: 2024-06-30 03:23:59


## Introduction

In today's software development, especially when dealing with APIs (Application Programming Interfaces), having clear and detailed documentation is essential. It guides developers on how to use a service, which endpoints are available, and what data to send or expect in return. Swagger has become a widely used tool for this purpose. This guide will explain what Swagger is, how it functions, and provide an illustrative example of its use.

## What is Swagger?

Swagger is a powerful open-source framework backed by a large ecosystem of tools that helps developers design, build, document, and consume RESTful web services. Swagger is language-agnostic and can be used with any programming language that supports REST API development.

### Key Features:

- **API Documentation**: Swagger automatically generates interactive API documentation, allowing developers to explore and test endpoints.
- **Design First or Code First**: Swagger supports design-first and code-first approaches, making it versatile for different development workflows.
- **Interactive API Console**: It provides an interface to test API endpoints directly from the documentation.
- **Standardization**: Using the OpenAPI Specification (formerly known as Swagger Specification), Swagger standardizes how APIs are described.

Before diving deeper into the practice today, you should prepare the things below:

### **Prerequisite**

- SpringBoot application source code
- IntelliJ
- (Option) I’m using the current project which is running on an AWS EC2 server, so if you want to deploy and test on your server
    - Open port `8080` in SecurityGroup

## Step 1: Setup library

- Choose the appropriate setup and compatible version depending on your project's configuration, whether it's Gradle or Maven.

[springfox-swagger-ui](https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui)

## Step 2: Create a `SwaggerConfig`

- We need to configure Swagger for our application.

Java:
```java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("your package name"))
                .paths(PathSelectors.any())
                .build();
    }
}
```

Kotlin

```kotlin

@Configuration
@EnableSwagger2
class SwaggerConfig {
    @Bean
    fun api(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("your package name")) 
            .paths(PathSelectors.any())
            .build()
    }
}
```

> Don't forget to replace “your package name” with your application (typically, your application name)

## Step 3: Update Security Config

- If your app is configured with a security layer, you need to modify it to allow access to the Swagger documentation.

Java
```java
  protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                // Other configurations...
                .antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**") // Add endpoint
                // Other configurations...
              
    }
```

Kotlin
```kotlin
@Throws(Exception::class)
protected fun configure(http: HttpSecurity) {
    http
        .cors()
        // Other configurations...
        .antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**") // Add endpoint
        .permitAll() // Add permit for it
        // Other configurations...
}
```

## Step 4: Viewing the Documentation
- Build and deploy (or start the server in localhost)

- If you're developing on your PC, simply restart and enter this in your browser:

```xml
http://localhost:8080/swagger-ui.html/
```
- If you’re deploying in your server

```xml
http://your-server-ip:8080/swagger-ui.html/
```

![API-List](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qdn8vdhw6rx6l89z6iel.png)

- All of the APIs will be displayed on the Swagger page. You can try and test the APIs just like you would in POSTMAN.


![Swagger-springboot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8y9bkbnb4n4d8h5njpvu.png)


## Final Thought

Swagger is an invaluable tool for API development and documentation. It not only helps in maintaining up-to-date documentation but also enhances the developer experience by providing an interactive interface to explore and test APIs. By integrating Swagger into your API development workflow, you can ensure that your APIs are well-documented, easy to understand, and user-friendly.

For the Node.js project, I also guide steps. Check it out!!!
[Set up swagger for NodeJS project!](https://dev.to/cuongnp/swagger-nodejs-express-a-step-by-step-guide-4ob)