Skip to content

Instantly share code, notes, and snippets.

@rolroralra
Last active April 19, 2022 07:16
Show Gist options
  • Select an option

  • Save rolroralra/5a65d764ff6a853acbcfcbc278dd64f4 to your computer and use it in GitHub Desktop.

Select an option

Save rolroralra/5a65d764ff6a853acbcfcbc278dd64f4 to your computer and use it in GitHub Desktop.
Postman

Postman JavaScript Reference

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/


Postman Pre-Request POST Script

https://codecamper.me/blog/91/

pm.sendRequest({
    url: 'https://codecamper.me/auth',
    method: 'POST',
    header: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
        {
            key: "type", 
            value: "email", 
            disabled: false
        },
        {
            key: "email",
            value: "user@example.com",
            disabled: false
        },
        {
            key: "password",
            value: "string",
            disabled: false
        }
    ]
    }
}, function (err, res) {
    res_data = res.json()
    console.log(res_data)
    pm.request.headers.add({
        key: "Authorization",
        value: "Bearer " + res_data.accessToken
    });
});

Retry a failing request

How to retry a failing request

var expectedHttpStatus = 200;
var maxNumberOfTries = 3;
var sleepBetweenTries = 5000;

if (!pm.environment.get("collection_tries")) {
    pm.environment.set("collection_tries", 1);
}

if ((pm.response.code != expectedHttpStatus) && (pm.environment.get("collection_tries") < maxNumberOfTries)) {
     var tries = parseInt(pm.environment.get("collection_tries"), 10);
     pm.environment.set("collection_tries", tries + 1);
     setTimeout(function() {}, sleepBetweenTries);
     postman.setNextRequest(request.name);
 } else {
     pm.environment.unset("collection_tries");

     pm.test("Status code is " + expectedHttpStatus, function () {
         pm.response.to.have.status(expectedHttpStatus);
     });

     // more tests here...
    
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment