Openapi Array Of Objects Example


01: [
02:   {
03:     "title": "Harry Potter"
04:   },
05:   {
06:     "title": "The Great Gatsby"
07:   }
08: ]

If you happen to be working on or creating an OpenAPI spec there are chances you might need to represent either the request and or response body as an OpenAPI schema.

Depending on your experience it might take doing it a couple of times to get a hang of it. In this post, I am going to transform the above JSON into an OpenAPI request body structure.


01: openapi: 3.0.0
02: info:
03:   title: Sample spec
04:   version: 0.0.1
05: paths:
06:   /:
07:     post:
08:       summary: ...
09:       requestBody:
10:         content:
11:           application/json:
12:             schema:
13:               $ref: "#/components/schemas/Books"
14:       responses:
15:         "200":
16:           description: successful operation
17:           content:
18:             application/json:
19:               schema:
20:                 $ref: "#/components/schemas/Books"
21: 
22: components:
23:   schemas:
24:     Books:
25:       type: array
26:       items:
27:         anyOf:
28:           - $ref: "#/components/schemas/Book1"
29:           - $ref: "#/components/schemas/Book2"
30:     Book1:
31:       type: object
32:       properties:
33:         title:
34:           type: string
35:           example: "Harry Potter"
36:     Book2:
37:       type: object
38:       properties:
39:         title:
40:           type: string
41:           example: "The Great Gatsby"

First, we create the individual book objects thus converting {"title": "Harry Potter"} and {"title": "The Great Gatsby"} to Book1 which spans line 30 to 35 and Book2 which starts from line 36 to 41.

Looking at the JSON object we are trying to covert, you notice that both books object are in an array. To represent that array we create the Books: section which pulls in Book1 and Book2 on line 28 and 29 respectively, and that gives us an array of objects. We can then go ahead and use it in our requests or response as shown on lines 13 and 20.

Get Better At Variable Naming

Here is another article for you 😊 "The difference between a JWT and a bearer token"