Skip to content

Instantly share code, notes, and snippets.

@carlbray
Last active April 30, 2023 21:48
Show Gist options
  • Save carlbray/ffacfbe7c54ddada38ac5551befd4774 to your computer and use it in GitHub Desktop.
Save carlbray/ffacfbe7c54ddada38ac5551befd4774 to your computer and use it in GitHub Desktop.
Sharing functions in Postman

Background

This Gist shows you how to create reusable function which you can access anywhere in your Postman collection.

Good practice when programming is to keep your code DRY (Don't repeat yourself). You should also apply this principle when writing Postman collections for API testing.

Example function

In this example we're going to write a common logging function which just logs to the console. In the future we might want to log somewhere else, so using a common function will allow us to redirect the logging from just one place.

Our simple logging function looks like:

const log = (msg) => {
    console.log(msg);
}

To use it you only need to write:

log(“Hello World!”)

You could add this function to a test script in Postman and it would work within the scope of your test. However if you want to use it in another test you'd have to copy and paste it to the other test. So you end up repeating yourself again.

Making it available to the collection

To make your function available outside of just the test scope you should add it to the collections Pre-request script

One way is to extend the base Object class with your new function using the prototype property.

You do this by adding your function to the Object.prototype like so:

Object.prototype.log = (msg) => {
    console.log(msg);
}

You can then use your function in any scope using underscore _

_.log(“Hello World!”)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment