☼
⌃
☰

Requests

Table of Contents

The de-facto standard Python library for HTTP. Clean, intuitive API for all HTTP methods, session management, authentication, file upload, and streaming. Used throughout security tooling — from quick API testing scripts to automated vulnerability checkers.

Related: Python API Testing Methodology

Installation

SHELL
pip install requests --break-system-packages

Basic Requests

PYTHON
import requests

# GET
response = requests.get("https://httpbin.org/get")
print(response.status_code)     # 200
print(response.headers)         # dict of response headers
print(response.text)            # response body as string
print(response.json())          # parse JSON body

# POST with JSON body
response = requests.post(
    "https://httpbin.org/post",
    json={"username": "alice", "password": "secret"}
)

# POST with form data
response = requests.post(
    "https://httpbin.org/post",
    data={"username": "alice", "password": "secret"}
)

# PUT, PATCH, DELETE
requests.put("https://api.example.com/users/1", json={"name": "Bob"})
requests.patch("https://api.example.com/users/1", json={"name": "Bob"})
requests.delete("https://api.example.com/users/1")

# HEAD — get headers without body
response = requests.head("https://example.com")
print(response.headers.get("Server"))

Query Parameters

PYTHON
# Append as dict — requests handles URL encoding
params = {"q": "python security", "page": 1, "limit": 10}
response = requests.get("https://api.example.com/search", params=params)
print(response.url)   # https://api.example.com/search?q=python+security&page=1&limit=10

Headers

PYTHON
headers = {
    "Authorization": "Bearer eyJhbGci...",
    "Content-Type": "application/json",
    "User-Agent": "Mozilla/5.0 (custom)",
    "X-API-Key": "abc123",
}

response = requests.get("https://api.example.com/profile", headers=headers)

Authentication

PYTHON
# HTTP Basic Auth
response = requests.get(
    "https://api.example.com/protected",
    auth=("username", "password")
)

# Bearer token (via header)
response = requests.get(
    "https://api.example.com/protected",
    headers={"Authorization": f"Bearer {token}"}
)

# Digest auth
from requests.auth import HTTPDigestAuth
response = requests.get(url, auth=HTTPDigestAuth("user", "pass"))

# Custom auth class
from requests.auth import AuthBase
class ApiKeyAuth(AuthBase):
    def __init__(self, key):
        self.key = key
    def __call__(self, r):
        r.headers["X-API-Key"] = self.key
        return r

response = requests.get(url, auth=ApiKeyAuth("my-key"))

Sessions

Sessions persist cookies, headers, and connection pooling across requests. Essential for testing authenticated application flows.

PYTHON
session = requests.Session()

# Set headers for all requests in this session
session.headers.update({"User-Agent": "TestClient/1.0"})

# Login — session stores the returned cookie
session.post("https://target.com/login", data={
    "username": "alice",
    "password": "password"
})

# Subsequent requests carry the session cookie automatically
response = session.get("https://target.com/dashboard")
response = session.get("https://target.com/admin")

# Inspect cookies
print(session.cookies.get_dict())

# Close session when done
session.close()

# Or use as context manager
with requests.Session() as s:
    s.post("https://target.com/login", data={"user": "alice", "pass": "pw"})
    r = s.get("https://target.com/profile")

Response Object

PYTHON
r = requests.get("https://api.example.com/data")

r.status_code           # 200
r.ok                    # True if status < 400
r.headers               # dict-like object
r.headers["Content-Type"]
r.text                  # body as string
r.content               # body as bytes
r.json()                # parse JSON (raises if not JSON)
r.url                   # final URL (after redirects)
r.history               # list of redirect responses
r.elapsed               # timedelta of request duration
r.encoding              # detected encoding

# Raise an exception for 4xx/5xx responses
r.raise_for_status()    # raises HTTPError if bad status

Error Handling

PYTHON
import requests
from requests.exceptions import (
    HTTPError, ConnectionError, Timeout, RequestException
)

try:
    response = requests.get("https://api.example.com/data", timeout=5)
    response.raise_for_status()
    data = response.json()
except HTTPError as e:
    print(f"HTTP error: {e.response.status_code}")
except ConnectionError:
    print("Connection failed")
except Timeout:
    print("Request timed out")
except RequestException as e:
    print(f"Request error: {e}")

Timeouts

Always set a timeout — by default requests waits forever:

PYTHON
# Connect timeout, read timeout
response = requests.get(url, timeout=(3.05, 10))

# Single value applies to both
response = requests.get(url, timeout=5)

File Upload

PYTHON
# Single file
with open("report.pdf", "rb") as f:
    response = requests.post(
        "https://target.com/upload",
        files={"file": f}
    )

# Specify filename and content-type (for filter bypass testing)
with open("shell.php", "rb") as f:
    response = requests.post(
        "https://target.com/upload",
        files={"file": ("image.jpg", f, "image/jpeg")}   # spoofed name and type
    )

# File upload with additional form fields
with open("image.png", "rb") as f:
    response = requests.post(
        "https://target.com/upload",
        files={"file": f},
        data={"description": "profile photo"}
    )

Proxying Through Burp Suite

PYTHON
proxies = {
    "http":  "http://127.0.0.1:8080",
    "https": "http://127.0.0.1:8080",
}

# Disable SSL verification for Burp's certificate
response = requests.get(
    "https://target.com/api/profile",
    proxies=proxies,
    verify=False
)

# Suppress the InsecureRequestWarning
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

Streaming (Large Responses)

PYTHON
# Download large file without loading into memory
with requests.get(url, stream=True) as r:
    r.raise_for_status()
    with open("output.bin", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

Security-Focused Patterns

PYTHON
# Enumerate IDs (IDOR testing)
session = requests.Session()
session.headers["Authorization"] = f"Bearer {token}"

for user_id in range(1, 1000):
    r = session.get(f"https://target.com/api/users/{user_id}")
    if r.status_code == 200:
        print(f"ID {user_id}: {r.json()}")

# Test multiple payloads against an endpoint
payloads = ["' OR 1=1--", "admin'--", "\" OR \"1\"=\"1"]
for payload in payloads:
    r = requests.post("https://target.com/login",
        data={"username": payload, "password": "x"})
    print(f"{payload!r}: {r.status_code} {len(r.text)} bytes")

# Collect response sizes for parameter fuzzing
import time
params_to_test = ["debug", "admin", "test", "dev", "verbose"]
for param in params_to_test:
    r = requests.get(f"https://target.com/page?{param}=1")
    print(f"{param}: {r.status_code} {len(r.content)} bytes elapsed={r.elapsed.total_seconds():.3f}s")

Tips

  • Always set timeout — a default requests call blocks forever if the server doesn't respond
  • Use session when testing authenticated flows — cookies are maintained automatically between requests
  • verify=False disables SSL verification — necessary when proxying through Burp but never use it against real targets outside a test environment
  • response.raise_for_status() is the cleanest way to handle error responses in scripts — raises an exception you can catch rather than checking status_code everywhere
  • elapsed gives you response time per request — useful for detecting timing-based differences during blind injection testing