Postman - Yash-777/MyWorld GitHub Wiki
Variable scopes | |
---|---|
![]() |
Postman supports variables at different scopes, allowing you to tailor your processing to a variety of development, testing, and collaboration tasks. Scopes in Postman relate to the different contexts that your requests run in, and different variable scopes are suited to different tasks. |
You can set variables programmatically in your request scripts.
Method | Use-case | Example |
---|---|---|
pm.globals |
Use to define a global variable. | pm.globals.set("variable_key", "variable_value"); |
pm.collectionVariables |
Use to define a collection variable. | pm.collectionVariables.set("variable_key", "variable_value"); |
pm.environment |
Use to define an environment variable in the currently selected environment. |
pm.environment.set("variable_key", "variable_value"); |
pm.variables |
Use to define a local variable. | pm.variables.set("variable_key", "variable_value"); |
unset |
You can use unset to remove a variable. | pm.environment.unset("variable_key"); |
Pre-request Script Add variable to JSON body stackoverflow post
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 |
---|---|
|
|
|
|
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;
}
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");
postman.setEnvironmentVariable("token", postman.getResponseHeader("authorization"));
Header:
Authorization: {{token))
Request | Authorization | Headers | Body Formdata | Tests |
---|---|---|---|---|
POST | No Auth |
|
|
|
GET | POST | Inherit Auth from parent |
|
- | - |
-
Sending parameters [Query parameters(
?id=1&type=new
), Path parameters (/customer/:id
)]
Defining variables in scripts You can set variables programmatically in your request scripts.
Method Use-case Example pm.globals Use to define a global variable. pm.globals.set("variable_key", "variable_value"); pm.collectionVariables Use to define a collection variable. pm.collectionVariables.set("variable_key", "variable_value"); pm.environment Use to define an environment variable in the currently selected environment. pm.environment.set("variable_key", "variable_value"); pm.variables Use to define a local variable. pm.variables.set("variable_key", "variable_value"); unset You can use unset to remove a variable. pm.environment.unset("variable_key");
Input file Inbound_Logs.csv
"OBJECT ID","REQUEST"
"123", "{""json"":{""country"":""PL""}"
"234", "{""json"":{""country"":""PL""}"
Java Code to generate a Postman collection from a CSV file.
Java, you can use libraries like Apache POI for reading CSV files and Gson for JSON handling
Steps:
- Add dependencies for Apache Commons CSV and Gson in your project.
- Create a PostmanCollectionGenerator.java file and use the following code.
Required Libraries: You can add these dependencies to your Maven pom.xml
if using Maven:
<dependencies>
<!-- Apache Commons CSV -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.9.0</version>
</dependency>
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
</dependencies>
public class PostmanCollectionGenerator {
public static final String PROTOCOL_HTTP = "http", PROTOCOL_HTTPS = "https";
static String protocal = PROTOCOL_HTTP;
static String headers[] = {"OBJECT ID", "REQUEST"}; // Define expected headers
public static void main(String[] args) {
String path = "D:\\Python_DataMigration\\";
String csvFilePath = path + "Inbound_Logs.csv"; // Path to your CSV file
String jsonFilePath = path + "my_collection.json"; // Output JSON file path
try {
List<Map<String, Object>> requests = readCSV(csvFilePath);
Map<String, Object> postmanCollection = createPostmanCollection(requests);
writeToJsonFile(postmanCollection, jsonFilePath);
System.out.println("Postman collection generated: " + jsonFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
// Read CSV file and parse the data
private static List<Map<String, Object>> readCSV(String filePath) throws IOException {
//CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers);
//CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader();
// Configure CSVFormat to handle headers and skip the header row in data
CSVFormat csvFormat = CSVFormat.EXCEL.builder() // Use Excel CSV formatting
.setHeader(headers) // Define headers manually
.setSkipHeaderRecord(true) // Skip the header row in parsing
.build();
List<Map<String, Object>> requests = new ArrayList<>();
try (FileReader reader = new FileReader(filePath);
CSVParser csvParser = new CSVParser(reader, csvFormat)
) {
for (CSVRecord record : csvParser) {
Map<String, Object> requestData = new LinkedHashMap<>();
String objectId = record.get("OBJECT ID");
String requestPayload = record.get("REQUEST");
requestData.put("object_id", objectId);
requestData.put("request_payload", requestPayload);
requests.add(requestData);
}
}
return requests;
}
// Create the Postman collection structure
private static Map<String, Object> createPostmanCollection(List<Map<String, Object>> requests) {
Map<String, Object> postmanCollection = new LinkedHashMap<>(); // To Maintain Insertion Order
Map<String, String> info = new LinkedHashMap<>();
info.put("name", "Generated Collection");
info.put("schema", "https://schema.getpostman.com/json/collection/v2.1.0/collection.json");
postmanCollection.put("info", info);
List<Map<String, Object>> items = new ArrayList<>();
for (Map<String, Object> requestData : requests) {
String objectId = (String) requestData.get("object_id");
String requestPayload = (String) requestData.get("request_payload");
Map<String, Object> item = new LinkedHashMap<>();
item.put("name", "Request for Header " + headers[0]);
Map<String, Object> request = new LinkedHashMap<>();
// Headers
List<Map<String, String>> headers = new ArrayList<>();
addHeader(headers, "Authorization", "{{token}}", "text");
addHeader(headers, "Cookie", "{{session ID}}", "text");
addHeader(headers, "Content-Type", "application/json", "text");
//addHeader(headers, "User-Agent", "PostmanRuntime/7.42.0", "text");
// URL
Map<String, Object> url = new LinkedHashMap<>();
url.put("raw", "{{host}}/client/participant/" + objectId);
url.put("protocol", Arrays.asList( protocal ));
url.put("host", Arrays.asList("{{host}}"));
url.put("path", Arrays.asList("client", "participant", objectId));
// Body
Map<String, Object> body = new LinkedHashMap<>();
body.put("mode", "raw");
body.put("raw", requestPayload);
request.put("method", protocal);
request.put("header", headers);
request.put("url", url);
request.put("body", body);
item.put("request", request);
item.put("response", new ArrayList<>()); // Empty response array
items.add(item);
}
postmanCollection.put("item", items);
return postmanCollection;
}
private static void addHeader(List<Map<String, String>> headers, String key, String value, String type) {
Map<String, String> header = new LinkedHashMap<>();
header.put("key", key);
header.put("value", value);
header.put("type", type);
headers.add(header);
}
// Write the generated Postman collection to a JSON file
private static void writeToJsonFile(Map<String, Object> postmanCollection, String filePath) throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (FileWriter writer = new FileWriter(filePath)) {
gson.toJson(postmanCollection, writer);
}
}
}
Python script’s functionality to generate a Postman collection from a CSV file.
- Installed Python (x64) (3.12.0)
- Environment Path =
- C:\Program Files\Python312
- C:\Program Files\Python312\Scripts
- Install the required
- pip install pandas
- pip install json
- Executed the python script from the file inbound.py
import pandas as pd
import json
def generate_postman_collection(excel_file):
# Read the Excel file
df = pd.read_csv(excel_file)
# Initialize the Postman collection structure
postman_collection = {
"info": {
"name": "Generated Collection",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": []
}
# Loop through the rows in the Excel file
for index, row in df.iterrows():
object_id = row['OBJECT ID']
request_payload = row['REQUEST']
# You can include more fields based on your columns
# Construct the API URL
api_url = f"{{host}}/client/participant/{object_id}"
# Construct the Postman request
request_data = {
"name": f"Request for OBJECT ID {object_id}",
"request": {
"method": "PUT", # Assuming POST request, adjust based on your need
"header": [
{
"key": "Authorization",
"value": "{{token}}",
"type": "text"
},
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": api_url,
"host": ["{{host}}"],
"path": ["client", "participant", f"{object_id}"]
},
"body": {
"mode": "raw",
"raw":request_payload # Use the raw JSON directly
}
}
}
# Append each request to the Postman collection
postman_collection['item'].append(request_data)
# Save the Postman collection as a JSON file
with open('postman_collection.json', 'w') as f:
json.dump(postman_collection, f, indent=4)
print("Postman collection generated: postman_collection.json")
# Usage example:
excel_file = 'D:\\Python_DataMigration\\Inbound_Logs.csv' # Path to your Excel file
generate_postman_collection(excel_file)
- Executed the python file using command
python filename.py