OpenAPI 3.0 Generic Data types

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'

Leave a Comment

tech