從 PostMan 串接 API 的範例說明 — 設定 URL, HTTP method,header & body
利用 PostMan 串接 API 時,為了設定發送給 server 的 request,我們主要設定 URL, HTTP method,header & body 四個欄位。
- URL
API 的網址。 - httpMethod
說明 request 的目的,常見的有 get, post, delete, put & patch。 - httpBody
上傳給 server 的資料,通常搭配 httpMethod post & put,應用於建立或修改資料。 - http header
以 key value 格式描述的資料,比方 api key & Content-Type。
接下來我們將以多個 API 的範例說明如何從 PostMan 串接 API,。
ps: 對 PostMan 不熟的朋友可先參考以下連結。
Reqres GET API
- 文件說明
HTTP method 為 GET。
- PostMan 設定
request:
選擇 GET,輸入網址 https://reqres.in/api/users?page=2。
response:
server 回傳 JSON,status code 為 200。
Reqres POST API
- 文件說明
HTTP method 為 POST,上傳的資料為 JSON 格式,需設定 HTTP header 的 content-type 為 application/json。
- PostMan 設定
request:
選擇 POST,輸入網址 https://reqres.in/api/users。
切換到 Body 分頁,選擇 raw & JSON,輸入上傳的 JSON 內容。
因為選擇上圖的 JSON,PostMan 會自動幫我們加入 content-type 為 application/json 的 HTTP header,我們不用再自己輸入。
切換到下圖的 Headers 分頁,點選 hidden,顯示 PostMan 自動產生的 header。
PostMan 果然貼心地幫我們輸入了 content-type 為 application/json。
response:
server 回傳 JSON,status code 為 201。
FavQs POST API
- 文件說明
API 網址的開頭為 https://favqs.com/api/。
HTTP header 需設定 token,比方 token 為 12345,表示要在 HTTP header 加入欄位名稱 Authorization
,對應的 value 為 Token token=12345
。
HTTP method 為 POST,上傳的資料為 JSON 格式,需設定 HTTP header 的 content-type 為 application/json。
- PostMan 設定
request:
選擇 POST,輸入網址 https://favqs.com/api/users。
切換到 Body 分頁,選擇 raw & JSON,輸入上傳的 JSON 內容。
此 API 必須輸入的 header 是 Content-Type & Authorization。切換到 Headers 分頁,PostMan 已幫我們輸入 Content-Type,因此我們只需新增 Authorization 和它對應的內容。
response:
server 回傳 JSON,status code 為 200。