快轉到主要內容

用 Python 使用 REST API

·1603 字·4 分鐘
目錄

甚麼是REST API
#

REST API或是RESTful API指的是同一件事情,REST=Representational State Transfer,是一種基於http上API設計風格。REST API有以下要點:

  • URL - 你想要操作資料的網頁位址
  • Method - 操作資料的方法,包含Get、Post、Put(或Patch)、Delete
    • Post是新增資料;Put是更新。以上兩者一定會有body的資訊
    • Get和Delete不見得有body資訊
  • Content type - 呈現資料的方式

因此,REST API的優點有:

  • 統一的介面 - 用URL透過HTTP methond操作你的資料(如上述)
  • 無狀態(Stateless) - Server不會記住Client的狀態,每個請求都是獨立的。(任何server都可以處理,系統易於維護)
    • server會回傳client request結果的代號(e.g. 200….)

組成要件
#

  • Header - 告訴server"我是誰",要傳送甚麼樣的格式
    • 通常會有 content-type,Authorization
    • 目前支援的格式有json或是表單(x-www-form-urlencoded)
    • Authorization通常會是token,或是account/password
  • Body - 實際傳輸的data
  • HTTP狀態碼(Server回應)
    HTTP Code
    Http code Meaning
    200 Request is successful
    201 Create data successful
    205 No content (請求成功,但沒有資料返回)
    304 Not modified(該data從上次請求後並未變更)
    400 Bad request(請求格式錯誤)
    401 Unauthorized(需登入認證)
    403 Forbidden(已登入但無權限)
    404 Not found
    409 Conflict(data衝突或已存在)
    500 Internal server error
    503 Service unavailable

Python 實作
#

Python會使用到的library為requests,常用的function有requests.get()request.put()….參數會包含url、header、body..等

Header #

Header就是一個dictionary,通常會在裡面指定你的token、傳輸的資料型態

api_headers = {
    'Authorization': f'Bearer {token}',
    'Content-Type': 'application/json'
    'Accept': 'application/json'
}

上面範例在Authorization裡面傳入token,告知我們在body傳的資料格式為json,並且要求server回傳的資料是json。

Content-type 目前有兩種:
Type header requests
json application/json requests.put(url, json={….})
Form application/x-www-form-urlencoded requests.put(url, data={….})

上述的data都是dictionary。另外,絕大多數的 OAuth2 認證 API(路徑包含 /token 或 /oauth2)在換取 Token 時,規格都強制要求使用 application/x-www-form-urlencoded。
那麼用json和form的差異在哪裡?

參數 python做了甚麼 傳出去的payload
json=payload 把字典轉換成標準json字串 {“name”: “New Secret”, “folderId”: 10}
data=payload 把字典轉換成網址參數格式 name=New+Secret&folderId=10

若請求參數是網址的一部分
#

這種情況下不需要設定content-type, 直接用param:

url = "https://MY/SERVER"
query_params = {
    'parm1': 'xxx1',
    'parm2': 'xxx2'
}
response = requests.get(url, params=query_params)

自動管理Header
#

如果你的header要重複用很多次(很多API都會用到),那麼可以用下面方式讓python記住:

session = requests.Session()

# 只要設定一次,後續所有的請求都會帶上這個 Header
session.headers.update({
    'Accept': 'application/json',
    'Authorization': f'Bearer {token}'
})

# 之後發送請求就不必再傳 headers 了
response = session.get("https://api.example.com/data")

Requests
#

Delinea server REST API 中,取得token為例:

import requests

url = "https://your-server/oauth2/token"

# 第一步:設定 Header
headers = {
    'Accept': 'application/json', 
    'Content-Type': 'application/x-www-form-urlencoded'
}

# 第二步:設定 Body (因為是 urlencoded,所以用字典格式)
payload = {
    'grant_type': 'password',
    'username': 'your_user',
    'password': 'your_password'
}

# 第三步:發送請求 (指定 headers 參數)
response = requests.post(url, headers=headers, data=payload)

print(response.json())

requests.xxx()有一個參數是verify,如果不寫的話會默認為True,python就會檢查seerver SSL憑證,若檢查發生問題,就會吐出SSLCertVerificationError。因此若只是內部測試,可指定verify=False,繞過SSL檢查,但僅供測試。
你也可以直接指定你的SSL憑證位址 verify='PATH/TO/CERTIFICATE'

參考資料
#

Gemini
RESTful API 概念與開發規範
什麼是 RESTful API?從日常生活理解 REST 架構原理


閱讀次數: