LoginSignup
3
2

More than 3 years have passed since last update.

Postman Pre-request After-request Scripts~UUID作成~Timestamp取得~SHA256変換

Last updated at Posted at 2020-08-26

はじめに

Web APIをテストするにはPostmanはよく使われていますよね、前はほとんど簡単なテストなので直接Requestを投げてResponseをもらうだけです。
最近はちょっとだけ複雑なテストをやってRequest前後は簡単なスクリプトを実行する必要があります、唯一なUUIDや、今現在のシステム時間を取得など。またはサーバーのTokenを取得した後に次のRequestでセットする。

Postman画面

❶はPre-requestの書く場所
❷はAfter-requestの書く場所

image.png

Pre-request Scripts

UUID作成

❶番Pre-requestのタブに下記のスクリプトで

var uuid = require('uuid');
postman.setEnvironmentVariable('myuuid', uuid.v4());

使う時にRequestのBodyに

{
    "uuid": "{{$myuuid}}",
    ...略...
}

更に簡単な書き方
RequestのBodyに{{$guid}}を使います、事前定義などは要りません

{
    "uuid": "{{$guid}}",
    ...略...
}

Timestamp取得

❶番Pre-requestのタブに下記のスクリプトで

const moment = require('moment')
pm.globals.set('logTime', moment().format('YYYY-MM-DD HH:mm:SS'))
console.log(pm.globals.get('logTime'))

使う時は上記と同じRequestのBodyに{{$logTime}}で取得

SHA256変換

Pre-requestのタブに下記のスクリプトで

var sha256Value = CryptoJS.SHA256("123456789");
postman.setGlobalVariable("sha256Value", sha256Value);

※postman.setGlobalVariable()/postman.getGlobalVariable()はpm.globals.set()/pm.globals.get()と同じ

使う時は上記と同じRequestのBodyに{{$sha256Value}}で取得

After-request Scripts

❷番Testsのタブに下記のスクリプトで

token = pm.response.json()['data']['token']
console.log(token)
postman.setGlobalVariable("token", token);

最後に

というのは、PostmanはRequestの前後にJavaScriptを実行する能力が持ちます、なので事前事後のデータ処理、引数設定などが可能です。上記の例だけではなくJavaScript実行さえであればいろんな可能性がありますよね。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2