2

I have a request that accepts json. Inside the body of the request I would like to use the same dynamic variable twice. So for example:

{
    "description": "{{$randomFirstName}}'s Home", 
    "first_name": "{{$randomFirstName}}",
    "first_name": "{{$randomLastName}}",
    "more_fields": "..."
}

However simply repeating the variable as above results in a different first name for the description and first_name fields when I would like the value to be the same.

How can I achieve this. I think it should be possible in the pre-request script though if there is someway to do the equivalent of

{
    "description": "{{firstName=$randomFirstName}}'s Home", 
    "first_name": "{{firstName}}",
    "first_name": "{{$randomLastName}}",
    "more_fields": "..."
}

without bothering with a pre-request script I might prefer that.

kaan_a
  • 3,503
  • 1
  • 28
  • 52

1 Answers1

4

You can achieve this by using the .replaceIn() function and constructing the Request Body in the sandbox environment.

Add this to the Pre-request Script of the POST request:

let firstName = pm.variables.replaceIn("{{$randomFirstName}}")

let requestBody = {
    "description": `${firstName}'s Home`, 
    "first_name": `${firstName}`,
    "last_name": "{{$randomLastName}}",
    "more_fields": "..."
};

pm.variables.set("requestBody", JSON.stringify(requestBody)); 

In the Request Body, add this variable without quotes:

{{requestBody}}

When you send the Request, it will resolve the variables and use the same first name.

Here's an example using the Postman-echo service:

enter image description here

Danny Dainton
  • 23,069
  • 6
  • 67
  • 80