在Postman中,是否有一种方法可以持久化请求体值(作为环境值)?

ffx8fchx  于 5个月前  发布在  Postman
关注(0)|答案(2)|浏览(86)

我试图将几个API请求链接在一起,并希望自动化链中的值。

{
   :
   :
   "details":{
      "identifiers":[
          {
            "id": "1234", // ---> Am setting this manually, which I need in my 2nd request.
            "idType": "SpecialID"
          },
          {
             "id": "3456",
             "idType": "uninterestingID"

          }

       ]

    }

}

字符串
注意

  • 我想在第二个请求中使用 * id * 的值,只有当它是 idType“SpecialID”时
  • 这两个ID的顺序可能不固定
  • 在某些请求中,可能不会发送“uninterested”ID,但始终会发送“SpecialID”

在上述条件下,我如何在Postman测试中做到这一点,即将id的值存储在一个API调用的请求体中,并在第二个API的请求调用中使用它?如果需要客户代码,我看不到在Postman中做到这一点的方法。

r1zhe5dt

r1zhe5dt1#

如果您确实希望从请求体中idType为“SpecialID”的对象获取id,并将其保存到环境变量中,可以执行以下操作。

let body = JSON.parse(pm.request.body.raw);

let specialID = (body.details.identifiers.find(obj => { return obj.idType === 'SpecialID' })).id

pm.environment.set("id", specialID);
console.log(pm.environment.get("id")); // 1234

字符串

t8e9dugd

t8e9dugd2#

我在测试之间使用了postman环境变量,我的测试创建了一个单独的警报,然后我想获取它,验证它返回了什么,然后删除警报。
POST /API/警报{}
x1c 0d1x的数据
然后,测试可以验证结果并为下一个测试创建环境变量。

pm.test("Response should be 200", function () { 
    pm.response.to.be.ok;
    pm.response.to.have.status(200);
});

const jsonData = pm.response.json();
pm.expect(jsonData.length).greaterThan(0);
postman.setEnvironmentVariable('Alert_Key', jsonData[0].Key_);

字符串
然后,我可以使用大括号语法在URL中发送一个带有环境变量的URL。



我还使用这些测试来简单地遍历所有返回值,并同时调用Roundroutes。

pm.test("Response should be 200", function () { 
    pm.response.to.be.ok;
    pm.response.to.have.status(200);
});

pm.test("Parse Alert Key_ values and send DELETE", function () {
    var jsonData = JSON.parse(responseBody);
    jsonData.forEach(function (AlertRecord) {
        console.log(AlertRecord.Key_);
        const DeleteURL = pm.variables.get('TimeSheetAPI') + '/api/alerts/' + AlertRecord.Key_;
        pm.sendRequest({
            url: DeleteURL, 
            method: 'DELETE',
            header: { 'Content-Type': 'application/json' },
            body: '{ "Key_": ' + AlertRecord.Key_ + '} ' }
        , function (err, res) {
            console.log("Sent Delete: " + DeleteURL );
        });
    });
});

相关问题