Search code examples
postmanpostman-testcase

Postman test - reusable body request (body as variable?)


I'm pretty new to automation tests and using Postman.

I have a collection of tests that send the same request body with smaller variables - I have found out how to use pre-request script to make smaller changes to the body for test purposes. For test reasons I have to keep the test in seperate requests. So far so good. What I really want to do is to be able to have ONE body (like a reusable body) If they (devs) add a new required field - I would NOT have to change 20-25 bodies in different tests. So ONE body so when devs changes the make-up of the API I have ONE place to change my body.

I hope this makes sense.

I have tried to create a parameter for this purpose but that does not seem to work.


Solution

  • Assuming this is a JSON body, and not form data.

    You can save the body as an JSON string in an environment or collection variable, then you can do the following in a pre-request script.

    const body = JSON.parse(pm.environment.get("body"));
    // make any changes to the body here
    pm.request.body.raw = body;
    // console.log(pm.request.body.raw);
    

    If you don't need to make any changes to the body, you can just reference the variable like following...

    enter image description here