Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Configuring Knife4j for Advanced API Documentation in Spring Boot

Tech 1

Include the starter dependency to enable enhanced Swagger UI capabilities.

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
    <version>4.0.0</version>
</dependency>

Configuration Setup

Define a Spring Bean to manage API metadata and controller scanning paths.

package com.example.service.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
public class ApiDocumentationConfig {

    @Bean(value = "apiDocket")
    public Docket configureApiDocs() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("API Reference Documentation")
                        .description("# Enhanced Interface Definitions")
                        .termsOfServiceUrl("https://doc.xiaominfo.com/")
                        .version("2.0")
                        .build())
                .groupName("Main Service")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
}

Access the interface via the designated endpoint:

http://localhost:PORT/doc.html

Unified Response Wrapper

Implement a generic structure for controller return values too ensure consistent payload formatting.

import lombok.Data;

@Data
public class ApiResponse<T> {

    private Integer errorCode;
    private String errorMessage;
    private T responseData;

    public ApiResponse() {}

    protected static <T> ApiResponse<T> create(T data) {
        ApiResponse<T> response = new ApiResponse<>();
        if (data != null) {
            response.setResponseData(data);
        }
        return response;
    }

    public static <T> ApiResponse<T> createWithStatus(T body, Integer code, String msg) {
        ApiResponse<T> response = create(body);
        response.setErrorCode(code);
        response.setErrorMessage(msg);
        return response;
    }

    public static <T> ApiResponse<T> ok(T data) {
        ApiResponse<T> response = create(data);
        response.setErrorCode(200);
        response.setErrorMessage("Success");
        return response;
    }

    public static <T> ApiResponse<T> error(Integer code, String msg) {
        ApiResponse<T> response = new ApiResponse<>();
        response.setErrorCode(code);
        response.setErrorMessage(msg);
        return response;
    }

    public ApiResponse<T> setErrorMsg(String msg) {
        this.setErrorMessage(msg);
        return this;
    }

    public ApiResponse<T> setErrorCode(Integer code) {
        this.setErrorCode(code);
        return this;
    }
}

Status Enumerations

Centralize error codes and messages using an enum type.

import lombok.Getter;

@Getter
public enum HttpStatusEnum {

    SUCCESS(200, "Operation Successful"),
    FAILURE(500, "Operation Failed");

    private final Integer code;
    private final String message;

    HttpStatusEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.