How can I describe complex json model in swagger

后端 未结 1 853
小蘑菇
小蘑菇 2020-12-24 12:13

I\'m trying to use Swagger to describe web-api I\'m building. The problem is that I can\'t understand how to describe complex json object?

For example, how to descri

相关标签:
1条回答
  • 2020-12-24 12:35

    Okay, so based on the comments above, you want the following schema:

    {
      "definitions": {
        "user": {
          "type": "object",
          "required": [ "name" ],
          "properties": {
            "name": {
              "type": "string"
            },
            "address": {
              "type": "array",
              "items": {
                "$ref": "#/definitions/address"
              }
            }
          }
        },
        "address": {
            "type": "object",
            "properties": {
                "type": {
                    "type": "string",
                    "enum": [ "home", "office" ]
                },
                "line1": {
                    "type": "string"
                }
            }
        }
      }
    }
    

    I've made a few assumptions to make the sample a bit more complicated, to help in the future. For the "user" object, I've declared that the "name" field is mandatory. If, for example, you also need the address to be mandatory, you can change the definition to "required": [ "name", "address" ].

    We basically use a subset of json-schema to describe the models. Of course not everyone knows it, but it's fairly simple to learn and use.

    For the address type you can see I also set the limit to two options - either home or office. You can add anything to that list, or remove the "enum" entirely to remove that constraint.

    When the "type" of a property is "array", you need to accompany it with "items" which declares the internal type of the array. In this case, I referenced another definition, but that definition could have been inline as well. It's normally easier to maintain that way, especially if you need the "address" definition alone or within other models.

    As requested, the inline version:

    {
      "definitions": {
        "user": {
          "type": "object",
          "required": [
            "name"
          ],
          "properties": {
            "name": {
              "type": "string"
            },
            "address": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "type": {
                    "type": "string",
                    "enum": [
                      "home",
                      "office"
                    ]
                  },
                  "line1": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题