'postman scripting with static guids

I'm hoping to use Postman to generate and insert test data for an API project I'm working on. The resources in the API have foreign key constraints, so I want to be able to generate static guids for the resources, and share those IDs among all the other requests so that we can maintain the references and have valid foreign keys.

At the moment I'm generating data that I want to keep accessible to all the requests in the collection in a pre-request script at the collection level:

// set the user ID for our test user
var userId = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("userId", userId);

// then generate a product ID
var productId = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("productId", productId);

// create a few vendors
var vendorId1 = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("vendorId1", vendorId1);

var vendorId2 = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("vendorId1", vendorId1);

// etc

My thought was that I'd use the userId in all subsequent POSTs so there'd be a real user to associate a new object with, then use the vendor IDs with the product inserts, etc.

However, the pre-request script runs before each request-- I think it's re-creating all these values rather than keeping them static, so my plan to maintain integrity isn't working.

Is there a better strategy? For example, can I capture the ID of the inserted object from the request response and pass that variable on to the next request in the workflow so that it can use that ID for the associated resources?



Solution 1:[1]

You could test if the userId is already set, and only if it isn't set your variables, something like:

if (!pm.collectionVariables.get("userId")) {
    // set the user ID for our test user
    var userId = pm.variables.replaceIn("{{$guid}}"); 
    pm.collectionVariables.set("userId", userId);

    // set your other variables...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christian Baumann