You need to enable JavaScript to run this app. 如何在Postman中通过编程方式设置集合变量的初始值并与当前值同步
优惠活动
大模型
产品
解决方案
定价
更多

如何在Postman中通过编程方式设置集合变量的初始值并与当前值同步

Postman 公开的 pm.collectionVariables.set() 方法默认仅修改集合变量的当前值,要同步修改初始值可以通过调用 Postman 官方的集合操作 API 实现,具体操作如下:

前置准备

  • 进入 Postman 账号设置页面生成你的 Postman API 密钥,将密钥存为集合变量,变量名设为 postman_api_key
  • 无需手动查询集合ID,脚本内可直接通过内置变量获取当前集合的ID

完整测试脚本

// 原有逻辑:筛选符合条件的物种数量,设置当前值
const responseJson = pm.response.json();
const tallSpeciesCount = responseJson.results.filter(species => Number(species.average_height) > 100).length;
pm.collectionVariables.set("talls", tallSpeciesCount); 

// 新增逻辑:同步更新集合变量初始值
const collectionId = pm.info.collectionId;
const postmanApiKey = pm.collectionVariables.get("postman_api_key");

// 调用Postman API拉取当前集合的配置信息
pm.sendRequest({
    url: `https://api.getpostman.com/collections/${collectionId}`,
    method: 'GET',
    header: {
        'X-Api-Key': postmanApiKey
    }
}, (err, res) => {
    if (err) {
        console.error("获取集合信息失败:", err);
        return;
    }
    const collectionData = res.json().collection;
    // 找到talls变量修改初始值,不存在则新增变量
    const targetVar = collectionData.variable?.find(item => item.key === "talls");
    if (targetVar) {
        targetVar.value = tallSpeciesCount.toString();
    } else {
        collectionData.variable.push({
            key: "talls",
            value: tallSpeciesCount.toString(),
            type: "number"
        });
    }
    // 提交修改到Postman服务端完成初始值同步
    pm.sendRequest({
        url: `https://api.getpostman.com/collections/${collectionId}`,
        method: 'PUT',
        header: {
            'X-Api-Key': postmanApiKey,
            'Content-Type': 'application/json'
        },
        body: {
            mode: 'raw',
            raw: JSON.stringify({ collection: collectionData })
        }
    }, (putErr, putRes) => {
        if (putErr || putRes.code !== 200) {
            console.error("同步初始值失败:", putErr || putRes.json());
            return;
        }
        console.log("集合变量talls的当前值和初始值已同步更新为", tallSpeciesCount);
    });
});

注意事项

  • Postman API密钥拥有你账号下资源的操作权限,请不要泄露给他人,也不要将存储了密钥的集合同步到公共工作空间
  • 此方法仅适用于Postman桌面端/网页端的在线使用场景,离线状态下无法调用Postman服务端接口完成初始值更新
  • 如果变量值为非字符串类型,建议转成字符串存储,避免Postman接口解析报错

内容的提问来源于stack exchange,提问作者Srishti Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 13:24:04