Validate API response against JSON Schema
Preconditions (2)
✅ Expected Result: The response body matches the JSON Schema and validation passes
pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); const userSchema = { type: 'object', required: ['id', 'name', 'email'], properties: { id: { type: 'integer' }, name: { type: 'string' }, email: { type: 'string', format: 'email' } } }; pm.test('Response matches JSON Schema', () => { pm.response.to.have.jsonSchema(userSchema); });
The first test checks that the response status code is 200, which means the request was successful.
The userSchema defines the expected structure of the JSON response: an object with id as an integer, name as a string, and email as a string in email format.
The second test uses Postman's built-in jsonSchema assertion to verify the response body matches this schema exactly.
This approach ensures the API returns data in the correct format and helps catch errors early.
Now add data-driven testing with 3 different user IDs (1, 2, 3) to validate their responses against the JSON Schema
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" }
},
required: ["name", "age"]
};
pm.test("Validate response schema", () => {
pm.response.to.have.jsonSchema(schema);
});const schema = {
type: "object",
properties: {
id: { type: "number" },
email: { type: "string" }
},
required: ["id", "email"]
};
pm.test("Check schema", () => {
pm.response.to.have.jsonSchema(schema);
});
The API response is {"id": 123, "email": "user@example.com"}. What is the likely problem?Pass the test and this pattern moves unknown