In this article, I will show you how to execute HTTP requests with urllib.request.
urllib.request.Request
method.urllib.request.urlopen
method to get response.json
module to parse the response.If the response is in json format, use json.load
to parse the response.
Here is an example.
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/
は偽ユーザーの情報を返してもらえますので、使えやすいです。
The following example tries an HTTP request using an unauthenticated API:https://randomuser.me/api/
.
https://randomuser.me/api/
is easy to use, and it returns fake user information.
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)
This is a simple way to execute HTTP requests with urllib.request.