OpenAPI 3.0 Generic Data types

2020-04-02 09:35发布

问题:

How can I best describe a generic response type which includes the real data type in OpenAPI 3.

Simplified example:

ApiResponse:
  data: object
  error: string

But the /users endpoint should give:

ApiResponse<List<User>>

So that basically is:

ApiResponse:
  data: List<User>
  error: string

It looks like this is not possible at the moment, but just want to make sure. I guess the best way to do this now is to make named responses for every call and use allOf to refer to ApiResponse and implemenent data: specific value.

回答1:

I search for generic types much time, but there is no way to define a generic type in OpenAPI3. The simplest way is using allOf and $ref at the same time. Suppose there is a list schema as follow:

List:
   type: object
   properties:
       page_number:
          type: integer
       page_count:
          type: integer

And the book schema is

Book:
   type: object
   properties:
       title:
          type: string
       summary:
          type: string

To return a list, the path is:

  /api/v1/books:
      get:
        responses:
          default:  
            description: description text
            content:
              application/json:
                schema:
                  allOf:
                    - $ref: '#/components/schemas/List'
                    - type: object
                      properties:
                        items: 
                          type: array
                          items: 
                            $ref: '#/components/schemas/Book'

Thie result is

   {
        "page_number": 1,
        "page_count": 10,
        "items": [{
            "title": "title",
            "description": ""
        },
        ... ]
    }

Actually, this is a list of books. As you can see, you add main attributes of the list to the result and list item type at the same time. You can repeat this pattern for others too:

  /api/v1/authors:
      get:
        responses:
          default:  
            description: description text
            content:
              application/json:
                schema:
                  allOf:
                    - $ref: '#/components/schemas/List'
                    - type: object
                      properties:
                        items: 
                          type: array
                          items: 
                            $ref: '#/components/schemas/Author'


回答2:

Well, you can use type object with additionalProperties with true value to get free form objects.