みなさんこんにちは、現役エンジニアのサメハックです
未経験からWebエンジニアに転職し、
現在正社員として5年働いたのちフリーランスとして独立しました。
Pythonの解説シリーズです。
今回はRequestsを使ってHTTP通信を行う方法について学んでいきましょう!
駆け出しエンジニアや未経験の方、
また新入社員を指導する先輩社員にとっても
わかりやすいように解説していきます!
この記事を読むと・・・
- Requestsがインストール出来る
- HTTP通信ができる
HTTP通信をしよう!
環境構築

Requestsとは
PythonのライブラリでHTTP通信をするために使われます。
主にスクレイピングで使われますが、APIを叩くこともできます。
Requestsを使う構文
request.get(URL,オプション)
# ■オプション
# headers
# timeout
# cookies
# params
Requestsをインストールしよう!
環境によってコマンドが若干変わるので、エラーが出たら上から順に入力してみてください。
どれかでうまくいくと思います。
$ pip install requests
$ pip3 install requests
$ pip install requests --user
$ pip3 install requests --user
実際に動かしてみよう!
data_get.py
import requests
# 対象のURL ★これはフリーのサンプルサイトです
GET_API = 'https://jsonplaceholder.typicode.com/users/1'# GET処理
response = requests.get(GET_API)
print("↓response")
print(response)
print("↓response.status_code")
print(response.status_code)
print("↓response.encoding")
print(response.encoding)
print("↓response.text")
print(response.text)
print("↓response.content #バイナリデータ")
print(response.content)
print("↓response.cookies")
print(response.cookies)
print("↓response.headers")
print(response.headers)
print("↓type(response)")
print(type(response))
print("↓response.json()")
print(response.json())
ターミナルで実行
% python3 data_get.py
↓response
↓response.status_code
200
↓response.encoding
utf-8
↓response.text
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
↓response.content #バイナリデータ
b'{\n "id": 1,\n "name": "Leanne Graham",\n "username": "Bret",\n "email": "Sincere@april.biz",\n "address": {\n "street": "Kulas Light",\n "suite": "Apt. 556",\n "city": "Gwenborough",\n "zipcode": "92998-3874",\n "geo": {\n "lat": "-37.3159",\n "lng": "81.1496"\n }\n },\n "phone": "1-770-736-8031 x56442",\n "website": "hildegard.org",\n "company": {\n "name": "Romaguera-Crona",\n "catchPhrase": "Multi-layered client-server neural-net",\n "bs": "harness real-time e-markets"\n }\n}'
↓response.cookies
<requestscookiejar[]>
↓response.headers
{'Date': 'Fri, 18 Jun 2021 14:04:05 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'X-Powered-By': 'Express', 'X-Ratelimit-Limit': '1000', 'X-Ratelimit-Remaining': '999', 'X-Ratelimit-Reset': '1624025057', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 'true', 'Cache-Control': 'max-age=43200', 'Pragma': 'no-cache', 'Expires': '-1', 'X-Content-Type-Options': 'nosniff', 'Etag': 'W/"1fd-+2Y3G3w049iSZtw5t1mzSnunngE"', 'Via': '1.1 vegur', 'CF-Cache-Status': 'MISS', 'cf-request-id': '0ac108b0920000243169a64000000001', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Report-To': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v2?s=7US%2FL905H0e%2BWK9cQhWkty2jRsODgysDrIfTYelm%2BR%2FY0i%2B6pxOB2iaWnxgWZWYHLoBdNh%2FvFFVh0byxvrGfdRo4QrSThtCRL%2B73uMiqHQiRR0oLCxqjQ2Dfg61sa4TbyURyKqFhoqeVf1wvoZ8g2iEpyPsMuQ%3D%3D"}],"group":"cf-nel","max_age":604800}', 'NEL': '{"report_to":"cf-nel","max_age":604800}', 'Server': 'cloudflare', 'CF-RAY': '6615109418862431-NRT', 'Content-Encoding': 'gzip', 'alt-svc': 'h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443"; ma=86400'}
↓type(response)
<class 'requests.models.response'="">
↓response.json()
{'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.biz', 'address': {'street': 'Kulas Light', 'suite': 'Apt. 556', 'city': 'Gwenborough', 'zipcode': '92998-3874', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}}, 'phone': '1-770-736-8031 x56442', 'website': 'hildegard.org', 'company': {'name': 'Romaguera-Crona', 'catchPhrase': 'Multi-layered client-server neural-net', 'bs': 'harness real-time e-markets'}}</requestscookiejar[]>
おまけ:curlを使ってターミナルからHTTP通信
ちなみにcurlでは・・・
ターミナルからHTTPリクエストをするものにcurlというコマンドがあります。
参考にですが、curlも叩いてみましょう!
% curl https://jsonplaceholder.typicode.com/users/1
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}%
まとめ

- Requestsライブラリを使うとHTTP通信が可能

満足いただけたら、1クリックなのでSNSフォローしてもらえると嬉しいです🦈