preface

API documentation is the best way to communicate in the front – and – back – end separated development model. Today we’ll talk about how to integrate Swagger into a beautiful, functional interface document. Source portal: https://gitee.com/huoqstudy/xiliu-admin.git


Introduction to Swagger

Swagger is a canonical and complete framework for generating, describing, invoking, and visualizing RESTful Web services with the following advantages: 1. Timeliness (after interface changes, it can timely and accurately inform relevant front-end developers) 2. Normative (and ensure that the interface is normative, such as interface address, request mode, parameter and response format and error message) 3. Consistency (the interface information is consistent, and there will be no differences due to the inconsistency of the document version obtained by the developer) 4. Testability (testing directly on the interface document to facilitate business understanding)

2. Configure Swagger

1. Add dependencies

<! --swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7. 0</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.7. 0</version>
</dependency>
Copy the code

2. Create a Swagger2 profile

The code is as follows (example) :

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket apiConfig(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                // Call the apiInfo method to create an instance of the apiInfo that is displayed on the document page
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                / / the headlines
                .title("Interface Document")
                // Detailed description
                .description("Interface Document")
                / / version
                .version("1.0")
                / / the author
                .contact(new Contact("xiliu"."http://www.xxx.com"."[email protected]")) .build(); }}Copy the code

3. Restart the service viewing interface

Access path:http://localhost:8081/swagger-ui.html, the generated document page appears. However, as a person with aesthetic pursuit, this UI is too ugly, so give it up and replace it with Knife4j

4. Use Knife4j

Knife4j’s predecessor was Swagger-Bootstrap-UI, and the predecessor swagger-Bootstrap-UI was a UI skin project of pure Swagger-UI. However, with the development of the project, in the face of more and more personalized requirements, we had to write back-end Java code to meet the new requirements. Therefore, the project was officially renamed Knife4J in the hope that knife4J could be as small, light and powerful as a dagger. The name change is also intended to make it a universal solution for Swagger interface documentation, not just focus on the front-end Ui front end.

4.1 Adding a Dependency

Need to remove the previously referenced Swagger dependency

<dependency>
	<groupId>com.github.xiaoymin</groupId>
	<artifactId>knife4j-spring-boot-starter</artifactId>
	<version>2.07.</version>
</dependency>
Copy the code

4.2 Modifying a Configuration Class

@Configuration
@EnableSwagger2WebMvc
public class Swagger2Config {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2(a) {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("Interface Document")
                        .description("# interface document")
                        .termsOfServiceUrl("http://www.xx.com/")
                        .contact("[email protected]")
                        .version("1.0")
                        .build())
                // Group name
                .groupName("2. X version")
                .select()
                // Specify the Controller scan package path
                .apis(RequestHandlerSelectors.basePackage("com.java.xiliu"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    /*@Bean public Docket apiConfig() { return new Docket(DocumentationType.SWAGGER_2) // ApiInfo (apiInfo()); call the apiInfo method to create an instance of the apiInfo that is displayed on the document page. ApiInfo (apiInfo()); } private ApiInfo ApiInfo () {return new ApiInfoBuilder().title(" API ").description(" API ") // version Version (" 1.0 "). / / the author contact (new contact (" xiliu ", "http://www.xxx.com", "277769738 @qq.com")). The build (); } * /

}
Copy the code

4.3 Restart Service View Interface

Visit address:http://localhost:8081/doc.html, this UI interface looks more beautiful, more in line with the habits of americans.

5. Define interface description and parameter description

Defined on a class: @API

Defined in method: @apiOperation

Defined in parameters: @apiparam

@API (tags = "User Management ")
@RestController
@RequestMapping("/ucenter/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @apiOperation (value = "all users list ")
    @GetMapping(value = "/getAll")
    public List<Member> list(a){
        return memberService.list(null);
    }

    @apiOperation (value = "delete user by id ")
    @PostMapping(value = "del/{memberId}")
    public boolean deleteById(
            @apiParam (name = "memberId", value = "userid ", Required = true)
            @PathVariable Long memberId){
        return memberService.removeById(memberId);
    }

    @apiOperation (value = "save user ")
    @PostMapping(value = "save")
    public boolean save(
            @apiparam (name = "member", value = "user object json", Required = true)
            @RequestBody Member member){
        if (null == member.getMemberId()) {
            return memberService.save(member);
        }
        returnmemberService.updateById(member); }}Copy the code


conclusion

Thanks for reading, that’s what I’m going to talk about today. This article briefly introduces how to integrate Swagger to generate API documents, although many people use Swagger, it is not easy to use, based on annotations, code is very intrusive, and many other reasons. But generally speaking, Swagger has been developed so far, including in various languages such as NodeJs,.NET, Java, PHP and so on. It can be said that swagger has some interface specifications. From the beginning to the step by step, it is a very difficult process, nothing is perfect, so is Swagger. At least it provides a document generation solution for so many languages that its value far outweighs its drawbacks.

Last but not least, does your project use swagger?