Modify Postman request dynamically
In this post we will see how can we modify Postman request dynamically.
What is postman?
Postman is a platform helpful in building and debugging APIs. It offers a desktop client that can be used to send network requests and is widely used in API development.
Why might we need to modify request body on the fly?
There might be cases where our actual client sending requests to APIs is modifying request data, before sending. Typical example can be password encryption, where the client (consider a webform) is encrypting or hashing sensitive information like password, before sending over the wire.
In such cases, instead of manually making this modification each time we send the request using postman, we could write a simple script to automate this and modify Postman request dynamically.
How to Modify Postman request dynamically?
An approach to achive this could be to use the method update()
on pm.request.body
object.
Example
Consider a request body like following
{
"email": "abc@example.com",
"password": "plain text pasword"
}
Now, if we want to encrypt password
before sending this data to API, we can do so by using Pre-Request scripts
Postman Pre-request scripts
Pre-request scripts in Postman are a way to execute javascript code before sending request. This can be added for collection, request or folder and can be used to set/modify pieces of information like setting up variables, headers and body data.
The pre-request option can be accessed from one of tabs in the Postman
Modify Postman request dynamically
Lets assume we have a “hypothetical” function encrypt()
that returns encrypted parameter. We will use this function to encrypt the password
field in our request body.
const requestData = JSON.parse(request.data);
requestData.password = encrypt(requestData.password);
const body = {
mode: "raw",
raw: JSON.stringify(requestData),
options: {
raw: {
language: "json"
}
}
}
pm.request.body.update(body);
Once above script is saved, it will be executed automatically before each request.