Take advantage of scripts in Postman to save your time

Hùng Trần - Oct 3 - - Dev Community


effectively utilizing Postman scripts

In my work process, using Postman script to test API terminals is almost indispensable in my work process. In this article, I will share a few good ways to optimize my time. you guys when testing the API.

Use scripts to create virtual data

When testing the API, you will need fake data sets to use as input data, perhaps passing in the request body, request param, or path variable, but you don’t want to have to change it manually. automatically randomize the value.

In Postman, there are already random functions that help you automatically create fake value sets. All we need to do is take them out to use, you can see below.

{
    "name": "{{$randomFullName}}",
    "gender": "MALE",
    "first_name": "{{$randomWord}}",
    "last_middle_name": "{{$randomWord}}",
    "identify_number": "{{$randomBankAccount}}",
    "permanent_address": "{{$randomStreetAddress}}",
    "self_description": "{{$randomWords}}",
    "bank_account_holder": "{{$randomBankAccountName}}",
    "bank_account_number": "{{$randomBankAccount}}",
    "bank_code": "{{$randomBankAccount}}",
    "bank_name": "{{$randomBankAccountName}}",
    "tax_code": "{{$randomBankAccount}}"
}
Enter fullscreen mode Exit fullscreen mode


using random method in the Postman tool

Or instead of using Postman’s built-in random functions, you can write your own function and create your own variables to use for your needs.

Random phone number

const prefixes = ['03', '05', '07', '08', '09']; 
const randomPrefix = prefixes[Math.floor(Math.random() * prefixes.length)]; 
let phoneNumber = randomPrefix + Math.random().toString().slice(2, 10); 
pm.environment.set("randomPhoneNumber", phoneNumber); 
console.log("Random phone number:", phoneNumber);
Enter fullscreen mode Exit fullscreen mode


random phone number script

Random full name

const lastNames = ["Nguyễn", "Trần", "Lê", "Phạm", "Hoàng", "Huỳnh", "Phan", "Vũ", "Võ", "Đặng", "Bùi", "Đỗ", "Hồ", "Ngô", "Dương", "Lý", "Đào", "Đoàn", "Đinh", "Lương"]; 
const firstNames = ["An", "Bình", "Châu", "Duy", "Giang", "Hải", "Hà", "Hạnh", "Hiếu", "Hoàng", "Huy", "Khoa", "Lan", "Linh", "Long", "Minh", "Nam", "Nga", "Nhi", "Như", "Phong", "Phương", "Quân", "Quốc", "Sơn", "Thảo", "Thành", "Thu", "Thủy", "Tiến", "Trang", "Trung", "Tùng", "Tú", "Tuấn", "Uyên", "Vân", "Việt", "Xuân", "Yến"]; 
function generateRandomFullName() { 
  const randomLastNameIndex = Math.floor(Math.random() * lastNames.length); 
  const randomFirstNameIndex = Math.floor(Math.random() * firstNames.length); 
  const fullName = lastNames[randomLastNameIndex] + " " + firstNames[randomFirstNameIndex];
 return fullName; 
} 
const randomFullName = generateRandomFullName(); 
pm.environment.set("randomFullName", randomFullName); 
console.log("Random full name:", randomFullName);
Enter fullscreen mode Exit fullscreen mode


random full name script

Random email

const domains = ["gmail.com", "yahoo.com", "hotmail.com", "outlook.com", "icloud.com", "aol.com", "protonmail.com", "mail.com", "zoho.com", "yandex.com"]; 
function generateRandomEmail() { 
  const randomUsername = Math.random().toString(36).substring(7); 
  const randomDomain = domains[Math.floor(Math.random() * domains.length)]; 
  const email = randomUsername + "@" + randomDomain; 
  return email; 
} 
const randomEmail = generateRandomEmail(); 
console.log("Random email:", randomEmail); 
pm.environment.set("randomEmail", randomEmail);
Enter fullscreen mode Exit fullscreen mode


random email script

Random gender

function generateRandomGender() { 
  const genders = ["MALE", "FEMALE", "OTHER"]; 
  const randomIndex = Math.floor(Math.random() * genders.length); 
  const randomGender = genders[randomIndex]; 
  return randomGender; 
} 
const randomGender = generateRandomGender(); 
pm.environment.set("randomGender", randomGender); 
console.log("Random gender:", randomGender);
Enter fullscreen mode Exit fullscreen mode


random gender script

You can reuse the above scripts or optimize them according to your actual needs.

Write a script to get data from the response and transmit it to other APIs

Now after getting the results from the API, you want to throw some values ​​from response API A to the request body or request param of API B, C, D, E, or something else to call again, but you don’t want to. Copying manually by hand it is very tiring.

The most effective way is to write functions to extract data from the response, then pass the extracted value results into parameter variables, and then use these parameter variables on the APIs that need to be called.

Some use cases you can often use are:

Get access token from login API

The example below is the resulting JSON string after making a call to the login API:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMzjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYyMzkwMjIsInJvbGUiOiJ1c2VyIn0.DeOXN2oxXntRklB5A9IMop0EXo-qYpBJE7Je9y06X5o",
    "token_type": "Bearer",
    "expires_in": 3600,
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJlreHAiOjE1MTYyMzkwMjIsInJvbGUiOiJ1c2VyIn0.S8EoXZBk7oG3K9TThlTMyhYO2XvE7YlzzI6xgJgrXhg",
    "scope": "read write",
    "user_id": "1234567890"
}
Enter fullscreen mode Exit fullscreen mode

Now you will need to write a function to get that access_token value and put it into another API to call

Go to the Tests tab in Postman to write the script below

console.log('Request:'+ pm.request.body.toString()) 
var jsonData = pm.response.json(); 
var accessToken = jsonData.access_token; 
pm.environment.set("accessToken", accessToken); 
console.log('Token:'+ accessToken)
Enter fullscreen mode Exit fullscreen mode

Now the access_token value from the login API has been passed into the variable accessToken, you just need to take it out and use it.


using variable accessToken

Get an array of a list of data

Just imagine, if you need to test 7 or 8 APIs continuously, each API needs data from the previous API. At that time, having to manually change each input data is a real torture.

Here, after successfully calling the first API, I get an array of values. Now the need is to get a list of results by field code, then pass this array of results into the second API, and you can implement it. declared as follows

Let’s say the JSON string below is the result of calling the API

{
    "data": [
        {
            "id": 1,
            "code": "org001",
            "name": "Organization A",
            "status": "ACTIVE"
        },
        {
            "id": 2,
            "code": "org002",
            "name": "Organization B",
            "status": "ACTIVE"
        },
        {
            "id": 3,
            "code": "org003",
            "name": "Organization C",
            "status": "INACTIVE"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

You can also go to the tab Teststo write js script as below:

let responseData = pm.response.json().data; 
if (Array.isArray(responseData)) { 
  let codes = []; 
  responseData.forEach(item => { 
    if (item && item.hasOwnProperty("code")) { 
      codes.push(item.code); 
      } 
    }); 
  pm.globals.set("envSegments", JSON.stringify(codes)); 
  console.log("Size envSegments: "+codes.length); 
  console.log("envSegments: " + JSON.stringify(codes)); 
} else { 
console.log("Trường data không phải là một mảng"); 
}
Enter fullscreen mode Exit fullscreen mode


script get list codes

And now in the API you need to use, you can take it out and use it similar to the above parts. Below is a sample request body snippet that I use. Please do not share the full request body but just stop at the part using variables. Okay, guys.


using variable envSegments

Originally published at https://cafeincode.com on March 24, 2024.

. . . . . .
Terabox Video Player