0
0

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】Python requests ライブラリ― シンプルに書けて、実務とセキュリティで最強

0
Posted at

はじめに

Python で HTTP 通信 を扱うとき、真っ先に名前が挙がるのが requests ライブラリです。

API 呼び出し、Web スクレイピング、業務自動化、セキュリティテスト(CTF / 脆弱性検証)まで、
「HTTP を触るならまず requests」 と言っても過言ではありません。

本記事では、

  • 基本的な使い方
  • 実務で必須のパターン
  • セキュリティ視点での活用

コード中心でわかりやすく 解説します。


requests とは何か?

requests は Python 用の 高水準 HTTP クライアントライブラリ です。

標準ライブラリ urllib と比べると、

項目 urllib requests
可読性 低い 非常に高い
学習コスト 高い 低い
実務向き
セキュリティ用途

という特徴があります。

「HTTP 通信を“人間の言葉”で書けるようにしたライブラリ」
それが requests です。


インストール

pip install requests

基本:GET リクエスト

import requests

response = requests.get("https://httpbin.org/get")

print(response.status_code)
print(response.text)

よく使うレスポンス属性

response.status_code   # HTTP ステータスコード
response.text          # 文字列としての本文
response.json()        # JSON(APIで頻出)
response.headers       # レスポンスヘッダ

クエリパラメータ付き GET

params = {
    "q": "python",
    "page": 1
}

response = requests.get(
    "https://httpbin.org/get",
    params=params
)

print(response.url)

✔ URL エンコードを自動で処理してくれる
✔ 手動で ?a=1&b=2 を書く必要なし


POST リクエスト

JSON 送信(最も一般的)

data = {
    "username": "admin",
    "password": "password123"
}

response = requests.post(
    "https://httpbin.org/post",
    json=data
)

フォーム送信

response = requests.post(
    "https://httpbin.org/post",
    data={"a": 1, "b": 2}
)

Header / 認証情報の扱い(重要)

カスタム Header

headers = {
    "User-Agent": "Mozilla/5.0",
    "Authorization": "Bearer YOUR_TOKEN"
}

requests.get(url, headers=headers)

Cookie

cookies = {
    "sessionid": "abcdef123456"
}

requests.get(url, cookies=cookies)

セキュリティテスト・API 検証では必須スキル


タイムアウトと例外処理(実務必須)

import requests

try:
    response = requests.get(url, timeout=5)
    response.raise_for_status()
except requests.Timeout:
    print("タイムアウト")
except requests.HTTPError as e:
    print("HTTPエラー:", e)
except requests.RequestException as e:
    print("通信エラー:", e)

❌ timeout を書かない
→ 本番でプロセスが固まる原因になります。


Session:ログイン状態を保持する

session = requests.Session()

session.post(
    "https://example.com/login",
    data={"user": "admin", "pass": "admin"}
)

response = session.get("https://example.com/dashboard")

Session のメリット

  • Cookie 自動保持
  • 認証状態を維持
  • 実ブラウザに近い挙動

ファイルのアップロード・ダウンロード

ファイルアップロード

files = {
    "file": open("test.txt", "rb")
}

requests.post(url, files=files)

ファイルダウンロード

response = requests.get(url)

with open("sample.zip", "wb") as f:
    f.write(response.content)

セキュリティ視点での requests

requests は以下の用途で 事実上の標準 です:

  • SQL Injection / XSS テスト
  • SSRF 検証
  • API トークン再利用
  • CTF / TryHackMe / HTB の PoC 作成

例:SSRF テスト

payload = "http://127.0.0.1:8080/admin"

requests.get(
    "https://vulnerable.site",
    params={"url": payload}
)

よくある落とし穴

ミス 結果
timeout 未指定 フリーズ
status_code 未確認 バグを見逃す
Token を直書き 情報漏洩
URL を手で組み立てる バグ地獄

requests を使わない方がいい場面

  • 非同期・高並列処理aiohttp
  • ブラウザ完全再現 → Playwright / Selenium
  • HTTP/2・gRPC → 専用クライアント

まとめ

  • requestsPython HTTP 通信の第一選択
  • 実務・自動化・セキュリティ全対応
  • シンプルだが奥が深い

requests を制する者は、Python での外部通信を制する。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?