使用静态 guids 的邮递员脚本

postman scripting with static guids

我希望使用 Postman 为我正在处理的 API 项目生成和插入测试数据。 API 中的资源有外键约束,所以我希望能够为资源生成静态 guids,并在所有其他请求之间共享这些 ID,以便我们可以维护引用和有有效的外键。

目前我正在生成数据,我希望在集合级别的预请求脚本中让集合中的所有请求都可以访问这些数据:

// 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

我的想法是,我会在所有后续的 POST 中使用 userId,这样就会有一个真正的用户与新对象相关联,然后使用 vendor 带有产品插页等的 ID

但是,预请求脚本在每个请求之前运行——我认为它是在重新创建所有这些值而不是将它们保持静态,所以我保持完整性的计划没有奏效。

有没有更好的攻略?例如,我能否从请求响应中捕获插入对象的 ID,并将该变量传递给工作流中的下一个请求,以便它可以将该 ID 用于关联资源?

您可以测试 userId 是否已经设置,并且只有当它没有设置您的变量时,例如:

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...
}