This is the 7th day of my participation in Gwen Challenge

preface

Believe that you usually develop the process, will use the API documentation tool, right? What is everybody using? Java Docs, I/O docs, Apiary. IO, Docco, Dexy, Doxygen, TurnAPI, Swagger. Today I’m going to show you how to build API documents with Swagger.

What is the swagger?

  • The most popular Api framework in the world;
  • RestFul Api document online automatic generation tool;
  • Documentation and implementation are kept synchronized and updated automatically to simplify the API building process;
  • Run directly, can test API interface online;
  • Supports multiple languages :(Java, PHP…)

Swagger – core annotation

Name Description
@Api Tagged with Swagger Resource
@ApiModel Labeled Swagger model
@ApiModelProperty Attribute description of model fields
@ApiOperation Description of HTTP interfaces
@ApiParam HTTP interface parameters

For more details, see github at github.com/swagger-api…

Springboot integration swagger

  1. Create a SpringBoot project => Web project
  2. Importing dependent dependencies
	<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.61.</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.61.</version>
        </dependency>
Copy the code
  1. Configure Swagger information
@Configuration
@EnableSwagger2 / / open Swagger2
public class SwaggerConfig {

    @Bean
    public Docket docket(Environment environment){

        // Whether to enable Swagger depending on your development environment
        Profiles profiles = Profiles.of("pro");
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
            Enable (flag) // Enable Whether to enable Swagger The default value is true. If the value is false, Swagger cannot be displayed in the browser
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cn.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    public ApiInfo apiInfo(a){
        Contact contact=new Contact("First love"."https://juejin.cn/user/3940246036953293"."[email protected]");
        return new ApiInfoBuilder()
                .title("Background Management System API Documentation")
                .description("The harder you work, the luckier you get.")
                .termsOfServiceUrl("https://juejin.cn/user/3940246036953293")
                .version("1.0") .contact(contact) .build(); }}Copy the code
  1. The controller layer
@Controller
public class LoginController {

    @GetMapping(value = "/toLogin")
    public String toLogin(a){
        return "login";
    }

    @apiOperation (value = "login ")
    @PostMapping("/login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
            return "index";
        }catch (UnknownAccountException uae){
            model.addAttribute("msg"."User does not exist");
            return "login";
        }catch (IncorrectCredentialsException ice){
            model.addAttribute("msg"."Incorrect password");
            return "login"; }}@GetMapping("/logOut")
    public String logOut(a){
        return "login";
    }

    @GetMapping("/noAuthorization")
    public String noAuthorization(a){
        return "This page cannot be accessed without authorization"; }}Copy the code
@Controller
@RequestMapping("/userInfo")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/userList")
    public String getUserList(a){
        return "userList";
    }

    @GetMapping("/userAdd")
    public String addUser(a){
        return "addUser";
    }

    @GetMapping("/userDel")
    public String deleteUser(a){
        return "deleteUser";
    }

    @GetMapping("/getList")
    public List<UserInfo> getList(int id){
        return userService.getList(id);
    }

    @apiOperation (value = "find user information based on user name ")
    @GetMapping("/findByUsername")
    public UserInfo findByUsername(@RequestParam("username") String username){
        returnuserService.findByUsername(username); }}Copy the code
  1. Browser visit: http://localhost:8080/swagger-ui.html

At the end

  1. Swagger can serve as an important bridge for communication between the front and back ends, easily and quickly. To be very practical.

  2. Swagger projects allow you to produce, display and consume your own RESTful services. No proxy or third party services are required. Swagger UI is a dependency free collection of resources that dynamically generates beautiful documents and sandboxes through the Swagger API. Since Swagger UI has no dependencies, you can deploy it to any server environment or your own machine.