【问题标题】:How can I visualize an API mashup in Postman?如何在 Postman 中可视化 API 混搭?
【发布时间】:2021-08-21 18:07:46
【问题描述】:

我有一个经典演员的 REST API,我想在 Postman 中进行可视化。 演员的图片 URL 不在 API 中,所以我需要创建一个 由核心 API 和另一个 API 组合而成的混搭。

1。先决条件

核心 API/端点位于 http://henke.atwebpages.com/postman/actors/actors.json:

{
  "area": {
    "name": "United States",
    "type": null
  },
  "release-groups": [
    {
      "primary-type": "Actor",
      "fullname": "Katharine Hepburn",
      "id": "Q56016",
      "born": "1907"
    },
    {
      "primary-type": "Actor",
      "fullname": "Humphrey Bogart",
      "id": "Q16390",
      "born": "1899"
    }
  ],
  "country": "US",
  "name": "Classical Actors",
  "life-span": {
    "begin": "1899",
    "ended": true,
    "end": "2003"
  }
}

Katharine HepburnHumphrey Bogart 的图片网址是:
http://henke.atwebpages.com/postman/actors/coverart/Q56016.json
http://henke.atwebpages.com/postman/actors/coverart/Q16390.json, 分别。

对应的 JSONS,凯瑟琳赫本:

{
  "images": [
    {
      "front": true,
      "thumbnails": {
        "small": "https://upload.wiki [...] 220px-Tom_cruise_1989.jpg",
        "large": "https://upload.wiki [...] -TomCruiseDec08MTV_cropped.jpg"
      },
      "back": false,
      "edit": 18084161
    },
    {
      "back": true,
      "edit": 39938947,
      "front": false,
      "thumbnails": {
        "small": "https://upload.wiki [...] -Katharine_Hepburn_promo_pic.jpg",
        "large": "https://upload.wiki [...] Tom_Cruise_by_Gage_Skidmore_2.jpg"
      }
    }
  ]
}

和汉弗莱·鲍嘉:

{
  "images": [
    {
      "edit": 40403385,
      "back": true,
      "thumbnails": {
        "small": "https://upload.wiki [...] 220px-Humphrey_Bogart_1940.jpg",
        "large": "https://upload.wiki [...] px-TomCruiseByIanMorris2010.jpg"
      },
      "front": false
    },
    {
      "edit": 40403384,
      "back": false,
      "thumbnails": {
        "small": "https://upload.wiki [...] 220px-Tom_cruise_1989.jpg",
        "large": "https://upload.wiki [...] -TomCruiseDec08MTV_cropped.jpg"
      },
      "front": true
    }
  ]
}

为了提高可读性,我截断了图片的链接。

在核心 API 中注意每个对象/人如何具有唯一的idQ56016 Katharine Hepburn 和 Q16390 代表 Humphrey Bogart)和 fullname。 其他端点具有 - 对于release-groups 数组中的每个对象 核心 API – 相同的唯一标识符,以及指向 图像/肖像。 因此,需要来自所有三个端点的信息来列出每个参与者 匹配图像。

2。所需的结果混搭

显然,如果API中的数据可以合并,问题就解决了 以这样一种方式组合在一起 – 对于每个标识符 – both 名称和 提供图片链接:

[
  {
    "name": "Katharine Hepburn",
    "image": "https://upload.wiki [...] -Katharine_Hepburn_promo_pic.jpg"
  },
  {
    "name": "Humphrey Bogart",
    "image": "https://upload.wiki [...] 220px-Humphrey_Bogart_1940.jpg"
  }
]

然后剩下的就是在 Postman 中可视化数据了。

3。方法

我将在 Postman 请求的单个 Tests 脚本中编写所有代码。 该请求只是一个虚拟,除了开始之外没有其他用途 运行 Tests 脚本。

要构建混搭然后显示结果,这样会很方便 使用众所周知的Fetch API,然后得到 图片使用Promise.all

需要注意的是 Postman 没有实现 Fetch API
但幸运的是有an answer 这解释了如何在 Postman 中模仿 fetch() 命令。
可以这样做:

function fetch (url) {
  return new Promise((resolve, reject) => {
    pm.sendRequest(url, function (_, fetchResponse) {
      resolve(fetchResponse);
    });
  });
} // ^^ No Fetch API in Postman! But see https://stackoverflow.com/a/67588692

由于这个fetch() 函数返回一个承诺,它应该(希望)工作 与任何现代网络浏览器中的fetch() 相同。

Tests 部分的其余部分应该构造结果。 注意Promise.all 需要如何与第一个请求链接/嵌套 fetch(urlOuter) – 因为它需要来自它的数据。
这类似于this answer 的第二个堆栈片段。
最后,结果应该是可视化的: 1

const lock = setTimeout(() => {}, 43210);
const fullnames = [];
const urls = [];
const urlOuter = 'http://henke.atwebpages.com/postman/actors/actors.json';
fetch(urlOuter).then(responseO => responseO.json()).then(responseBodyO => {
  const tblHeader = responseBodyO.name;
  const actors = responseBodyO['release-groups'];
  for (const item of actors) {
    fullnames.push(item.fullname);
    urls.push('http://henke.atwebpages.com/postman/actors/coverart/' +
        item.id + '.json');
  }
  return Promise.all(urls.map(url => fetch(url)
    .then(responseI => responseI.json())
    .then(responseBodyI => responseBodyI.images.find(obj =>
      obj.back === true).thumbnails.small)))
    .then(imageURLs => {
      clearTimeout(lock); // Unlock the timeout.
      const actorNames = fullnames.map(value => ({ name: value }));
      const actorImages = imageURLs.map(value => ({ image: value }));
      const actorsAndImages = actorNames.map(
        (item, i) => Object.assign({}, item, actorImages[i]));
      console.log('actorsAndImages:\n' + JSON.stringify(actorsAndImages));
      const template = `<table>
        <tr><th>` + tblHeader + `</th></tr>
        {{#each responseI}}
        <tr><td>{{name}}<br><img src="{{image}}"></td></tr>
        {{/each}}
      </table>`;
      pm.visualizer.set(template, { responseI: actorsAndImages });
    });
}).catch(_ => {
  console.error('Failed to fetch - ' + urlOuter);
});

