Sharing tips and tricks with others in the Postman community

Loosely Detecting Headers

Whilst testing a collection of APIs recently I found myself in a situation whereby I needed to detect if the response was JSON - pretty straight forward really in the grand schema of things. Postman has the pm.response.headers collection and the has method. However, that’s quite strict and uses exact matching. Some of the responses I was dealing with where inconsistent in their Content-Type values. e.g.

Content-Type: application/json
Content-Type: application/json;charset=utf-8

At the time of writing there was no .contains() method, so I had to improvise and came up with the following:

const isJsonResponse = (pm.response.headers.filter((header) => header.value.indexOf('application/json') !== -1).length > 0);

if (isJsonResponse) { 
	... do stuff ... 
}

A JavaScript dev I know, improved upon the snippet using object destructing, making it:

const isJsonResponse = pm.response.headers.filter(({headerValue}) => headerValue.indexOf('application/json') > -1).length;

It’s probably not going to change your life, but it’s something to keep in the tool box.

Oh, and one more thing!

The reason I needed a JSON detection snippet was because I was validating the JSON Schema of the API response. If you’re lazy like me, I can totally recommend a free tool for generating the JSON Schema from existing JSON over at Quicktype IO. Paste your JSON on the left hands side, and choose JSON Schema from the languages drop-down, thus:

https://app.quicktype.io?share=GxkZCPp7lZ1g3NpWhS6j.

4 Likes