继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Swagger入门教程:轻松上手API文档自动生成

BIG阳
关注TA
已关注
手记 474
粉丝 73
获赞 458
概述

Swagger 是一个用于描述和文档化 RESTful API 的规范和框架,提供了一套工具来设计、构建、测试和使用 API。Swagger 通过简单的注解和配置自动生成 API 文档,并支持交互式测试界面和跨平台兼容性,大大提高了 API 开发的效率和质量。

Swagger简介与基本概念
什么是Swagger

Swagger 是一个用于描述 RESTful API 的规范和框架,它提供了一套工具来设计、构建、文档化、测试、使用和理解 RESTful Web 服务。Swagger 能够在不编写任何代码的情况下定义和验证 API 的结构,同时也可以生成交互式文档,使开发者能够更容易理解和使用 API。Swagger 通过 JSON 或 YAML 格式来描述 API 的各个部分,包括资源、方法、参数和数据模型。

Swagger的作用和优势

Swagger 的作用主要体现在以下几个方面:

  1. API 文档自动生成:Swagger 能够自动生成 API 文档,减少了手动编写文档的工作量。
  2. 交互式体验:提供交互式的 API 测试界面,无需编写代码即可测试 API 的功能。
  3. 跨平台兼容性:Swagger 提供了一个统一的规范,可以在多种编程语言和框架中使用。
  4. 版本控制:支持版本控制,方便管理和维护不同版本的 API。
  5. 自动化测试:可以生成测试案例,帮助开发者进行自动化测试。
  6. 团队协作:团队成员可以更方便地协作,确保 API 的设计和实现一致。
  7. API 通信协议:Swagger 支持多种通信协议,如 HTTP、HTTPS 等。

Swagger 的优势包括:

  1. 易于使用:通过简单的注解和配置,可以快速生成 API 文档。
  2. 标准化:遵循 OpenAPI 规范,确保 API 文档的标准化。
  3. 跨平台:支持多种编程语言,如 Java、Python、Ruby、JavaScript 等。
  4. 文档和代码同步:Swagger 的注解可以与代码同步,保证文档和代码的一致性。
  5. API 管理:支持 API 的发现、集成和管理,便于维护和扩展 API。
Swagger与API文档的关系

Swagger 在 API 文档生成中扮演了非常关键的角色。传统的 API 文档通常是手动编写或通过特定工具生成的,这不仅耗时而且容易出错。Swagger 则提供了一种自动化的方式,通过在代码中添加特定注解来描述 API 的结构,从而生成精确且易于理解的交互式文档。

Swagger 的核心是通过 OpenAPI 规范定义 API,这些规范描述了 API 的各个方面,包括资源、方法、参数、响应等。这些规范可以被 Swagger 工具解析,生成相应的文档,并且可以在不编写代码的情况下进行测试和验证。

Swagger与API开发流程

  1. 设计阶段:在 API 设计阶段,开发者可以使用 Swagger 来定义 API 的结构和规范。
  2. 实现阶段:在实现阶段,开发者可以使用 Swagger 注解来描述 API 的具体实现。
  3. 测试阶段:在测试阶段,Swagger 提供的交互式界面可以用于验证 API 的功能。
  4. 文档阶段:Swagger 自动生成的交互式文档可以供开发团队和用户查看和理解 API。

通过这种方式,Swagger 从 API 的设计、实现到测试、文档生成等各个阶段都提供了强有力的工具支持,极大地提高了 API 开发的效率和质量。

Swagger安装与配置
安装Swagger依赖库

要使用 Swagger,首先需要在项目中添加相应的依赖库。Swagger 的库通常与 Spring Boot 框架结合使用,因此这里将以 Spring Boot 为例进行介绍。

Maven 依赖配置

在 Maven 项目的 pom.xml 文件中添加 Swagger 的依赖库。

<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>

Gradle 依赖配置

如果使用 Gradle 项目,可以在 build.gradle 文件中添加 Swagger 的依赖库。

dependencies {
    implementation 'io.springfox:springfox-swagger2:2.9.2'
    implementation 'io.springfox:springfox-swagger-ui:2.9.2'
}

配置Swagger文档的基本信息

在配置完依赖库之后,需要配置 Swagger 的基本信息。这些信息包括 API 的标题、描述、版本等。配置通常放在一个配置类中,例如 SwaggerConfig.java

