Python Requestsを使用してJSONデータをPOSTする方法

PYTHON3 チュートリアル

Python Requestsを使用してJSONデータをPOSTする方法

PythonでHTTPリクエストを簡単に扱うためのライブラリであるRequestsを使用して、サーバーにJSONデータをPOSTする方法を解説します。POSTリクエストは、サーバーにデータを送信する際によく使用されます。特に、REST APIとの通信においてJSON形式でデータを送ることが一般的です。

基本的なPOSTリクエストの送信

まずは、Requestsライブラリを使ってシンプルなJSONデータをPOSTする基本的な例から見ていきましょう。次のステップに従ってください。

  1. Requestsライブラリをインストールします。
  2. Pythonスクリプトを作成し、リクエストを送信します。
  3. サーバーからのレスポンスを処理します。

以下のコード例は、{“name”: “John”, “age”: 30} というJSONデータをPOSTリクエストで送信する方法を示しています。

import requests
import json

url = 'http://example.com/api'
data = {'name': 'John', 'age': 30}
headers = {'Content-Type': 'application/json'}

response = requests.post(url, data=json.dumps(data), headers=headers)

print(response.text)

エラーハンドリング

リクエストが失敗した場合に備えて、適切なエラーハンドリングを行うことが重要です。以下のコードは、ステータスコードをチェックしてエラーがあれば処理を行う例です。

import requests
import json

url = 'http://example.com/api'
data = {'name': 'John', 'age': 30}
headers = {'Content-Type': 'application/json'}

try:
    response = requests.post(url, data=json.dumps(data), headers=headers)
    response.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else", err)

応答データの処理

サーバーからの応答を受け取った後、そのデータを適切に処理する必要があります。以下のコードは、JSON形式のレスポンスを解析する方法を示しています。

import requests
import json

url = 'http://example.com/api'
data = {'name': 'John', 'age': 30}
headers = {'Content-Type': 'application/json'}

response = requests.post(url, data=json.dumps(data), headers=headers)

if response.status_code == 200:
    response_data = response.json()
    print(response_data)
else:
    print('Failed to get proper response from server')

以上の例では、Requestsライブラリを使用してJSONデータをPOSTリクエストで送信し、サーバーからの応答を処理する方法を説明しました。適切なヘッダーの設定やエラーハンドリングも重要であることを忘れないでください。

購読
通知
0 Comments
Inline Feedbacks
View all comments