JSON (JavaScript Object Notation) is the de facto standard for API data exchange because it is flexible and schema-less. However, when building robust applications, accepting schema-less data is a massive security and stability risk. You must ensure the incoming JSON has the correct fields, and that those fields are of the correct data type.
Instead of writing dozens of manual 'if/else' statements in your code to check if a field exists or if an age is an integer greater than zero, developers use JSON Schema. JSON Schema is a declarative vocabulary that allows you to define the exact required structure of your JSON data using JSON itself.
Defining types and constraints
A JSON Schema defines the expected properties of an object. You can declare that the 'username' property must be a string, and the 'age' property must be an integer. Crucially, it goes beyond basic types to enforce data constraints.
For example, you can specify that a string must match a specific Regular Expression (like an email format), or that an integer must have a 'minimum' of 18 and a 'maximum' of 120. If an API payload arrives with an age of 17, the schema validator automatically rejects it before it ever touches your application logic.
Required properties and additional fields
By default in JSON Schema, all defined properties are optional. You must explicitly declare an array of 'required' properties. If the incoming payload is missing any of the keys listed in the 'required' array, validation fails.
Furthermore, security best practices dictate setting the 'additionalProperties' boolean to false in your schema. This prevents clients from sending unexpected fields in the JSON payload (like malicious database injection attempts or administrative flags) that your application was not designed to handle.