Introduction to JavaScript in Postman
What is JavaScript
JavaScript is a popular programming language used to make web pages interactive and dynamic. It is widely used for:
● Creating interactive websites
● Handling user actions
● Sending and receiving data from APIs
● Automating tasks
● Validating data
JavaScript works in browsers as well as tools like .
Why JavaScript is Used in Postman
In , JavaScript is used to automate API testing and request handling.
JavaScript helps users to:
● Set dynamic request data
● Store and reuse values
● Validate API responses
● Automate workflows
● Perform calculations before sending requests
● Write test cases
This script stores a value inside an environment variable.
Postman Scripting Overview
Postman provides scripting features that allow users to execute JavaScript code during API execution.
Scripts are mainly used for:
● Automation
● API testing
● Data extraction
● Request chaining
Postman uses the pm API object for scripting.
These methods help interact with:
● Responses
● Variables
● Collections
● Environments
Pre-request Script vs Tests Tab
1. Pre-request Script
The Pre-request Script runs before the API request is sent.
It is used for:
● Generating tokens
● Creating dynamic timestamps
● Setting variables
● Preparing request data
2. Test Tab
The Tests script runs after receiving the API response.
It is used for:
● Validating response status
● Checking response data
● Writing test cases
● Extracting values from responses
Console Usage (console.log)
The console.log() function is used to print messages in the Postman Console.
It helps in:
● Debugging scripts
● Checking variable values
● Viewing execution flow
You can open the Postman Console from:
● View > Show Postman Console
This prints the complete API response in the console.
Example of a simple JavaScript statement:
let name = 'Raj'; console.log(name); let is used to create a variable 'Raj' is the value stored in the variable console.log() prints the output to the console
Example: Pre-request Script
let currentTime = new Date().toISOString();
pm.environment.set('time', currentTime);
Example: Test Tab
pm.test('Status code is 200', function () {
pm.response.to.have.status(200);
});
Example:Console Usage (console.log)
let username = 'admin'; console.log(username); Output: admin
Example with API response:
let response = pm.response.json(); console.log(response);
Difference Between Pre-request Script and Tests
Feature Pre-request Script Tests ---------------------------------------------------- Execution Time Before request After response Main Purpose Prepare request Validate response Common Usage Tokens, variables Assertions, validations
Summary:
JavaScript in helps automate API testing and scripting tasks. Using JavaScript in Pre-request Scripts and Tests makes API workflows faster, reusable, and efficient. The console.log() function is very useful for debugging and understanding script execution.