ในระบบงานปัจจุบัน เรามีการทดสอบ API ผ่าน Postman อยู่แล้ว ซึ่งนอกจากต้องเตรียม request body หรือ query parameter หรือ header แล้ว ยังต้องเตรียม OAuth2 authentication ด้วย เราก็ต้องไปเรียก authentication server เพื่อเอา access token ไป request API

Postman authorization pane

ทีมเราขี้เกียจที่จะ copy access token มาแปะใน placeholder ทุกครั้ง เรากับ QA เลยลองใช้ Pre-request Script ใน Postman เพื่อ automate ขั้นตอนนี้

สร้าง Environment ใน Postman แล้วเพิ่ม variable สำหรับการขอ access token ลงไป ตัวอย่างเช่น

Postman authorization pane

จากนั้นผมก็จะเพิ่ม Pre-request Script สำหรับการขอ access token และ set environment variable ชื่อ access_token ผ่านการใช้ function ของ Postman API จากรูปผมใช้ Microsoft Azure ซึ่ง script จะมาประมาณนี้

ดู Postman JavaScript reference ได้ที่ https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/