深入解析Swaggo/swag项目中的Swagger YAML规范

深入解析Swaggo/swag项目中的Swagger YAML规范

swag Automatically generate RESTful API documentation with Swagger 2.0 for Go. swag 项目地址: https://gitcode.com/gh_mirrors/sw/swag

Swaggo/swag是一个强大的Go语言API文档生成工具,它能够自动从代码注释生成Swagger/OpenAPI文档。本文将详细解析项目中提供的示例Swagger YAML文件,帮助开发者理解如何构建规范的API文档。

基础信息配置

在Swagger文档的顶部,我们首先看到的是API的基础配置信息:

basePath: /api/v1
host: localhost:8080
info:
  title: Swagger Example API
  version: "1.0"
  description: This is a sample server celler server.

这些配置定义了API的基本信息:

  • basePath:所有API路径的前缀,这里是/api/v1,表示这是API的第1版
  • host:API服务的主机和端口
  • info部分包含了API的标题、版本和描述信息

数据模型定义

Swagger文档的核心部分之一是数据模型定义,它描述了API中使用的各种数据结构:

definitions:
  model.Account:
    properties:
      id:
        example: 1
        format: int64
        type: integer
      name:
        example: account name
        type: string
      uuid:
        example: 550e8400-e29b-41d4-a716-446655440000
        format: uuid
        type: string
    type: object

这个示例中定义了Account模型,包含三个属性:

  • id:64位整数类型,示例值为1
  • name:字符串类型,示例值为"account name"
  • uuid:UUID格式的字符串

这种定义方式使得API的输入输出结构非常清晰,便于前后端开发人员理解数据格式。

路径和操作定义

Swagger文档最重要的部分是API路径和操作的定义。让我们看一个完整的GET操作示例:

/accounts:
  get:
    consumes:
    - application/json
    description: get accounts
    parameters:
    - description: name search by q
      format: email
      in: query
      name: q
      type: string
    produces:
    - application/json
    responses:
      "200":
        description: OK
        schema:
          items:
            $ref: '#/definitions/model.Account'
          type: array
      "400":
        description: Bad Request
        schema:
          $ref: '#/definitions/httputil.HTTPError'
    summary: List accounts
    tags:
    - accounts

这个定义包含了:

  1. 路径:/accounts
  2. HTTP方法:GET
  3. 请求参数:一个名为q的查询参数,用于按名称搜索
  4. 响应:成功(200)时返回Account数组,错误(400)时返回HTTPError
  5. 标签:accounts,用于分组相关API

参数类型详解

Swagger支持多种参数类型,示例中展示了各种参数使用方式:

  1. 路径参数
- description: Account ID
  in: path
  name: id
  required: true
  type: integer
  1. 查询参数
- description: used for calc
  in: query
  name: val1
  required: true
  type: integer
  1. 请求体参数
- description: Add account
  in: body
  name: account
  required: true
  schema:
    $ref: '#/definitions/model.AddAccount'
  1. 表单参数(文件上传):
- description: account image
  in: formData
  name: file
  required: true
  type: file
  1. Header参数
- description: Authentication header
  in: header
  name: Authorization
  required: true
  type: string

安全认证配置

Swagger支持多种认证方式,示例中展示了丰富的安全配置:

securityDefinitions:
  ApiKeyAuth:
    in: header
    name: Authorization
    type: apiKey
  BasicAuth:
    type: basic
  OAuth2AccessCode:
    authorizationUrl: https://example.com/oauth/authorize
    flow: accessCode
    scopes:
      admin: Grants read and write access to administrative information
    tokenUrl: https://example.com/oauth/token
    type: oauth2

这些定义包括:

  • API Key认证
  • Basic认证
  • 多种OAuth2流程(授权码模式、隐式模式、密码模式等)

在实际API中,可以这样应用安全配置:

security:
- ApiKeyAuth: []
- OAuth2Implicit:
  - admin
  - write

响应状态码定义

良好的API文档应该明确定义各种可能的响应状态码。示例中展示了常见的HTTP状态码处理:

responses:
  "200":
    description: OK
    schema:
      $ref: '#/definitions/model.Account'
  "400":
    description: Bad Request
    schema:
      $ref: '#/definitions/httputil.HTTPError'
  "404":
    description: Not Found
    schema:
      $ref: '#/definitions/httputil.HTTPError'
  "500":
    description: Internal Server Error
    schema:
      $ref: '#/definitions/httputil.HTTPError'

