API 請求的基本結構

Python API 入門

Chris Ramakers

Engineering Manager

什麼是 URL?

  • URL = Uniform Resource Locator(統一資源定位器)
  • 指向 API Resource 的結構化位址
  • 客製化 URL 以操作特定的 API Resources
http://350.5th-ave.com/unit/243
Python API 入門

剖析 URL

一張圖示出 URL 的構成:Protocol(http://)、Domain(350.5th-ave.com)、Port(:80)、Path(/unit/243)、以及 Query(?floor=77)。

  • Protocol = 傳輸方式
  • Domain = 大樓的門牌地址
  • Port = 進入時使用的入口
  • Path = 大樓內的特定辦公室
  • Query = 其他補充指示
Python API 入門

用 requests 加入查詢參數

# 將查詢參數直接接在 URL 字串後
response = requests.get('http://350.5th-ave.com/unit/243?floor=77&elevator=True')
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
  • params 參數加入查詢參數
# 建立字典
query_params = {'floor': 77, 'elevator': True}
# 透過 `params` 參數傳入字典
response = requests.get('http://350.5th-ave.com/unit/243', params=query_params)
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
Python API 入門

HTTP 動詞

  • 目的地:350 5th Ave 辦公大樓的 Unit 243
  • URLhttp://350.5th-ave.com/unit/243

動作

Verb Action Description
GET Read 查看信箱內容
POST Create 投遞新包裹進信箱
PUT Update 以新包裹取代所有舊包裹
DELETE Delete 移除信箱內所有包裹
1 HTTP 動詞共有 9 個,但對於簡單的 REST API,通常只需這 4 個。
Python API 入門

用 POST 與 PUT 傳送資料

# GET = 取得資源
response = requests.get('http://350.5th-ave.com/unit/243')

# POST = 建立資源 response = requests.post('http://350.5th-ave.com/unit/243', data={"key": "value"}) # PUT = 更新現有資源 response = requests.put('http://350.5th-ave.com/unit/243', data={"key": "value"})
# DELETE = 移除資源 response = requests.delete('http://350.5th-ave.com/unit/243')
  • 每個動詞在 requests 套件中都有對應方法。
  • data 參數在 POST 或 PUT 請求中傳遞資料。
Python API 入門

一起來練習吧!

Python API 入門

Preparing Video For Download...