How to validate API body in python using ‘JSON schema’

Akhil Chaudhary
VectoScalar
Published in
2 min readJan 23, 2023

JSON Schema is a way to define the structure and data types of a JSON object, using a JSON document. It can be used to validate the request body of an API endpoint before the request is processed. Here is a step-by-step guide to creating a JSON Schema for validating the request body of an API endpoint:

Define the structure of your JSON object:

1: Determine the keys and values that should be present in the JSON object.

For example, suppose a JSON object with user info like name, email and age.

2: Decide on the data types for each value (e.g. string, number, boolean, etc.).

Here, name and email is a string and age will be a number.

3: Create a JSON Schema document:

Start the document with {"type": "object"} to specify that it is a JSON object.

Add a properties field, which is an object containing the keys and values of the JSON object you defined in step 1.

For each key-value pair, specify the data type using the type field.

Optionally, you can add additional constraints using the required, minimum, maximum, and other fields. You can also add apattern field to validate a specific regex pattern.

Here, constraints will be minimum: 12 and maximum: 60 for age and a regex pattern to validate the email, wherein name and email are required properties.

In the above example, after grouping all these properties we get:

JSON Schema document

Use a JSON Schema validation library to validate the request body:

1Choose a JSON Schema validation library for your programming language (e.g. jsonschema for python or ajv for JavaScript).

For example, We will be using the jsonschema lib for python. Use the following command to install it:

pip install jsonschema

2Use the library to validate the request body of your API endpoint against the JSON Schema.

The following code will give you an idea of how to pass a JSON object to the validator:

Simple function to validate a JSON object

The above function takes the following parameters:

json_data: The incoming data that is yet to be validated. The API JSON body is passed into this parameter.

{"name": "John Doe", "email": "john@doe.com", "age": 11}

schema: The schema that is used to validate incoming data as given above.

The above function returns:

[True]:When the data is validated without any errors and is correct.

[False, "error message"]:When the incoming data is not correct.

For more information on this library, read the documentation.

Conclusion:

In summary, using a JSON schema validation library like jsonschema can offer several benefits when validating the request bodies of an API, including standardized validation, ease of use, increased reliability, and greater flexibility. These benefits can help to make your API more reliable and easy to use and can reduce the amount of code you need to write.

--

--