首页 文章

如何在swagger中成功获取GET响应中的多种内容类型

提问于
浏览
2

假设我们有一个例子json swagger规范:

{
"swagger": "2.0",
"info": {
    "version": "1.0.0",
    "title": "Some API"
},
"basePath": "/api/v1",
"consumes": [
    "application/json"
],
"produces": [
    "application/json",
    "text/csv"
],
"paths": {
    "/some/endpoint": {
        "get": {
            "parameters": [
                {
                    "in": "body",
                    "name": "body",
                    "required": false,
                    "schema": {
                      "$ref": "#/definitions/BodyParamsDefinition"
                    }
                }
            ],
            "responses": {
                "200": { ?? } ...

可以生成两种内容类型:

  • application / json

  • text / csv

GET /some/endpoint 的默认响应是csv文件,但如果 format 查询参数像_2535727那样使用,则响应将采用json格式 .

我很难找到如何通过适当的回答完成我的规范 . 当我使用这种方法时:https://swagger.io/docs/specification/describing-responses/我收到验证错误: ...get.responses['200'] should NOT have additional properties

1 回答

  • 2

    你几乎就在那里,你只需要为响应定义一个 schema . 此 schema 定义与此状态代码关联的所有内容类型的响应结构 .

    例如,如果操作返回此JSON:

    [
      {
        "petType": "dog",
        "name": "Fluffy"
      },
      {
        "petType": "cat",
        "name": "Crookshanks"
      }
    ]
    

    这个CSV:

    petType,name
    dog,Fluffy
    cat,Crookshanks
    

    你会用:

    # YAML
    responses:
      200:
        description: OK
        schema:
          type: array
          items:
            type: object
            properties:
              petType:
                type: string
              name:
                type: string
    

    更多信息:Describing Responses

    在OpenAPI 3.0中,内容类型定义得到了改进,模式可能因内容类型而异:

    openapi: 3.0.0
    ...
    
    paths:
      /some/endpoint:
        get:
          responses:
           '200':
              description: OK
              content:
                # JSON data is an object
                application/json:
                  schema:
                    type: object
                    properties:
                      message:
                        type: string
                # CSV data is a string of text
                text/csv:
                  schema:
                    type: string
    

    GET / some / endpoint的默认响应是csv文件,但如果使用格式查询参数,如/ this / endpoint?format = json,则响应将采用json格式 .

    目前无法将特定响应映射到特定操作参数,但OpenAPI规范存储库中有几个相关的提议:

相关问题