Change request body (RAW JSON) dynamicalls

@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:

  1. 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'
};
  1. Stringify the body, using JSON.stringify. This converts objects to strings.
var body_str = JSON.stringify(body); // body was defined in the previous step.
  1. 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
  1. 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:

https://www.postman.com/postman/workspace/postman-answers/collection/9215231-b9133e48-73c3-4aa4-b189-e038ee4c5e00?ctx=documentation

3 Likes