Validate response with JSON schema in Postman

Postman’s test functionality can be used to validate that an API response conforms with a specific JSON schema. This is a great way to prevent accidental changes to the output, which could cause a lot of headache to the API consumers.

I’m not going to go into details on how to generate JSON schemas. You can either do it manually or by pasting a valid response into an online schema generator, like this one from Liquid Technologies (do not do this, if your response contains sensitive data).

Open your request and go to the test tab. Insert the following code (substitute your own JSON schema) into the code field in the test tab:

const schema = {
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
  },
  "required": [
    "name",
    "id"
  ]
}

pm.test("Validate schema", () =>{
    pm.response.to.have.jsonSchema(schema);
});

When you send your request with the test added, you should be able to see it in the list of test results. If it passes it will look like this (the test for status code and response time are separate tests):

If you have any suggestions on how to test your API with Postman, please leave a comment below.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s