curlコマンドをPython requestsに変換

curlコマンドをPython requestsライブラリのコードに変換する方法を解説。ヘッダー、認証、JSONペイロード、ファイルアップロードをPythonらしいコードに変換しましょう。

Python

詳細な説明

curlからPython Requestsへの変換

Python の requests ライブラリは、Pythonエコシステムで最も人気のあるHTTPクライアントです。curlコマンドをPythonに変換することは、開発者が最も頻繁に行うタスクのひとつです。

GETリクエスト

curl:

curl -H "Accept: application/json" https://api.example.com/users

Python:

import requests

response = requests.get(
    "https://api.example.com/users",
    headers={"Accept": "application/json"}
)
data = response.json()

JSONを使ったPOST

curl:

curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice"}'

Python:

response = requests.post(
    "https://api.example.com/users",
    json={"name": "Alice"}
)

json パラメータを使うと、Content-Typeヘッダーの設定と辞書のシリアライズが自動的に行われます。

認証

curl:

curl -u user:pass https://api.example.com/data

Python:

response = requests.get(
    "https://api.example.com/data",
    auth=("user", "pass")
)

ファイルアップロード

curl:

curl -F "file=@photo.jpg" https://api.example.com/upload

Python:

with open("photo.jpg", "rb") as f:
    response = requests.post(
        "https://api.example.com/upload",
        files={"file": f}
    )

対応表リファレンス

curlフラグ Python requestsの対応
-H headers={} 辞書
-d data= パラメータ
-d(JSON) json= パラメータ
-u auth=() タプル
-F files={} 辞書
-x proxies={} 辞書
--timeout timeout= 秒数
-L デフォルトで有効
-k verify=False

Python requestsはリダイレクト、Cookie、コネクションプーリングを自動的に処理するため、ほとんどのユースケースで生のcurlコマンドよりも簡潔に記述できます。

ユースケース

Python開発者がAPIドキュメントにある動作確認済みのcurlコマンドを、requestsライブラリを使った本番用のPythonコードに変換する必要がある場合に使用します。

Try It — Curl to Code Converter

フルツールを開く