在邮递员中:

4。有用吗?

那么它有效吗? – 答案是肯定的和否定的。

  • 从好的方面来说,我可以创建所需的 JSON 混搭结果,如下所示 上面第 2 节。
  • 不好的一面是,可视化失败:

消息为此请求设置可视化工具是典型的当 已忘记致电pm.visualizer.set()。 但我确实没有忘记了。那么有什么问题呢?

5。如何在 Postman 中复制我的尝试

在 Postman 中复制我的尝试应该很简单。
假设您使用的是the desktop version of Postman,请执行以下操作:

  1. 下载并保存
    http://henke.atwebpages.com/postman/actors/Promise.all-Actors.pm_coll.json
    放在硬盘上的合适位置。

  2. 在 Postman 中,Ctrl + O > 上传文件 > Promise.all-Actors.pm_coll.json > 导入
    您现在应该在 Postman 的收藏中看到 Promise.all-Actors

  3. 收藏 > Promise.all-Actors > DummyRequest > 发送

  4. 在 Postman 响应正文中,单击可视化

  5. 完成! – 如果一切都按预期工作,您现在应该看到输出为 以上。

参考文献


1 不要被台词弄糊涂 const lock = setTimeout(() =&gt; {}, 43210);clearTimeout(lock);。 – 他们唯一的目的是充当a workaround for a known bug

【问题讨论】:

    标签: javascript asynchronous postman


    【解决方案1】:

    消息为此请求设置可视化工具是典型的当 打电话给pm.visualizer.set() 已经忘记了。 但我确实没有忘记了。那么有什么问题呢?

    如前所述,问题在于 Postman does not natively support promises1
    那是什么意思? – 嗯,显然这意味着一个功能,如 pm.visualizer.set() 不能从 的回调中调用 承诺。 它必须在 pm.sendRequest() 的回调中调用。 请注意,通过fetch() 函数的构造,对应的 Promise 实际上在pm.sendRequest() 回调的之外

    1。实现期望的结果将其可视化

    换句话说,您需要将所有出现的fetch() 替换为 pm.sendRequest().
    您还需要实现自己的Promise.all 版本,因为它依赖于 根据承诺,这是您在本地 Postman 脚本中所没有的。
    幸运的是,这样的实现发布在 an answer the day before yesterday.

    进行这些更改后,这里是 Tests 部分的代码,开始 与初始化: 2

    const lock = setTimeout(() => {}, 43210);
    const fullnames = [];
    const urls = [];
    const urlOuter = 'http://henke.atwebpages.com/postman/actors/actors.json';
    

    主要部分 - 略微非常规格式 - 避免垂直 滚动:

    pm.sendRequest(urlOuter, (_, responseO) => {
      const tblHeader = responseO.json().name;
      const actors = responseO.json()['release-groups'];
      for (const item of actors) {
        fullnames.push(item.fullname);
        urls.push('http://henke.atwebpages.com/postman/actors/coverart/' +
            item.id + '.json'); }
      const images = [];
      let countDown = urls.length;
      urls.forEach((url, index) => {
        asynchronousCall(url, imageURL => {
          images[index] = imageURL;
          if (--countDown === 0) { // Callback for ALL starts on next line.
            clearTimeout(lock); // Unlock the timeout.
            const actorNames = fullnames.map(value => ({ name: value }));
            const actorImages = images.map(value => ({ image: value }));
            const actorsAndImages = actorNames.map(
              (item, i) => Object.assign({}, item, actorImages[i]));
            console.log('actorsAndImages:\n' + JSON.stringify(actorsAndImages));
            const template = `<table>
              <tr><th>` + tblHeader + `</th></tr>
              {{#each responseI}}
              <tr><td>{{name}}<br><img src="{{image}}"></td></tr>
              {{/each}}
            </table>`;
            pm.visualizer.set(template, { responseI: actorsAndImages });
          }
        });
      });
      function asynchronousCall (url, callback) {
        pm.sendRequest(url, (_, responseI) => {
          callback(responseI.json().images.find(obj => obj.back === true)
            .thumbnails.small); // Individual callback.
        }); } });
    

    在邮递员中:

    2。有用吗?

    是的! – 有效:

    3。如何在 Postman 中复制我的解决方案

    假设您使用的是the desktop version of Postman,请执行以下操作:

    1. 下载并保存
      http://henke.atwebpages.com/postman/actors/Actors.pm_coll.json
      放在硬盘上的合适位置。

    2. 在 Postman 中,Ctrl + O > 上传文件 > Actors.pm_coll.json > 导入.

    3. 收藏 > Actors > DummyRequest > 发送

    4. 在 Postman 响应正文中,单击可视化

    5. 完成! – 您现在应该看到如上的输出。

    参考文献


    1 我希望 Postman 在未来的版本中支持 Promise。
    2 再说一次,不要被这些行弄糊涂了 const lock = setTimeout(() =&gt; {}, 43210);clearTimeout(lock);。 – 他们唯一的目的是充当a workaround for a known bug

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 2012-04-09
      • 2020-02-15
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      相关资源
      最近更新 更多