urllib.requestでHTTPリクエストを実行する方法を紹介します。
urllib.request.Request
関数でHTTPリクエストを作成する。urllib.request.urlopen
関数の引数にして、関数を実行してレスポンスを取得する。json
モジュールで取得したJSONレスポンスを解析する。もし、レスポンスはJSON形式であれば、json.load
を使ってレスポンスの解析ができます。
具体例は、
with urllib.request.urlopen(req) as res:
body = json.load(res)
... # Do something you want.
以下の例は、https://randomuser.me/api/
という認証なしのAPIを使って、HTTPリクエストを試してみました。
https://randomuser.me/api/
は偽ユーザーの情報を返してもらえますので、使えやすいです。
import urllib.request
import json
reqUrl = 'https://randomuser.me/api/'
reqData = None
headers = {
'Content-Type': 'application/json'
}
method = 'GET'
req = urllib.request.Request(reqUrl, reqData, headers, method=method)
with urllib.request.urlopen(req) as res:
body = json.load(res)
print(body)
print(f"gender: {body['results'][0]['gender']}")
print(f"name: {body['results'][0]['name']['first']} {body['results'][0]['name']['last']}")
print(f"country: {body['results'][0]['location']['country']}")
urllib.request — Extensible library for opening URLs
Free API – Top 15 APIs You Can Use For Free (No Key Needed)
以上簡単にurllib.requestでHTTPリクエストを実行する方法を紹介しました。