0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでHTTPリクエストを簡単に扱う!requestsライブラリ徹底解説

Posted at

PythonでHTTPリクエストを簡単に扱う!requestsライブラリ徹底解説

目次

  1. はじめに

  2. requestsとは?

  3. インストール方法

  4. 基本的な使い方

    • GETリクエスト
    • POSTリクエスト
  5. よく使うオプション

    • ヘッダーの追加
    • パラメータの付与
    • タイムアウト設定
  6. 応用例

    • JSONデータの送受信
    • ファイルのアップロード/ダウンロード
  7. エラーハンドリング

  8. まとめ


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やスクレイピング、ファイル操作など、幅広い用途で活躍

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?