Postman - Yash-777/MyWorld GitHub Wiki

By using pre-request scripts we can change the variable values, parameters, headers, and body data before a request runs by execting JavaScript.

Post URL : http://postman-echo.com/post Code tested in Postman-win64-8.12.4-Setup

Request Body - raw

Writing pre-request scripts Images

{
    "locale": "en_US",
    "key"   : "{{dynamic_key}}",
    "value" : "{{dynamic_val}}"
}

pm.collectionVariables.set("dynamic_key", "key1");
pm.collectionVariables.set("dynamic_val", "val1");

console.log('Add variable to JSON body', pm.request.body);

Important

pre-request script in Postman that removes comments (uses a regular expression to remove both single-line (//) and multi-line (/* */)) from a JSON payload:

You can add pre-request scripts to entire collections and folders within collections. In both cases, your pre-request script will run before every request in the collection or direct child request in the folder. This allows you to define commonly used pre-processing or debugging steps you need to execute for multiple requests.

pre-request scripts: to entire collections and folders within collections. Remove Comments in payload
// Get the Content-Type header value
var contentTypeHeader = pm.request.headers.get('Content-Type');

// Check if the Content-Type is JSON
if (contentTypeHeader && contentTypeHeader.includes('application/json')) {
    // Get the current request body
    var requestBody = pm.request.body;

    // Check if the request body is in raw mode
    if (requestBody && requestBody.mode === 'raw') {
        // Remove comments from JSON payload
        var sanitizedBody = removeCommentsFromJSON(requestBody.raw);

        // Set the modified payload back to the request body
        pm.request.body.raw = sanitizedBody;
    }
}

// Function to remove comments from JSON
function removeCommentsFromJSON(jsonString) {
    // Use regular expression to remove single-line and multi-line comments
    var sanitizedJSON = jsonString.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '');

    return sanitizedJSON;
}
pre-request scripts: Remove Comments in payload and update payload with by adding properties
// Parse the JSON string from the request body
let jsonStr_withoutComments = removeCommentsFromJSON(pm.request.body.raw);
let jsonObj = JSON.parse( jsonStr_withoutComments );

// Add or update the property
jsonObj["companyId"] = "VorwerkTMPL";

// Convert the JSON object back to a string
pm.request.body.raw = JSON.stringify(jsonObj);

 // Function to remove comments from JSON
function removeCommentsFromJSON(jsonString) {
    // Use regular expression to remove single-line and multi-line comments
    var sanitizedJSON = jsonString.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '');

    return sanitizedJSON;
}

postman - how to generate random number in specific range?

Pre-req
pm.collectionVariables.set ("random_Number_per_Request", _.random (1,1000));

Body
"randomNumber": "{{random_Number_per_Request}}",

Add Query Params GET: ps://postman-echo.com/get

pm.request.addQueryParams("foo=bar");

Adding Variable to JOSN Body POST: http://postman-echo.com/post

// Setting the "Signature" collection variable to "encryption"
pm.collectionVariables.set("Signature", "encryption");

TESTS - EnvironmentVariable

postman.setEnvironmentVariable("token", postman.getResponseHeader("authorization"));

Header:
Authorization: {{token))
Request Authorization Headers Body Formdata Tests
POST No Auth

content-type 
: 
application/x-www-form-urlencoded
  

    User Name: XXXXX
    Password:  XXXXX

var a = pm.response.headers.get("Set-Cookie");
pm.environment.set("session ID", a);
pm.test("response is ok", function () {
    pm.response.to.have.status(200);
});

postman.setEnvironmentVariable("token", postman.getResponseHeader("authorization"));

GET | POST Inherit Auth from parent

content-type : application/json
Cookie : {{session ID}}

Authorization : {{token}}

- -


⚠️ **GitHub.com Fallback** ⚠️