總結

Python API 入門

Chris Ramakers

Engineering Manager

API 基礎

  • API 的角色
  • API 的類型
  • URL 組成
  • 請求與回應的結構
  • HTTP 動詞

Python API 入門

用 Python 操作 API

Requests 套件

import requests

HTTP 方法

# 讀取資源
requests.get('https://api.my-music.com')
# 建立資源
requests.post('https://api.my-music.com', data={...})
# 更新資源
requests.put('https://api.my-music.com', data={...})
# 刪除資源
requests.delete('https://api.my-music.com')

URL 參數

query_params = {'artist': 'Deep Purple'}
requests.get('http://api.my-music.com', params=query_params)

標頭(Headers)

headers = {'accept': 'application/json'}
response = requests.get('http://api.my-music.com', headers=headers)
print(response.headers.get('content-type'))

狀態碼

response = requests.get('http://api.my-music.com')
print(response.status_code)
Python API 入門

進階主題

  • 驗證
    • 基本驗證(Basic Authentication)
      headers = {'Authorization':'Basic am9obkBleGF...'}
      
    • API 金鑰/權杖驗證
      headers = {'Authorization': 'Bearer faaa1c9f4...'}
      
  • 結構化資料
    • 要求 JSON 格式資料
      requests.get('https://api.my-music.com', headers={'accept': 'application/json'})
      
    • 傳送 JSON 格式資料
      playlists = [{"Name":"My favorite songs"}, {"Name":"Road Trip"}]
      requests.post('https://api.my-music.com/playlists/', json=playlists)
      
Python API 入門

錯誤處理

  • 錯誤類型
    • 連線錯誤
    • HTTP 錯誤
      • 4XX 用戶端錯誤
      • 5XX 伺服器錯誤
  • 以狀態碼處理錯誤
    • response.status_code
  • 以例外處理錯誤
    • raise_for_error()
import requests
from requests.exceptions import ConnectionError, HTTPError

try:
    response = requests.get("http://api.music-catalog.com/albums") 
    response.raise_for_status()

except ConnectionError as conn_err: 
    print(f'Connection Error! {conn_err}.')

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
Python API 入門

恭喜你!

Python API 入門

Preparing Video For Download...