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

ffx8fchx  于 2024-01-07  发布在  Postman
关注(0)|答案(2)|浏览(319)

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

  1. {
  2. :
  3. :
  4. "details":{
  5. "identifiers":[
  6. {
  7. "id": "1234", // ---> Am setting this manually, which I need in my 2nd request.
  8. "idType": "SpecialID"
  9. },
  10. {
  11. "id": "3456",
  12. "idType": "uninterestingID"
  13. }
  14. ]
  15. }
  16. }

字符串
注意

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

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

r1zhe5dt

r1zhe5dt1#

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

  1. let body = JSON.parse(pm.request.body.raw);
  2. let specialID = (body.details.identifiers.find(obj => { return obj.idType === 'SpecialID' })).id
  3. pm.environment.set("id", specialID);
  4. console.log(pm.environment.get("id")); // 1234

字符串

t8e9dugd

t8e9dugd2#

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

  1. pm.test("Response should be 200", function () {
  2. pm.response.to.be.ok;
  3. pm.response.to.have.status(200);
  4. });
  5. const jsonData = pm.response.json();
  6. pm.expect(jsonData.length).greaterThan(0);
  7. postman.setEnvironmentVariable('Alert_Key', jsonData[0].Key_);

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



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

  1. pm.test("Response should be 200", function () {
  2. pm.response.to.be.ok;
  3. pm.response.to.have.status(200);
  4. });
  5. pm.test("Parse Alert Key_ values and send DELETE", function () {
  6. var jsonData = JSON.parse(responseBody);
  7. jsonData.forEach(function (AlertRecord) {
  8. console.log(AlertRecord.Key_);
  9. const DeleteURL = pm.variables.get('TimeSheetAPI') + '/api/alerts/' + AlertRecord.Key_;
  10. pm.sendRequest({
  11. url: DeleteURL,
  12. method: 'DELETE',
  13. header: { 'Content-Type': 'application/json' },
  14. body: '{ "Key_": ' + AlertRecord.Key_ + '} ' }
  15. , function (err, res) {
  16. console.log("Sent Delete: " + DeleteURL );
  17. });
  18. });
  19. });

展开查看全部

相关问题