JSON Schema and OpenAPI can seem similar but have different use-cases.

Image for post

To begin, how JSON Scheme and OPenAPI differ? Well, in contrast to JSON Schema, an OpenAPI document is a definition for an entire API, not just data models. One might compare JSON Schema with the OpenAPI data model.

Why the need to validate JSON?

There are a plethora of use-cases, but let me explain why I use it:

Enter the world of Kubernetes and you’ll find yourself surrounded by object manifests which are either defined as YAML or JSON. But having to maintain thousands of such manifests can be a nightmare if your code is repeated. Languages likejsonnet, a lazy data templating language by Google, let you DRYup (Don’t Repeat Yourself) the configuration code. The jsonnet spits JSON, offers template reuse, processes a code only if it is required. So not only does it give you a performance boost, it also takes away a big percentage of maintenance.

Good, now we have a lot of code written in jsonnet which generates JSON based manifests. Going forward, as custom JSON objects grow, we need some way to validate inputs and auto-document. This is when you would use OpenAPI.

JSON Schema

JSON schema, as defined at json-schema.org, is a powerful tool for validating the structure of JSON data.

At its heart, JSON is built on the following data structures:

  • **object**: for example { "key1": "value1", "key2": "value2" }
  • **array**: for example [ "first", "second", "third" ]
  • **numbers**: for example 423.1415926
  • **string**: for example "This is a string"
  • **boolean**: for example true and false
  • **null**: for example null

These types have analogs in most programming languages, though they may go by different names.

In JSON Schema, an empty object, **{}**, is a completely valid schema that will accept any valid JSON (any object, number, string, etc). You can also use true in place of empty object to represent a schema that matches anything, or false for a schema that matches nothing.

The most common thing to do in a JSON schema is to restrict to a specific type. The **type** keyword is used for that. For example,

{ "type": "string" }

The type keyword may either be a string or an array (in which case the JSON snippet is valid if it matches any of the given types).

{ "type": ["number", "string"] }

Since JSON Schema is itself JSON, it’s not always easy to tell when something is JSON Schema or just an arbitrary chunk of JSON. The **$schema** keyword is used to declare that something is a JSON Schema. It’s generally a good practice to include it, though it is not required.

{ "$schema": "http://json-schema.org/schema#" }

It is also best practice to include an **$id** property as a unique identifier for each schema. You can just set it to a URL at a domain you control, for example,

{ "$id": "http://yourdomain.com/schemas/myschema.json" }

#json #kubernetes #json-schema #validation #openapi-specification

JSON Schema vs. OpenAPI
7.15 GEEK