Dynamic body with dynamic variables

Hi Alex,

That’s a strange one! The core parts of your script are all working for me in the way that you’d expect - here’s a stripped-down version which always uses prodBody to set the req_body variable:

Snippet
const moment = require('moment');

pm.environment.set('today', moment().format("YYYY-MM-DD"));

pm.environment.set('externalId', '{{$randomInt}}');

var prodBody = '{"origin":"PC","type":"WRITTEN","user":{{externalId}}, "date": "{{today}}", "type2": "unique"}';

pm.collectionVariables.set('req_body',prodBody);

When I post that payload to https://postman-echo.com/post then the console (and the mirrored response) reveal that the variables were substituted as you’d expect:

If this example works for you too, then there are a couple of things I’d suggest checking:

  • Is your pm.environment.name variable being set as you’d expect (have you confirmed you’re executing the code path that you’re intending to?)
  • Is your qaBody variable setup in the same way as prodBody? You’d mentioned experimenting with different formats; the one in prodBody is working for me, so if you’re seeing the same with my example then maybe try double-checking what qaBody is doing.
1 Like