如何为Swagger中的内容类型:text/html的响应主体提供示例值(使用dredd进行测试)

Sha*_*r R 7 swagger apiary.io swagger-ui apiary swagger-2.0

我有一个API调用,响应200 OK并返回一个HTML.我想将此添加到我的API文档中(特别是因为我使用dredd验证它,除非我提供预期的响应体,测试失败).我怎么会在Swagger这样做?

---更多细节---我对API调用的响应是200 OK并且有一行响应正文:

<html><body>You are being <a href="https://my.domain.com/users/sign_in">redirected</a>.</body></html>

我可以使用以下格式轻松定义蓝图中的响应主体:

 + Response 302 (text/html; charset=utf-8)

     + Body

         `<html><body>You are being <a href="https://my.domain.com/users/sign_in">redirected</a>.</body></html>`
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在Swagger中做到这一点.我能找到的几乎所有例子都是针对应用程序/ json响应(可以理解),我无法猜测这种响应的正确语法.

我的文档中相关的招摇文本是这样的(到目前为止没有指定响应主体,因此空主体dredd失败,因为响应主体应该是<html><body>You are being <a href="https://my.domain.com/users/sign_in">redirected</a>.</body></html>):

# this is my API spec in YAML
swagger: '2.0'
info:
  title: My API (Swagger)
  description: blablabla
  version: "1.0.0"
# the domain of the service
host: my.domain.com
# array of all schemes that your API supports
schemes:
  - https
# will be prefixed to all paths
basePath: /
produces:
  - application/json; charset=utf-8
paths:
  /users/password:
    post:
      summary: Password Reset
      description: |
        Handles Reset password for existing user.
      consumes:
        - application/x-www-form-urlencoded
      produces:
        - text/html; charset=utf-8
      parameters:
        - name: "user[email]"
          description: email
          in: formData
          required: true
          type: string
          default: "user@gmail.com"
      tags:
        - Reset Password
      responses:
        200:
          description: Success
Run Code Online (Sandbox Code Playgroud)

如果您对此有任何建议,请发表评论.谢谢!

Sha*_*r R 10

弄清楚了.响应对象有一个名为"examples"的字段,允许显示API响应的示例.

语法清楚地显示在规范中,基本上说你需要为示例响应识别MIME类型,在我的例子中是text/html,值是实际文本.

像这样:

    responses:
      200:
        description: success and returns some html text
        examples:
          text/html: 
            <html><body>Your HTML text</body></html>
Run Code Online (Sandbox Code Playgroud)

而已.现在dredd是否知道拿这个值并比较它是另一个故事.他们的文档声明除JSON之外的任何响应都被验证为纯文本,因此这应该有效.

希望这有帮助.


小智 6

如果有人在 openapi 3.0 版本中需要这个,你可以这样做:

  • 保存您的 HTML。例如,在文件末尾给出以下内容:
components:
  schemas:
    error401:
      type: string
      example: '<html>HTML text</html>'
Run Code Online (Sandbox Code Playgroud)
  • 然后您可以在响应中的任意位置引用此方案。例如:
  responses:
    '401':
      description: Error
      content:
        text/html:
          schema:
            $ref: '#/components/schemas/error401'
Run Code Online (Sandbox Code Playgroud)