JSON Schema Validation
Postman supports the validation of JSON Schema using scripts. Let us discuss how to validate JSON schema in Postman:
Step 1: Install the Json schema library
You can install the library using the following command:
pip install jsonschema
Step 2: Create a JSON Schema
Create a simple JSON Schema file named schema.json that describes the structure we want our JSON data to have:
Javascript
{ "$schema" : "http://json-schema.org/draft-07/schema#" , "type" : "object" , "properties" : { "name" : { "type" : "string" }, "age" : { "type" : "integer" , "minimum" : 0 }, "email" : { "type" : "string" , "format" : "email" } }, "required" : [ "name" , "age" ] } |
This schema defines an object with properties name (string), age (integer with a minimum value of 0), and an optional email (string with email format). The required keyword specifies that name and age are mandatory properties.
Step 3: Create a JSON Document
Create a JSON document named data.json that we want to validate against the schema:
Javascript
{ "name" : "Krishna Gupta" , "age" : 20, "email" : "krishna.gupta@example.com" } |
Step 4: Validate JSON Document against Schema in Python
Write a Python script to validate the JSON document against the JSON schema using the jsonschema library:
Python
import json from jsonschema import validate, ValidationError # Load JSON Schema with open ( "schema.json" ) as schema_file: schema = json.load(schema_file) # Load JSON Document with open ( "data.json" ) as data_file: data = json.load(data_file) # Validate try : validate(instance = data, schema = schema) print ( "Validation successful! The document is valid." ) except ValidationError as e: print (f "Validation failed. Error: {e.message}" ) |
Step 5: Run the Python Script
Save the script in a file, for example, validate_json.py, and run it using the following command:
python validate_json.py
Note:
- Ensure that the necessary npm packages are installed by running `npm install ajv` in the Postman Script’s sandbox.
- Adjust the script as needed based on your specific JSON Schema and API response structure.
- Remember to customize the script according to your specific requirements and JSON Schema.
What is Json Schema and How to Validate it with Postman Scripting?
JSON stands for JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
- It is often used to transmit data between a server and a web application.
- It supports data structures like arrays and objects and JSON documents that are rapidly executed on the server.