Validate JSON response schema for user data API
Preconditions (2)
✅ Expected Result: The response JSON matches the schema with correct data types and required fields
Jump into concepts and practice - no test required
const schema = {
type: 'object',
required: ['id', 'name', 'email'],
properties: {
id: { type: 'integer' },
name: { type: 'string' },
email: { type: 'string', format: 'email' }
}
};
pm.test('Status code is 200', () => {
pm.response.to.have.status(200);
});
pm.test('Response matches user schema', () => {
pm.response.to.have.jsonSchema(schema);
});The schema variable defines the expected JSON structure with required fields and their types.
The first test checks that the response status code is 200, ensuring the request was successful.
The second test uses Postman's built-in to.have.jsonSchema method to validate the response body against the schema.
This approach keeps tests clear and maintainable by separating schema definition and assertions.
Now add data-driven testing with 3 different user IDs to validate their responses against the schema
schema variable?pm.response.to.have.jsonSchema(schema); to validate JSON schema.{
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"}
},
"required": ["id", "name"]
}{"id": 10, "name": "Alice"}?const schema = {
type: "object",
properties: {
age: { type: "integer" }
},
required: ["age"]
};
pm.test("Schema is valid");
pm.response.to.have.jsonSchema(schema);age. What is the likely error?pm.test("name", () => { assertion }); but the code calls pm.test("Schema is valid"); without the required callback function.pm.response.to.have.jsonSchema(schema); is outside the pm.test callback and will not be properly associated with the test.pm.test callback, but the code uses pm.test incorrectly -> Option Aid (integer) and optional email (string). Which JSON schema correctly validates this response array?