配置说明

  1. @Configuration:将该类配置为 Spring Boot 的配置类。
  2. @EnableSwagger2:启用 Swagger 2。
  3. @Bean:定义一个 Docket 配置对象,用于配置 Swagger 的基本信息。
  4. apiInfo():用于定义 API 的基本信息,如标题、描述和版本等。
  5. select():用于配置 API 的扫描范围,这里配置为扫描所有控制器。

示例配置类

package com.example.demo.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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger API Documentation")
                .description("This is a sample API documentation.")
                .version("1.0.0")
                .build();
    }
}
创建Swagger文档
添加API信息和路径

在配置完 Swagger 的基本信息后,可以开始定义具体的 API 信息。这通常是在控制器类中使用 Swagger 注解来完成的。

示例控制器类

package com.example.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
@Api(value = "User API", description = "Operations related to users")
public class UserController {

    @GetMapping("/users")
    @ApiOperation(value = "Get all users", notes = "Returns a list of all users")
    public String getUsers() {
        return "List of users";
    }

    @PostMapping("/users")
    @ApiOperation(value = "Create a new user", notes = "Creates a new user")
    public String createUser() {
        return "User created";
    }

    @PutMapping("/users/{id}")
    @ApiOperation(value = "Update a user", notes = "Updates a user by id")
    public String updateUser(@PathVariable String id) {
        return "User updated";
    }

    @DeleteMapping("/users/{id}")
    @ApiOperation(value = "Delete a user", notes = "Deletes a user by id")
    public String deleteUser(@PathVariable String id) {
        return "User deleted";
    }
}

描述API请求参数

在定义 API 请求时,可以使用 Swagger 注解描述请求参数。这包括参数的名称、类型、是否必填等信息。

示例请求参数

package com.example.demo.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class UserController {

    @GetMapping("/users")
    @ApiOperation(value = "Get all users", notes = "Returns a list of all users")
    public String getUsers() {
        return "List of users";
    }

    @PostMapping("/users")
    @ApiOperation(value = "Create a new user", notes = "Creates a new user")
    @ApiParam(name = "user", value = "User object", required = true)
    public String createUser(@RequestParam String user) {
        return "User created";
    }

    @PutMapping("/users/{id}")
    @ApiOperation(value = "Update a user", notes = "Updates a user by id")
    @ApiParam(name = "id", value = "User id", required = true)
    public String updateUser(@PathVariable String id) {
        return "User updated";
    }

    @DeleteMapping("/users/{id}")
    @ApiOperation(value = "Delete a user", notes = "Deletes a user by id")
    @ApiParam(name = "id", value = "User id", required = true)
    public String deleteUser(@PathVariable String id) {
        return "User deleted";
    }
}

定义API响应结果

定义 API 的响应结果可以使用 Swagger 注解来描述响应的类型和结构。这有助于更清晰地定义 API 的输出格式。

示例响应结果

