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 describe this objects:
{ name: "Jhon", address: [ { type: "home", line1: "1st street" }, { type: "office", line1: "2nd street" } ] }
A swagger:model annotation optionally gets a model name as extra data on the line. when this appears anywhere in a comment for a struct, then that struct becomes a schema in the definitions object of swagger. The struct gets analyzed and all the collected models are added to the tree.
Swagger uses an extended subset of JSON Schema to describe its models. Assuming you follow the same subset, you can just take the schema you have as-is and use them as part of the Swagger document (you can even $ref your own hosted files).
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" } } } } } } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With