实用示例

示例文件中还包含了许多实用的API示例,如:

  1. 枚举参数
- description: string enums
  enum:
  - A
  - B
  - C
  in: query
  name: enumstring
  type: string
  1. 数值验证
- description: int valid
  in: query
  maximum: 10
  minimum: 1
  name: int
  type: integer
  1. 字符串验证
- description: string valid
  in: query
  maxLength: 10
  minLength: 5
  name: string
  type: string

最佳实践总结

通过分析这个Swagger YAML示例,我们可以总结出一些API文档的最佳实践:

  1. 清晰的路径结构:使用/api/v1作为基础路径,便于版本管理
  2. 完整的模型定义:明确定义所有数据模型及其属性
  3. 详尽的参数说明:为每个参数提供描述、类型和验证规则
  4. 全面的响应定义:覆盖所有可能的响应状态码
  5. 合理的API分组:使用tags对相关API进行分组
  6. 多种认证方式支持:明确定义API支持的安全认证方式
  7. 丰富的示例:提供各种参数类型的示例,便于开发者理解

这个Swagger YAML示例文件展示了Swaggo/swag项目如何帮助开发者生成规范、完整的API文档。通过遵循这些规范,可以创建出既易于理解又便于测试的API文档,大大提高开发效率。

swag Automatically generate RESTful API documentation with Swagger 2.0 for Go. swag 项目地址: https://gitcode.com/gh_mirrors/sw/swag

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

在 Go 1.17 中,你可以使用 embed 包将静态文件嵌入到可执行文件中,因此可以将 Swagger UI 嵌入到 Go Web 项目中,而不需要单独部署 Swagger UI。 以下是在 Goland 项目中使用 Swagger 的步骤: 1. 安装 Swagger 相关依赖:在项目中添加 `github.com/swaggo/swag` 和 `github.com/swaggo/gin-swagger` 两个依赖库,可以使用以下命令: ``` go get -u github.com/swaggo/swag go get -u github.com/swaggo/gin-swagger go get -u github.com/swaggo/gin-swagger/swaggerFiles ``` 2. 在项目中添加 Swagger 注释:在需要生成 Swagger 文档的接口上添加注释,例如: ``` // @Summary 获取用户信息 // @Description 根据用户ID获取用户信息 // @Tags 用户管理 // @Produce json // @Param id path int true "用户ID" // @Success 200 {object} UserResponse // @Failure 400 {string} string "请求参数错误" // @Router /users/{id} [get] func GetUserByID(c *gin.Context) { // ... } ``` 3. 生成 Swagger 文档:在项目根目录下执行以下命令,生成 Swagger 文档: ``` swag init ``` 该命令会在项目中生成一个 `docs` 目录,其中包含了 Swagger 文档的 JSON 文件和 HTML 文件。 4. 在项目中嵌入 Swagger UI:在项目中添加一个 `swagger` 目录,并将 Swagger UI 的静态文件拷贝到该目录中。可以从 Swagger 官网(https://swagger.io/tools/swagger-ui/)下载最新的 Swagger UI 版本。 ``` ├── main.go ├── go.mod ├── go.sum ├── docs │ ├── docs.go │ ├── swagger.json │ └── swagger.yaml └── swagger ├── index.html ├── swagger-ui-standalone-preset.js ├── swagger-ui-standalone-preset.js.map ├── swagger-ui.css ├── swagger-ui.css.map ├── swagger-ui.js ├── swagger-ui.js.map └── swagger-ui.min.js ``` 5. 在项目中添加 Swagger UI 的路由:在项目中添加一个路由,将 Swagger UI 的 HTML 文件和静态文件提供给用户访问,例如: ``` router.GET("/swagger/*any", gin.WrapH(http.FileServer(http.Dir("./swagger")))) ``` 这样,用户可以通过访问 `/swagger/index.html` 来查看 Swagger 文档。 6. 启动项目并访问 Swagger UI:在 Goland 中启动项目,然后在浏览器中访问 `http://localhost:8080/swagger/index.html`,即可访问 Swagger UI 并查看文档。 需要注意的是,这种方式虽然可以将 Swagger UI 嵌入到可执行文件中,但是每次修改 Swagger UI 后都需要重新编译可执行文件,因此不建议在生产环境中使用。如果你需要在生产环境中使用 Swagger UI,建议单独部署一个 Swagger UI 服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

齐添朝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值