package com.example.demo.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class UserController {

    @GetMapping("/users")
    @ApiOperation(value = "Get all users", notes = "Returns a list of all users")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully retrieved list"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    public String getUsers() {
        return "List of users";
    }

    @PostMapping("/users")
    @ApiOperation(value = "Create a new user", notes = "Creates a new user")
    @ApiResponses(value = {
            @ApiResponse(code = 201, message = "User created"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "user", value = "User object", required = true)
    public String createUser(@RequestParam String user) {
        return "User created";
    }

    @PutMapping("/users/{id}")
    @ApiOperation(value = "Update a user", notes = "Updates a user by id")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User updated"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "id", value = "User id", required = true)
    public String updateUser(@PathVariable String id) {
        return "User updated";
    }

    @DeleteMapping("/users/{id}")
    @ApiOperation(value = "Delete a user", notes = "Deletes a user by id")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User deleted"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "id", value = "User id", required = true)
    public String deleteUser(@PathVariable String id) {
        return "User deleted";
    }
}
运行与测试Swagger文档
启动Swagger UI

启动 Swagger UI 后,可以访问 Swagger UI 界面来查看和测试 API 文档。

启动步骤

  1. 运行 Spring Boot 应用程序:启动 Spring Boot 应用程序。
  2. 访问 Swagger UI:在浏览器中输入 http://localhost:8080/swagger-ui.html,访问 Swagger UI 界面。

测试示例

  1. 选择 API 方法:在 Swagger UI 界面中,选择要测试的 API 方法。
  2. 输入参数:根据方法的定义输入参数值。
  3. 执行测试:点击“Try it out”按钮执行测试。
查看生成的Swagger文档

生成的 Swagger 文档可以在 Swagger UI 界面中查看。Swagger 文档包括 API 的基本信息、路径、参数、响应等信息。

文档结构

  1. 基本信息:包括 API 的标题、描述、版本等信息。
  2. 路径:包括定义的所有路径和方法。
  3. 参数:包括每个方法的参数描述。
  4. 响应:包括每个方法的响应结果和响应码。
Swagger常用注解详解

Swagger 提供了丰富的注解来描述 API 的各个方面。这些注解包括:

  1. @Api:用于描述控制器的 API 信息,包括标题和描述。
  2. @ApiOperation:用于描述方法的 API 信息,包括方法名称、注释等。
  3. @ApiParam:用于描述参数的详细信息,包括名称、描述和是否必填。
  4. @ApiResponses:用于描述方法的响应结果。
  5. @ApiResponse:用于描述具体的响应信息,包括响应码和响应信息。

示例代码

package com.example.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
@Api(value = "User API", description = "Operations related to users")
public class UserController {

    @GetMapping("/users")
    @ApiOperation(value = "Get all users", notes = "Returns a list of all users")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully retrieved list"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    public String getUsers() {
        return "List of users";
    }

    @PostMapping("/users")
    @ApiOperation(value = "Create a new user", notes = "Creates a new user")
    @ApiResponses(value = {
            @ApiResponse(code = 201, message = "User created"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "user", value = "User object", required = true)
    public String createUser(@RequestParam String user) {
        return "User created";
    }

    @PutMapping("/users/{id}")
    @ApiOperation(value = "Update a user", notes = "Updates a user by id")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User updated"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "id", value = "User id", required = true)
    public String updateUser(@PathVariable String id) {
        return "User updated";
    }

    @DeleteMapping("/users/{id}")
    @ApiOperation(value = "Delete a user", notes = "Deletes a user by id")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User deleted"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "id", value = "User id", required = true)
    public String deleteUser(@PathVariable String id) {
        return "User deleted";
    }
}

注解解释

  1. @Api:描述控制器的 API 信息。
  2. @ApiOperation:描述方法的 API 信息。
  3. @ApiParam:描述参数的详细信息。
  4. @ApiResponses:描述方法的响应结果。
  5. @ApiResponse:描述具体的响应信息。
常见问题及解决方案
遇到的常见问题

在使用 Swagger 过程中,可能会遇到一些常见问题,例如:

  1. 文档生成失败:文档生成过程中报错,无法生成文档。
  2. 文档不完整:生成的文档中某些信息没有正确显示。
  3. 测试失败:在 Swagger UI 中测试 API 时,返回错误结果。
解决问题的方法与技巧

文档生成失败

  • 检查配置:确认 Swagger 的配置类和注解是否正确配置。
  • 依赖库版本:确保使用的 Swagger 依赖库版本与 Spring Boot 版本兼容。
  • 启动类:确保在启动类中引入了 Swagger 的配置。
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

文档不完整

  • 检查注解:确保所有控制器和方法都正确使用了 Swagger 注解。
  • 路径配置:确保路径配置正确,例如使用 @RequestMapping 注解。

测试失败

  • 路径映射:确保请求路径映射正确,例如 @GetMapping 注解路径是否正确。
  • 参数映射:确保请求参数映射正确,例如 @RequestParam 注解是否正确使用。

示例代码

package com.example.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
@Api(value = "User API", description = "Operations related to users")
public class UserController {

    @GetMapping("/users")
    @ApiOperation(value = "Get all users", notes = "Returns a list of all users")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully retrieved list"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    public String getUsers() {
        return "List of users";
    }

    @PostMapping("/users")
    @ApiOperation(value = "Create a new user", notes = "Creates a new user")
    @ApiResponses(value = {
            @ApiResponse(code = 201, message = "User created"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "user", value = "User object", required = true)
    public String createUser(@RequestParam String user) {
        return "User created";
    }

    @PutMapping("/users/{id}")
    @ApiOperation(value = "Update a user", notes = "Updates a user by id")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User updated"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "id", value = "User id", required = true)
    public String updateUser(@PathVariable String id) {
        return "User updated";
    }

    @DeleteMapping("/users/{id}")
    @ApiOperation(value = "Delete a user", notes = "Deletes a user by id")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User deleted"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource is forbidden")
    })
    @ApiParam(name = "id", value = "User id", required = true)
    public String deleteUser(@PathVariable String id) {
        return "User deleted";
    }
}

通过以上配置和注解,可以确保 Swagger 文档生成和测试的顺利进行。如果遇到具体问题,可以参考官方文档或在线社区寻求帮助,以确保项目顺利进行。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP