Skip to content
Advertisement

Postman Pre-Request Script to Read Variables from CSV file and Append to JSON Body

I have a JSON body with template to pass to an API endpoint in Postman/Newman as follows:

{
  "total": [
    {
      "var1a": "ABCDE",
      "var1b": {
        "var2a": "http://url/site/{{yyyy}}/{{mmdd}}/{{yyyymmdd}}.zip",
        "var2b": {
           "var3a": "{{yyyymmdd}}",
           "var3b": "GKG"
        },
        "var2c": "ABCDE"
        "var2d": "{{p}}"
      }
    },
    {
      "var1a": "ABCDE",
      "var1b": {
        "var2a": "http://url/site/{{yyyy}}/{{mmdd}}/{{yyyymmdd}}.zip",
        "var2b": {
           "var3a": "{{yyyymmdd}}",
           "var3b": "GKG"
        },
        "var2c": "ABCDE"
        "var2d": "{{p}}"
      }
    }
}

Everything enclosed in double braces is a variable that needs to read from an external CSV file, which looks like:

p,yyyymmdd,yyyy,mmdd
1,19991231,1999,1231
2,20001230,2000,1230
  • Note that the CSV isn’t necessarily 2 entries long – I’d ideally like it to take in a dynamic number of entries that append after the last.
  • Ideally, I’d get rid of the last two columns in the CSV file (yyyy and mmdd) and have the code just do a slice as needed.

How do I even begin coding the pre-request script?

Even if reading from an external CSV is not possible, or even coding within the pre-request script to do this, what is a quick one-liner in Javascript or Python that can quickly give me the output I need so that I can just manually place it in the request body?

I even tried using the Postman runner to do a “fake” run so that I can quickly extract the different JSON bodies, but even with this, there is no clean way that it does the export…

Advertisement

Answer

Reading data from CSV is not the good way to solve problem because each record is will be used to one request. You want the whole record into ONE request.

I think write code in pre-request script will work.

In body tab:

enter image description here

In pre-rquest tab:

let data_set = [
    [1, 1999, 1231],
    [2, 2000, 1230]
];

let total = [];

for (let i = 0; i < data_set.length; i++) {
    let p = data_set[i][0];
    let yyyy = data_set[i][1];
    let mmdd = data_set[i][2];

    const item = {
        var1a: "ABCDE",
        var1b: {
            var2a: `http://url/site/${yyyy}/${mmdd}/${yyyy}${mmdd}.zip`,
            var2b: {
                var3a: `${yyyy}${mmdd}`,
                var3b: "GKG"
            },
            var2c: "ABCDE",
            var2d: `${p}`
        }
    };

    total.push(item);
}

pm.environment.set("total", JSON.stringify(total));

Advertisement