Build request bodies in a pre-request script

Most bodies are best written as plain JSON with a few {{variables}}. Some aren't: an order whose total must equal the sum of its lines, a field that's only there in one environment, a comment with quotes in it, a body that has to be signed. For those, build the body in JavaScript and hand it to the request.

The pattern

JavaScript
const items = [
  { sku: 'TSHIRT-M', quantity: 2, unitPrice: 19.99 },
  { sku: 'MUG', quantity: 1, unitPrice: 9.5 },
];

const body = {
  orderId: require('uuid').v4(),
  customerId: pm.environment.get('customerId'),
  items,
  total: Math.round(items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0) * 100) / 100,
  createdAt: new Date().toISOString(),
};

pm.request.body.raw = JSON.stringify(body, null, 2);
pm.variables.set('expectedTotal', body.total);

JSON.stringify handles every quote, backslash and line break, so the JSON is always valid. The test script can compare the response with expectedTotal.

Optional fields

Leave a field out instead of sending null, depending on the environment or the data row:

JavaScript
const body = { email: pm.iterationData.get('email') || '[email protected]' };

const coupon = pm.iterationData.get('coupon');
if (coupon) body.couponCode = coupon;

if (pm.environment.get('featureNewCheckout') === 'true') {
  body.checkoutVersion = 2;
}

pm.request.body.raw = JSON.stringify(body);

From an earlier response

A later request often sends back part of what an earlier one returned. Store the object, then use it:

JavaScript
// Tests on "Get cart"
pm.environment.set('cart', pm.response.json());
JavaScript
// Pre-request on "Checkout"
const cart = JSON.parse(pm.environment.get('cart'));
pm.request.body.raw = JSON.stringify({
  cartId: cart.id,
  items: cart.items.map(({ sku, quantity }) => ({ sku, quantity })),
  shippingAddress: { country: 'DE', postalCode: '10115' },
});

Objects are stored as JSON text, so read them back with JSON.parse.

Dates

JavaScript
const moment = require('moment');
pm.request.body.raw = JSON.stringify({
  from: moment().subtract(7, 'days').startOf('day').toISOString(),
  to: moment().endOf('day').toISOString(),
});

More in test dates and time zones.

Signatures over the body

When the API wants an HMAC of the exact body bytes, build the body first, then sign the same string:

JavaScript
const CryptoJS = require('crypto-js');
const raw = JSON.stringify({ event: 'ping', at: Date.now() });
pm.request.body.raw = raw;
pm.request.headers.add({ key: 'X-Signature', value: CryptoJS.HmacSHA256(raw, pm.environment.get('signingSecret')).toString() });

See sign API requests with HMAC.

Keep it readable

The body in the editor is what people read. Leave a realistic example there, and a comment at the top of the script saying it replaces the body. Someone opening the request should still see what it sends without reading code.