Debug School

rakesh kumar
rakesh kumar

Posted on

How to assign response value to postman envirnment variable

To assign a response value to a Postman environment variable, you can use Postman scripts. Postman provides pre-request and test scripts that allow you to manipulate request data and extract values from responses.

Here's an example of how you can assign a response value to an environment variable using a Postman test script:

Step 1: Create or open a Postman request where you expect to receive a response containing the desired value.

Step 2: In the request, navigate to the "Tests" tab.

Step 3: Write a script in the Postman test script editor to extract the desired value from the response and assign it to the environment variable. For example, if the response is in JSON format and contains an attribute named "access_token" that you want to assign to the environment variable "access_token":

// Postman test script
var jsonData = pm.response.json();
pm.environment.set("access_token", jsonData.access_token);
Enter fullscreen mode Exit fullscreen mode

replace access token to token because in environment varable value assigned to token name

Image description

var jsonData = pm.response.json();
pm.environment.set("token", jsonData.token);
Enter fullscreen mode Exit fullscreen mode

Step 4: Send the request. The test script will execute after the response is received.

Image description

Step 5: Verify that the environment variable has been updated with the desired value. You can check the environment variable by opening the Postman environment and inspecting the value assigned to "access_token".

Now, the assigned value can be used in subsequent requests by referencing the environment variable as

{{access_token}}
Enter fullscreen mode Exit fullscreen mode

.

Note: If the response is not in JSON format, you might need to use a different method to extract the desired value. For example, you can use pm.response.text() to get the response as plain text and then use string manipulation functions to extract the desired value.

By using Postman scripts, you can dynamically assign response values to environment variables, making them easily accessible across different requests within the same environment.

step6: now delete the current value of token from environment and click save

Image description

Image description

step7: now put cursor on token u find current value is zero

Image description

step8 run the login api where test script written

Image description

Image description

now automatically token variable value set

Image description

Top comments (0)