APIリクエストの基本構造

Pythonを使ったAPI入門

Chris Ramakers

Engineering Manager

URLとは?

  • URL = Uniform Resource Locator(統一資源位置指定子)
  • APIリソースを指す、一定の構造を持ったアドレス
  • 特定のAPIリソースとやり取りするためにURLをカスタマイズ
http://350.5th-ave.com/unit/243
Pythonを使ったAPI入門

URLを分解する

A diagram showing different parts of a URL: Protocol (http://), Domain (350.5th-ave.com), Port (:80), Path (/unit/243), and Query (?floor=77).

  • プロトコル = 移動手段
  • ドメイン = オフィスビルの住所
  • ポート = 建物に入るときに使う入口
  • パス = 建物内の特定のオフィス区画
  • クエリ = 追加の指示
Pythonを使ったAPI入門

requestsを使ったクエリパラメータの追加

# Append the query parameter to the URL string
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 引数を使ってクエリパラメータを追加
# Create dictionary
query_params = {'floor': 77, 'elevator': True}
# Pass the dictionary using the `params` argument
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にあるオフィスビルの243号室
  • URLhttp://350.5th-ave.com/unit/243

アクション

HTTPメソッド 操作 説明
GET 読み取り 郵便受けの中身を確認
POST 作成 新しい荷物を郵便受けに入れる
PUT 更新 郵便受けの中の荷物をすべて新しい荷物に置き換える
DELETE 削除 郵便受けからすべての荷物を取り除く
1 HTTPメソッドは全部で9種類ありますが、シンプルなREST APIで必要となるのはこの4つだけです
Pythonを使ったAPI入門

POSTとPUTによるデータ送信

# GET = Retrieve a resource
response = requests.get('http://350.5th-ave.com/unit/243')

# POST = Create a resource response = requests.post('http://350.5th-ave.com/unit/243', data={"key": "value"}) # PUT = Update an existing resource response = requests.put('http://350.5th-ave.com/unit/243', data={"key": "value"})
# DELETE = Remove a resource response = requests.delete('http://350.5th-ave.com/unit/243')
  • requests パッケージには、各HTTPメソッドに対応する関数があります
  • data 引数を使って、POSTリクエストまたはPUTリクエストにデータを渡します。
Pythonを使ったAPI入門

練習しましょう!

Pythonを使ったAPI入門

Preparing Video For Download...