2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Postman Collection のスクリプト機能でリクエストとレスポンスを動的に定義する

Posted at

この記事はPostman Adventcalender 2024 12月14日の記事です。

Postman Collectionで設定するAPIコールにはスクリプト機能があり、JavaScriptによって動的にパラメータを指定することが可能になっています。

固定値であれば過去紹介した変数を用いた方が便利ですが、例えばAPIコール時の時間を挿入するなど、動的に定義しないといけない値の操作に用います。

Pre-Request と Post-Response

スクリプトを設定する箇所は2種類あります。Pre-Requestはリクエスト前のパラメータの操作、Post-Responseはレスポンスの文字列操作、になります。
いずれもpmという環境変数に値が入るのでリクエストであればpm.request,レスポンスであればpm.responseで操作可能です。

さっそくやってみる

ではいつも通りrequest catherをもちいて簡単なPOST APIコールを作成します。
次にスクリプトタブをクリックします。
image.png
Pre-Requestに以下のスクリプトをコピーして実行してみます。
image.png

// 任意のヘッダーを設定する(例えば Content-Type)
pm.request.headers.add({ key: 'Content-Type', value: 'application/json' });

// 現在時刻を取得(ISO形式)
const currentDate = new Date().toISOString();  // 例: 2024-12-25T12:34:56.789Z

// リクエストボディを設定(例: JSON形式)
const requestBody = {
    name: "John Doe",
    email: "john.doe@example.com",
    timestamp: currentDate  // 現在時刻を追加
};

// リクエストのボディを設定
pm.request.body.update({
    mode: 'raw',
    raw: JSON.stringify(requestBody)
});

// ログで確認
console.log("Pre-request Script executed, sending data:", requestBody);

動的にリクエストボディが生成され以下の値を受け取ることが確認できます。

{"name":"John Doe","email":"john.doe@example.com","timestamp":"2024-12-25T05:04:49.040Z"}

この例では以下の行でヘッダーを追記し

pm.request.headers.add({ key: 'Content-Type', value: 'application/json' });

以下の行でリクエストボディを追記しています。

const requestBody = {
    name: "John Doe",
    email: "john.doe@example.com",
    timestamp: currentDate  // 現在時刻を追加
};

// リクエストのボディを設定
pm.request.body.update({
    mode: 'raw',
    raw: JSON.stringify(requestBody)
});

ヘッダータブで以下のように別のContent-Typeを追記するとAppendされ出力は以下のようになります。

Content-Type: test, application/json

一方ボディタブの設定は以下のように指定してもスクリプトの内容によってUpdate(上書き)されます。
image.png

pm.request.headers.addのようにヘッダーはaddを用いるためappendされますが、m.request.body.updateのようにボディにaddは存在せず、updateを用いる必要があるためです。

次にPost-Responseです。

// レスポンスをテキストとして取得
const responseText = pm.response.text();

// 現在時刻を取得(ISO形式)
const currentDate = new Date().toISOString();  // 例: 2024-12-25T12:34:56.789Z

// レスポンスの内容と現在時刻をログに出力
console.log("Response received at " + currentDate + ":", responseText);

のようにすることで戻り時間と共にレスポンスをコンソールに出力できます。
image.png

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?