Pythonのurllib.request
モジュールは、URLを開くための関数とクラスを定義しています。これは基本的な認証、リダイレクト、クッキーなど、複雑な世界でのURLの開放を助けます。
GETリクエストの送信
urllib.request
モジュールを使用してGETリクエストを送信するには、以下のようにRequest
オブジェクトを作成し、urlopen
に渡します。
import urllib.request
url = 'https://example.com/api/v1/resource'
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as res:
body = res.read()
POSTリクエストの送信
POSTリクエストを送信するには、Request
オブジェクト作成時にdata
パラメータを指定します。
import json
import urllib.request
url = 'https://example.com/api/v1/resource'
data = {
'foo': 123,
}
headers = {
'Content-Type': 'application/json',
}
req = urllib.request.Request(url, json.dumps(data).encode(), headers)
with urllib.request.urlopen(req) as res:
body = res.read()
例外処理
urlopen
は二種類の例外を投げます。
urllib.error.URLError
: HTTP通信に失敗したときurllib.error.HTTPError
: HTTPステータスコードが4xxまたは5xxだったとき
import urllib.request
url = 'https://example.com/api/v1/resource'
req = urllib.request.Request(url)
try:
with urllib.request.urlopen(req) as res:
body = res.read()
except urllib.error.HTTPError as err:
print(err.code)
except urllib.error.URLError as err:
print(err.reason)
以上、Pythonのurllib.request
モジュールの基本的な使い方について説明しました。このモジュールを使うことで、PythonからHTTP APIを利用することができます。