Audit Your API
Often when I’m working on a project, or even when I inherit and existing project, the first thing I look at is the API. It’ll give me insight as to how the payload is handled, what status codes to account for, what conventions are being followed, and more.
If you’re going to take on an existing project, it’s always a good idea to factor in an audit of the API, even if there is documentation.
Don’t always trust the API Documentation. Do an Audit.
A client may not like it, but it’s better to find out problems at the beginning versus finding them out later and not being able to manage expectations.
Postman Tests
If you’re not already using Postman, I recommend getting it, and even integrating into your tests with their CLI called newman
. Great way to spot errors, and unexpected behaviour.
1. Collection Tests
As a common rule, if you ever find yourself copying and pasting things, that is probably not the way to go. This just reinforces the DRY principle, Don’t Repeat Yourself.
If you organize your tests in folders, and if all your payload is JSON, then there is one consistent test that you can run for all endpoints, to make sure that if you hit an endpoint, it’s not returning 500 Error
with a bunch of error messages from the backend. This is the test I run for every endpoint:
// GET JSON DATA
const jsonData = JSON.parse(responseBody);// VALIDATE JSON
tests["Validate JSON - Body - Present"] = ((responseBody) !== undefined && (responseBody.length > 1))tests["Validate JSON - Response - Object"] = (typeof jsonData) === 'object';tests["Validate JSON - Header - Content-Type - JSON"] = postman.getResponseHeader("Content-Type").has('application/json');
To make sure this test is run for all your endpoints, create a New Collection, and click the three (…)
dots and go to Edit
, which will bring you to edit your collection.
In the Edit Collection modal, click the tab called Tests and copy and paste the code above.
Click Update, and now when we create any new tests under that folder it will run those tests as well as any other tests specific to that endpoint.
Small Plug. If you haven’t joined my email list yet, I’m working on a few courses that are going to be released later this year on JavaScript, React, NodeJS, Docker, and more. The first people will be given massive discounts when they are released.
2. Global Variable Functions
This is more of a hack of a solution, but if you ever found yourself writing the same functions over and over again for pre-scripts, tests, and overall http requests, then this is a great way to make functions globally accessible.
The first step is to define your function in JavaScript normally.
// Random Integer
(min, max) => Math.floor(Math.random() * (max - min + 1) + min)
Next we’ll take that function and go back to our Edit Collection > Tests and create a Global.
The code should look like this, which sets our function as a string:
pm.globals.set("RANDINT", "(min, max) => Math.floor(Math.random() * (max - min + 1) + min)");
Next we’re going to use that function with eval
in our tests and just output the value in a test.
// Globals
const randInt = eval(pm.globals.get("RANDINT"));// Init
const ourValue = randInt(1, 10);// Test
tests[`Validate '${ourValue}' Is Integer`] = typeof ourValue === 'number';
You’ll notice I’m using tests['My Test']
more so than the documentation offered by Postman. That’s just a personal preference for simpler code, but if you wanted to write the same test in the standard tests Postman defined, you would write it as:
// Globals
const randInt = eval(pm.globals.get("RANDINT"));// Init
const ourValue = randInt(1, 10);// Test
pm.test(`Validate '${ourValue}' Is Integer`, () => {
pm.expect(typeof ourValue).to.eq('number');
});
3. Test Snippets
This last one is taking advantage of Postman test snippets, but specifically in Mac OS. This might differ for windows, but note that this does have the potential of making Postman not work if not done correctly. I recommend doing a backup of the file we’re modifying.
UPDATE OCT/21/2019: If you want to know how to do this on Windows, check out Gopi Krishna’s article on how you can implement Postman Test Snippets on Windows.
To give you context on Postman test snippets, there are two places they exist, Pre-request Scripts
and Tests
.
Currently, there is no way to add your own snippets to Postman, but we’re going to change that. To make this more efficient, we’re going to use Visual Studio Code to modify the file.
File:
/Applications/Postman.app/Contents/Resources/app/js/vendor-shared.js
cd /Applications/Postman.app/Contents/Resources/app/js/;
open -a /Applications/Visual\ Studio\ Code.app vendor-shared.js;
Make Sure To Make A Backup
We’re modifying a core file for Postman, so it’s import you have a way to revert back if anything goes wrong.
cp /Applications/Postman.app/Contents/Resources/app/js/vendor-shared.js /Applications/Postman.app/Contents/Resources/app/js/vendor-shared.js.bak;
When we open up the file, it’ll be large, but the line we’re looking for starts with:
module.exports = [{"id":"get-env-var","name":"Get an environment variable", ...
What we’re going to do is copy the form of one of the array objects and include one of our own functions, that we can easily use multiple times.
Existing Sample Object
{
// unique id
"id": "get-env-var",
// name shown on postman
"name": "Get an environment variable",
// description not really shown in postman
"description": "Gets an environment variable",
// actual escaped code that is copied over
"code": "pm.environment.get(\"variable_key\");",
// where the code is shown, in Pre-Request Scripts and Tests
"validity":["prerequest","test"]
}
Now that we have the format, we’re going to create a new snippet that is visible on both the Pre-Scripts
and Tests
.
Our Function
{
"id": "rand-integer",
"name": "Random integer",
"description": "Generates random integer",
"code": "const randInt = eval(pm.globals.get(\"RANDINT\"));",
"validity":["prerequest","test"]
}
Now let’s minify the script:
{"id":"rand-integer","name":"Random integer","description": "Generates random integer","code":"const randInt = eval(pm.globals.get(\"RANDINT\"));","validity":["prerequest","test"]}
Add it to the end of the array in the vendor-shared.js
file:
...,{"id":"rand-integer","name":"Random integer","description":"Generates random integer","code":"const randInt = eval(pm.globals.get(\"RANDINT\"));","validity":["prerequest","test"]}]
Save our file and now restart Postman. We should now see under Pre-Request Scripts
and Tests
our snippet. You just need do a one-click of our new Random Integer
snippet.
If you got value from this, and/or if you think this can be improved, please let me know in the comments.
Please share it on twitter 🐦 or other social media platforms. Thanks again for reading. 🙏
Follow me on twitter: @codingwithmanny and instagram at @codingwithmanny.