paint-brush
Defining Types: Using allOf in Swagger JSON by@heypran
5,857 reads
5,857 reads

Defining Types: Using allOf in Swagger JSON

by Pran B.May 10th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

AllOf is an array of object definitions that are used for independent validation but together compose a single object. The data provided by the client must be valid against all of the given subschemas - source: Devanath from Pixabay. The allOf keyword is used to extend an already defined type 'AnyArticleSchema', by adding one more property 'articleRank' to it. You may use these in scenarios where you don't want to repeat the whole Schema and existing Schema is already being used in many places.
featured image - Defining Types: Using allOf in Swagger JSON
Pran B. HackerNoon profile picture

Image by Devanath from Pixabay 

This is a very short article just to give a highlight on how to use allOf with swagger in JSON, although its not a big deal but I could not really find a good example while searching for it.

So here you go,

OpenAPI lets you combine and extend model definitions using the allOf keyword. allOf takes an array of object definitions that are used for independent validation but together compose a single object. To be valid against allOf, the data provided by the client must be valid against all of the given subschemas.  - source

So if you want to use allOf within an array you may do it like this,

 "V1ListArticle": {
        "type": "array",
        "description": "List of articles",
        "items": {
          "allOf": [
            {
              "$ref": "#/components/schemas/AnyArticleSchema"
            },
            {
              "type": "object",
              "properties": {
                "articleRank": {
                  "type": "number"
                }
              }
            }
          ]
        }

In the above example we have extended an already defined schema type 'AnyArticleSchema', by adding one more property 'articleRank' to it.

You may use these in scenarios where you don't want to repeat the whole schema and existing schema (in this case AnyArticleSchema) is already being used in lot of places ( i.e. has dependency). So you may want to extend the schema for your new use case by adding a new property.

Cheers! Happy Swagging!