PythonとcURLを組み合わせてAPIリクエストを行う方法について解説します。Pythonはリクエストを自動化でき、cURLは多用途のツールであるため、この組み合わせは非常に強力です。
PythonとcURLの基本
PythonでcURLリクエストを行う基本的なコードは次のようになります。
import subprocess
curl_command = 'curl https://api.example.com/users'
output = subprocess.check_output(curl_command, shell=True)
output = output.decode('utf-8')
print(output)
このコードは、subprocess
モジュールを使ってcURLコマンドを実行し、その出力を取得しています。
GETリクエストの例
GETリクエストを行う一例として、以下のようなコードがあります。
import urllib.request
import json
url = 'https://petstore.swagger.io/v2/store/inventory'
try:
with urllib.request.urlopen(url) as response:
body = json.loads(response.read())
headers = response.getheaders()
status = response.getcode()
print(headers)
print(status)
print(body)
except urllib.error.URLError as e:
print(e.reason)
このコードは、指定したURLにGETリクエストを送信し、レスポンスのボディ、ヘッダー、ステータスコードを表示します。
POSTリクエストの例
POSTリクエストを行う一例として、以下のようなコードがあります。
import urllib.request
import json
url = 'https://petstore.swagger.io/v2/store/order'
req_header = {
'Content-Type': 'application/json',
}
req_data = json.dumps({
'id': 0,
'petId': 0,
'quantity': 0,
'shipDate': '2020-04-10T10:11:13.419Z',
'status': 'placed',
'complete': True,
})
req = urllib.request.Request(url, data=req_data.encode(), method='POST', headers=req_header)
try:
with urllib.request.urlopen(req) as response:
body = json.loads(response.read())
headers = response.getheaders()
status = response.getcode()
print(headers)
print(status)
print(body)
except urllib.error.URLError as e:
print(e.reason)
このコードは、指定したURLにPOSTリクエストを送信し、レスポンスのボディ、ヘッダー、ステータスコードを表示します。
以上がPythonとcURLを使ったAPIリクエストの基本的な使い方です。これらのコードを参考に、自分のプロジェクトに適したリクエストを作成してみてください。.