Horje
Implement Global Functions in Postman

Postman is a tool for API development that allows developers to create global functions which allows you to define reusable code snippets that can be shared across multiple requests and collections. In this article, we’ll explore how to write global functions in Postman and use them to enhance your API testing workflows.

Global Functions in Postman

Global functions in Postman are JavaScript functions that can be defined at the collection, folder, or global scope. These functions can perform various tasks, such as generating dynamic data, parsing responses, extracting values, or performing validations. By encapsulating common logic into global functions, you can simplify your test scripts, improve code reusability, and maintain consistency across your API tests.

Using Pre-request Scripts

Pre-request scripts, executed before sending a request in Postman, serve as a prime avenue for defining global functions.

Syntax:

// Define a function in the pre-request script
pm.globals.set("function_name", function() {
    // Function logic here
});

Example

Let’s create a function to generate an authentication token within the pre-request script:

// Define a function to generate an authentication token
pm.globals.set("generatedToken", function () {
    // Logic to generate token
    return "generated_token";
});
console.log(pm.globals.get("generatedToken"));
pm.sendRequest({
    url:'https://jsonplaceholder.typicode.com/todos',
    method : 'GET',
    header : {
        'Authorization' : pm.globals.get(("generatedToken"))
    }
});

Steps to Implement Pre-request Scripts

  • Launch Postman and create a new request or collection.
  • Navigate to the “Pre-request Script” tab of the request or collection.
  • Compose the JavaScript code to define the global function.
  • Send the request or run the collection.
  • Inspect the request output or console for any logs or results generated by the global function.
i

Pre-requisites Scripts

Using Environment Variables:

Environment variables within Postman provides the storage of key-value pairs, allowing for the definition of JavaScript functions.

Syntax:

// Define a function within an environment variable
pm.environment.set("variable_name", function() {
    // Function logic here
});

Example

// Define a function to calculate a hash value
pm.environment.set("calculateHash", function(data) {
    return function(data) {
  console.log("Setting calculateHash function"); // Log for debugging
  const CryptoJS = require("crypto-js");
  // ... (function logic)
  return CryptoJS.SHA256(data).toString();
}});
// Access the function from an environment variable
var hashedData = pm.environment.get("calculateHash")("secret_data");
console.log(hashedData)

Steps to Implement Environment Variables

  • Open Postman and create a new request or collection.
  • Navigate to the “Variables” tab of the associated environment.
  • Specify an environment variable housing the JavaScript function.
  • Employ the function within the request or collection scripts.
  • Dispatch the request or execute the collection.
  • Review the request output or console for any generated logs or results by the global function.
en

Environment Variables

Using Collection Variables

Collection variables, similar to environment variables, store data and can house JavaScript functions.

Syntax:

// Define a function within a collection variable
pm.collectionVariables.set("variable_name", function() {
    // Function logic here
});

Example

Let’s create a function to format a date and store it in a collection variable:

// Define a function to format date
pm.collectionVariables.set("formatDate", function(){
   return function(date) {
   var moment = require('moment');
    return moment(date).format("YYYY-MM-DD");
}});

// Access the function from a collection variable
var formattedDate = pm.collectionVariables.get("formatDate")(new Date());
console.log(formattedDate);

Steps to Implement Collection Variables

  • Initiate Postman and generate a new request or collection.
  • Navigate to the “Variables” tab of the collection.
  • Define a collection variable housing the JavaScript function.
  • Utilize the function within the request or collection scripts.
  • Execute the request or run the collection.
  • Examine the request output or console for any logs or results generated by the global function.

cv

Collection Variables

Defining Functions in Collection Scripts

Collection scripts, executed before or after the entire collection run, offer a venue for defining global functions.

Syntax:

// Define a function in the collection script
function functionName() {
    // Function logic here
}

Example

Let’s define a function to log request details within the collection script.

// Define a function to log request details
function logRequestDetails(request) {
    console.log("Request URL:", request.url);
    console.log("Request Method:", request.method);
}

// Access the function from any request within the collection
logRequestDetails(pm.request);

Steps to Implement Collection Scripts

  • Launch Postman and produce a new request or collection.
  • Navigate to the “Pre-request Script” or “Tests” tab of the collection.
  • Construct the JavaScript function within the collection script.
  • Employ the function within any request or test scripts within the collection.
  • Dispatch the request or execute the collection.
  • Review the request output or console for any logs or results generated by the global function.
ls

Collection Scrips

Conclusion

Postman’s global functions helps you to reduce redundancy and promote code reusability, streamlining testing and automation workflows. By using pre-request scripts, environment and collection variables, or collection scripts, you can encapsulate common logic and enhance productivity and code quality.




Reffered: https://www.geeksforgeeks.org


Web Technologies

Related
npm mongoose npm mongoose
How to Optimize Images for WordPress? How to Optimize Images for WordPress?
Top 10 Angular features you should know Top 10 Angular features you should know
How to Speed Up WordPress Page Loading Time? How to Speed Up WordPress Page Loading Time?
Web3.0: The Next Era of the Internet Web3.0: The Next Era of the Internet

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13