Search code examples
javascriptjsonvariablespostman

How to create a variable from response body in Postman?


I have the following response body: `

{
    "timestamp": "2022-11-08T12:40:11.631Z",
    "data": {
        "version": "2.2",
        "endpoints": [
            {
                "identifier": "credentials",
                "role": "SENDER",
                "url": "https://example.com/credentials65"
            },
            {
                "identifier": "tokens",
                "role": "RECEIVER",
                "url": "https://example.com/tokens245"
            },
            {
                "identifier": "tokens",
                "role": "SENDER",
                "url": "https://example.com/tokens353"
            },
.......

For each identifier and role (in Postman tests session), i want to define variables automatically.

I tried the following for the first ones:

_.each(pm.response.json(), (responseBody) => {

        if (responseBody.identifier['data'][1]['identifier'] === "credentials") { 
           pm.globals.set("credentials_url", responseBody.url)
        }

        else if (responseBody.identifier === "tariffs") {
           pm.globals.set("tariffs_url", responseBody.url)
        }

    })

The problem is that i do not know how to call the "identifier" and the script do not enter in the if loop. Can anyone help?


Solution

  • const endpoints = pm.response.json().data.endpoints;
    for (const endpoint of endpoints) {
        const array = pm.globals.get(`${endpoint.identifier}_url`) ?? [];
        array.push(endpoint.url);
        pm.globals.set(`${endpoint.identifier}_url`, array);
    }
    

    You can access the URLs in the arrays by using pm.globals.get("tariffs_url"), pm.globals.get("credentials_url") etc. (it'll work for every identifier)