PythonでHTTPリクエストを簡単に扱う!requestsライブラリ徹底解説
目次
-
はじめに
-
requestsとは? -
インストール方法
-
基本的な使い方
- GETリクエスト
- POSTリクエスト
-
よく使うオプション
- ヘッダーの追加
- パラメータの付与
- タイムアウト設定
-
応用例
- JSONデータの送受信
- ファイルのアップロード/ダウンロード
-
エラーハンドリング
-
まとめ
1. はじめに
PythonでWeb APIにアクセスしたり、Webサイトからデータを取得したりする場合、標準ライブラリの urllib でも可能ですが、コードが複雑になりがちです。
そこで登場するのが requests ライブラリです。シンプルな構文でHTTPリクエストを扱えるため、Python界隈では事実上の標準となっています。
2. requestsとは?
requests は Python 用の HTTP クライアントライブラリです。
主な特徴:
- GETやPOSTなどHTTPメソッドの送信が簡単
- パラメータやヘッダーの追加が容易
- Cookieやセッション管理が可能
- SSL/TLSも簡単に扱える
3. インストール方法
pip install requests
インストール後、import requests で使用可能です。
4. 基本的な使い方
GETリクエスト
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
print(response.status_code) # HTTPステータスコード
print(response.text) # レスポンス内容(文字列)
print(response.json()) # JSONとして取得
POSTリクエスト
url = "https://jsonplaceholder.typicode.com/posts"
data = {"title": "foo", "body": "bar", "userId": 1}
response = requests.post(url, json=data) # JSON形式で送信
print(response.status_code)
print(response.json())
5. よく使うオプション
ヘッダーの追加
headers = {"User-Agent": "MyApp/1.0"}
response = requests.get(url, headers=headers)
URLパラメータの付与
params = {"userId": 1}
response = requests.get("https://jsonplaceholder.typicode.com/posts", params=params)
タイムアウト設定
try:
response = requests.get(url, timeout=5) # 5秒でタイムアウト
except requests.Timeout:
print("タイムアウトしました")
6. 応用例
JSONデータの送受信
payload = {"name": "Alice", "age": 25}
response = requests.post("https://httpbin.org/post", json=payload)
print(response.json())
ファイルのアップロード
files = {'file': open('example.txt', 'rb')}
response = requests.post("https://httpbin.org/post", files=files)
print(response.json())
ファイルのダウンロード
url = "https://via.placeholder.com/150"
response = requests.get(url)
with open("image.png", "wb") as f:
f.write(response.content)
7. エラーハンドリング
try:
response = requests.get("https://httpbin.org/status/404")
response.raise_for_status() # ステータスコードが200番台以外は例外
except requests.HTTPError as e:
print("HTTPエラー:", e)
except requests.RequestException as e:
print("リクエストエラー:", e)
8. まとめ
-
requestsはPythonでHTTP通信を行う際の定番ライブラリ - GET/POSTだけでなく、ヘッダー、パラメータ、ファイル操作も簡単
- エラー処理やタイムアウト設定も組み込みで可能
- Web APIやスクレイピング、ファイル操作など、幅広い用途で活躍