V
V
Vitaly Khomenko2019-08-07 14:11:36
JSON
Vitaly Khomenko, 2019-08-07 14:11:36

How to describe a single REST API response format for everyone in Swagger OpenAPI3?

There are many controllers, all of them return a response in the same format:

{
  "response": true, # true/false
  "error": {
    "code": 0, # 0 или код ошибки
    "message": "" # текст ошибки
  },
  "data": null # null или данные ответа
}

All models of request forms, responses, headers, etc. are taken out into components and connected by $ref.
But it is not possible to combine the uniform response format with response data. Here is an example:
paths:
  /system/banner/{position}:
    get:
      # ...
      parameters:
        - name: position
          # ...
      responses:
        200:
          description: OK
          headers:
            # ...
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/responses/CommonResponse' # <-- Единый формат ответа
                  - properties: <-- # Он должен быть дополнен данными
                      data:
                        $ref: '#/components/schemas/BannerList'
        400:
          # ...

As a result, the swagger generates this:
{
  "data": [
    {
      "id": 0,
      "title": "string",
      "content": "string",
      "date_created": "2019-08-07T10:54:38.215Z",
      "date_edited": "2019-08-07T10:54:38.215Z"
    }
  ]
}

and you need it like this:
{
  "response": true,
  "error": {
    "code": 0,
    "message": ""
  },
  "data": [
    {
      "id": 0,
      "title": "string",
      "content": "string",
      "date_created": "2019-08-07T10:54:38.215Z",
      "date_edited": "2019-08-07T10:54:38.215Z"
    }
  ]
}

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
davidnum95, 2019-08-07
@iiifx

properties should be on the same level as allOf, like this:

allOf:
   - $ref: '#/components/responses/CommonResponse' # <-- Единый формат ответа
properties: <-- # Он должен быть дополнен данными
   data:
      $ref: '#/components/schemas/BannerList'

I
Ivan Shumov, 2019-08-07
@inoise

Handles. You know it's not REST, right?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question