API 入門

Python API 入門

Chris Ramakers

Engineering Manager

什麼是 API?

  • Application Programming Interface
  • 一組通訊規則與能力
  • 讓軟體之間彼此互動

一張圖示說明電子郵件用戶端與郵件伺服器透過 API 互動,將郵件傳送到 john@acme.com。

Python API 入門

Web API、用戶端與伺服器

  • Web API 透過網際網路以 HTTP 溝通
  • 用戶端送出請求給伺服器
  • 伺服器回傳回應給用戶端

一張圖示說明用戶端與伺服器透過 API 經由網際網路互動,並標示請求與回應訊息。

  • 請求/回應循環
Python API 入門

Web API 類型

  • SOAP
    • 著重嚴謹、正式的 API 設計
    • 企業級應用
  • REST
    • 著重簡潔與可擴充性
    • 最常見的 API 架構
  • GraphQL
    • 著重彈性
    • 針對效能最佳化
1 https://www.postman.com/state-of-api/api-technologies/#api-technologies
Python API 入門

在 Python 中使用 API

urllib

  • 隨 Python 附帶
  • 功能強大但不太友善
from urllib.request import urlopen
api = "http://api.music-catalog.com/"

with urlopen(api) as response:
  data = response.read()
  string = data.decode()
  print(string)

requests

  • 內建多種強大功能
  • 更容易使用
import requests
api = "http://api.music-catalog.com/"

response = requests.get(api)
print(response.text)
Python API 入門

Let's code!

Python API 入門

Preparing Video For Download...