Hi , the json body of my request keeps changing every now and then , I have over 20 to 30 collections which will use that particular request , is there a way i can change the request body from pre request script ? or any other way i can change the request body dynamically ? so that i dont want to go and change it every single time manually
@prasu.eng123 The best way to do this is to break the body down into individual pieces and set their values using variables in pre-request scripts. Assuming that your request body takes the following form:
{
"foo": "bar"
}
If youâd like to make the value of the key foo
dynamic, youâd update the request body to:
{
"foo": "{{foo}}"
}
Also, your pre-request code will have to include the following:
pm.environment.set('foo', 'THIS HAS TO BE REPLACED WITH YOUR VALUE');
@kunagpal : Thank for your reply , but this is not what i was looking for . I want to build the whole body dynamically, for example . the json body might sometimes take have 3 key value pairs or four key value pair etc
{
id :âasdasâ
pwd:âasdasâ
auth: âashdâ
}
or
{
id :âasdâ
pwd:âasdasâ
auth"adssa"
newauth :âasdsaâ
}
is there any way i can write script to handle this ?
@prasu.eng123 This can be done as follows:
// in the pre-request script
var body = {}; // this will contain all the necessary keys
pm.environment.set('req_body', JSON.stringify(body));
In the request body (notice how the req_body
variable is referenced directy in the raw body):
{{req_body}}
@kunagpal i am not able to understand what you have posted , could you please elaborate a bit ? may be with an example
@prasu.eng123 Sure thing. As we need to dynamically set the entire request body, weâll have to save it to a variable that can be used inside the request body editor. The flow goes something like this:
- Build the body in the form of a JSON object. This happens inside the pre-request script.
var body = {
id: 'asdas',
pwd: 'asdas',
auth: 'ashd'
};
- Stringify the body, using JSON.stringify. This converts objects to strings.
var body_str = JSON.stringify(body); // body was defined in the previous step.
- Save the stringified body as an environment variable using
pm.environment.set
;
pm.environment.set('request_body', body_str); // this sets an environment variable with the stringified body
- In the request body editor, specify the
raw
request body as the variable created in step 3.
{{request_body}}
Note that the snippet from step 4 will have to be placed in the body editor.
EDIT: Check this collection to see it working directly in Postman, you can also fork it to adapt it to your own use-case:
Thank you @kunagpal . But i am getting the new line paramaters like \n and\r how can i eleiminate them , any idea ?
@prasu.eng123 Where exactly are you getting these values?
@kunagpal i have a sample request from postman , whose response is the same as data u send. Example beloww . as u can see the data field in response contains the data with \n ad \r
Request: postman-echo.com/post
Pre request:
var body = {foo: "1", password: "asas"};
pm.environment.set('req_body', JSON.stringify(body));
pm.variables.get("variable_key");
Response:
{
"args": {},
"data": "\r\n{\"foo\":\"1\",\"password\":\"asas\"}",
"files": {},
"form": {},
"headers": {
"host": "postman-echo.com",
"content-length": "31",
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"authorization": "Basic Og==",
"cache-control": "no-cache",
"content-type": "text/plain",
"cookie": "sails.sid=s%3AlnH3kM7X-xeDKcn6G0hehamaL_Mu-ELn.sKV0Fi5CRHiTsT0fUiY7xgA%2BBVjIR5PNXa3JHjYC7ok",
"postman-token": "077d84f1-e8b9-431b-8870-96f080914896",
"user-agent": "PostmanRuntime/7.1.5",
"x-forwarded-port": "80",
"x-forwarded-proto": "http"
},
"json": null,
}
@prasu.eng123 This is happening because the request body is being sent as text instead of JSON. You can fix this by clicking on the mode dropdown to the right of the request body and selecting application/json
, as can be seen below:
Hello @kunagpal,
Thanks for the snippet,
Could you please explain how can we set dynamic AlphaNumeric string value which is incremental(Letters+Number) to a Json object of the request. Ex: âOrderIdâ: âThisValue01234â.
Hi. Why wouldnât this work on the pre-request script? Itâs in the SDK documentation.
console.log(pm.request);
pm.request.body.raw = âYour Requestâ;
console.log(pm.request);
I found this post when I trying to construct my request from the pre-request script.
Even though using environment variables can work around the issue, but I think @obisignano-c 's suggestion will make Postman more useful to the developers.
Nevertheless, thank you guys for this great software
@kunagpal What happens when the value that you want to replace is not a string?
perfect, worked for me.
Set::TESTS
pm.environment.set(âreq_bodyâ, pm.request.body.raw);
Use:: RAW>JSON
{{req_body}}
Dear all guys:
Here is my script which will set the request RAW JSON body.
pm.request.body.mode = ârawâ;
pm.request.headers.upsert({key: âContent-Typeâ, value: âapplication/jsonâ});
var raw_body = {âaccountâ: âusername1â};
var body_json = JSON.stringify(raw_body);
pm.request.body.raw = body_json;
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.