Apifox 中怎么获取当前时间戳作为接口的入参?图文教程

时间戳是记录时间的方式,对于 API 开发至关重要。它能准确标记事件的发生时间,方便调试和验证数据时效性。在 Apifox 中,获取当前时间戳非常简便,可以通过动态值、Mock 或脚本实现,详情见下文。
1.通过【动态值】获取
如果你需要在 URL 路径上携带时间戳,或者请求体是form-data
或x-www-form-urlencoded
格式的,可以在接口请求参数的【示例值】那里,点击一个像“魔棒”的图标,然后依次点击【数据生成器->时间戳】,在发送请求时即可获取到当前时间的时间戳。


如果你需要在请求体(Body)里面携带时间戳,并且发送的请求体是 JSON 或 XML 格式的,那么可以在【修改文档】页面通过 Mock 获取(注意参数类型为 integer)。

或者在【运行】页面通过【动态值->数据生成器】获取。

2.通过脚本
你可以在接口的【前置操作】中添加一个自定义脚本,然后在【自定义脚本】中通过 Javascript 代码来获取到当前时间戳。

在脚本中,你可以使用Date
对象来获取。以下是一个简单的例子:
// 获取当前时间戳(以毫秒为单位)
let timestamp = new Date().getTime();
console.log(timestamp);

上述代码创建了一个Date
对象,然后使用getTime()
方法获取该对象的时间戳,返回的时间戳是从 1970 年 1 月 1 日午夜(UTC)开始的毫秒数。如果你想要秒级别的时间戳,可以使用Math.floor
或Math.round
:
// 获取当前时间戳(以秒为单位)
var timestampInSeconds = Math.floor(new Date().getTime() / 1000);
console.log(timestampInSeconds);

时间戳定义并获取到之后,可以将其存储到环境变量或者全局变量中,这样你就可以在接口中引用该变量了。【前置操作】中的脚本是接口发送前执行的代码片段,所以在接口发送时可以获取到存储在环境变量中的时间戳。
将时间戳存储在环境变量中的脚本参考:
// 将获取到的时间戳 timestampInSeconds 存储到环境变量的 timestamp 字段中
pm.environment.set("timestamp",timestampInSeconds)
如果环境变量中没有 timestamp 字段,那么 Apifox 会自动创建一个:

在接口中引用环境变量示例如下,你可以用{{}}
包裹字段,或者通过【动态值->读取变量】找到存储在环境变量中的字段名,最后点击“插入”即可

总结
通过 Apifox,你可以轻松获取当前时间戳。使用【动态值】功能,在 URL 路径、form-data
或x-www-form-urlencoded
请求体中,可通过点击示例值的“魔棒”图标并在【数据生成器->时间戳】中获取。对于 JSON 或 XML 格式的请求体,可在【修改文档】或【运行】页面通过 Mock 或【动态值->数据生成器】获取。此外,通过在接口的【前置操作】中添加自定义脚本,使用 JavaScript 获取当前时间戳,并存储在环境变量中,实现在接口中引用。
知识扩展: