3
votes

I am using swagger-ui version 2.2.8

Our existing API can produce application/json as well as application/xml.
For a single record result in json it produces:

{
  "person": {
    "id": 23,
    "name": "John"
  }
}

and for XML it produces:

<person>
  <id>23</id>
  <name>John</name>
</person>

My swagger-schema for this is:

 {
    "person": {
        "type": "object",
        "properties": {
            "person": {
                "$ref": "#/definitions/personfields"
            }
        }
    }
}

When viewed in swagger-ui the json model is looking fine. However the XML-model becomes:

<person>
  <person>
    <id>1</id>
    <name>string</name>
  </person>
</person>

Is there a way to prevent this double <person> but still get the correct JSON result?

1

1 Answers

0
votes

In OpenAPI terms, your JSON and XML models are different – the JSON version of

<person>
  <id>23</id>
  <name>John</name>
</person>

would be

{
  "id": 23,
  "name": "John"
}

without the wrapper property person.

You can't have a single schema for models that differ in this way.


What you can do is define your model as a free-form object (type: object without properties) and specify the JSON/XML response examples instead – but in this case you lose the ability to define the object properties.

definitions:
  person:
    type: object

paths:
  /person:
    get:
      produces:
        - application/json
        - application/xml
      responses:
        200:
          description: OK
          schema:
            $ref: '#/definitions/person'
          examples:
            application/json: |
              {
                "person": {
                  "id": 23,
                  "name": "John"
                }
              }
            application/xml: |
              <person>
                <id>23</id>
                <name>John</name>
              </person>              

Note: If you use Swagger UI, use version 3.0.x becase 2.2.x does not display such examples correctly.


In the next version – OpenAPI 3.0 (which is RC at the moment of writing) – it will be possible to specify different schemas for different response MIME types. So in 3.0 your example will be described as:

paths:
  /person:
    get:
      responses:
        '200':
          description: OK
          content: 
            application/json:
               $ref: '#/components/definitions/PersonJson'               
            application/xml:
               $ref: '#/components/definitions/Person'

components:
  definitions:

    # XML object schema
    Person:
      type: object
      properties:
        id:
          type: integer
          example: 23
        name:
          type: string
          example: John
      xml:
        name: person

    # JSON object schema with a wrapper property "person"
    PersonJson:
      type: object
      properties:
        person:
          $ref: '#/components/definitions/Person'