#Why this matters
Web security assessments and veb-tahlil CTF challenges rarely end after a single curl command. You often need to log in, capture a session cookie or CSRF token, follow pagination across fifty API pages, or verify whether an endpoint enforces object-level access control across sequential IDs. Python's requests library combined with the standard-library json module turns tedious browser repetition into clean, repeatable scripts.
#Structured HTTP requests with timeouts
Building URLs with string concatenation (f"{base}?q={user_input}") breaks whenever input contains &, =, or spaces, and creates parameter-pollution bugs. Instead, pass dictionaries to params or json so requests encodes them properly and sets the right headers.
| Argument | Purpose | Key detail |
|---|---|---|
params |
URL query string | Automatically URL-encodes keys and values |
json |
JSON request body | Serialises dict and sets Content-Type: application/json |
data |
Form-encoded body | Sets application/x-www-form-urlencoded for dicts |
headers |
Custom HTTP headers | Used for Authorization or custom API keys |
timeout |
Wait limit in seconds | Tuple (connect, read), e.g. (3.0, 10.0) |
allow_redirects |
Follow 3xx responses | Defaults to True; set False to inspect Location |
import requests
resp = requests.get(
"http://lab.local:8080/api/v1/items",
params={"category": "sensors", "page": 1},
headers={"Accept": "application/json"},
timeout=(3.0, 10.0),
)
resp.raise_for_status()
data = resp.json()
print(f"Returned {len(data.get('results', []))} items")Notice resp.raise_for_status(): by default, requests does not raise an exception on HTTP 404 or 500. Calling raise_for_status() prevents your script from trying to parse an HTML error page as JSON.
#Persisting cookies with requests.Session
Single requests.get() and requests.post() calls are stateless: any Set-Cookie header sent by the server is discarded once the call finishes. A requests.Session() object acts like a lightweight scriptable browser that preserves cookies, shares default headers, and reuses the underlying TCP/TLS connection.
Use a with requests.Session() as s: context manager so pooled sockets close cleanly when your script ends:
import json
import requests
BASE = "http://lab.local:8080"
with requests.Session() as s:
s.headers.update({"User-Agent": "CyberSamSU-LabClient/1.0"})
login = s.post(
f"{BASE}/api/login",
json={"username": "student", "password": "lab-password"},
timeout=(3.0, 10.0),
)
login.raise_for_status()
profile = s.get(f"{BASE}/api/profile", timeout=(3.0, 10.0))
profile.raise_for_status()
print(json.dumps(profile.json(), indent=2))When an API returns a bearer token inside the login JSON instead of a cookie, attach it to the session headers once with s.headers["Authorization"] = f"Bearer {token}" so every later call includes it automatically.
#Handling multi-step flows and JSON safely
Real REST APIs and multi-stage challenges often chain tokens, redirects, or cursor pagination. Keep automation resilient by wrapping network calls in try/except requests.RequestException and checking response types before calling .json():
import requests
def fetch_all_pages(session: requests.Session, url: str) -> list[dict]:
items = []
cursor = None
while True:
params = {"cursor": cursor} if cursor else {}
resp = session.get(url, params=params, timeout=(3.0, 10.0))
if resp.status_code == 429:
raise RuntimeError("Rate limit reached; back off and retry later")
resp.raise_for_status()
if "application/json" not in resp.headers.get("Content-Type", ""):
raise ValueError("Expected JSON response from API")
payload = resp.json()
items.extend(payload.get("items", []))
cursor = payload.get("next_cursor")
if not cursor:
break
return itemsUsing .get("items", []) avoids KeyError crashes if an endpoint changes or omits optional fields.
#Defending and common mistakes
Server defenders should verify object ownership on every API route, bind CSRF tokens to user sessions for cookie-authenticated endpoints, enforce rate limiting (429 Too Many Requests), and serve TLS 1.3 on production APIs.
Common client mistakes to avoid:
- Omitting
timeout, which leavesrequestswaiting forever if a server stalls. - Setting
verify=Falseand silencing TLS certificate warnings permanently instead of trusting a lab CA certificate viaverify="/path/to/lab-ca.pem". - Passing a dictionary to
data=when the API expects JSON, which sends form-encoded text instead ofapplication/json. - Calling
requests.post()andrequests.get()separately and wondering why the login cookie disappeared. - Calling
resp.json()without checkingstatus_codeorContent-Type, causingjson.JSONDecodeErroron HTML login redirects.
#Summary
- Use
paramsandjsonarguments inrequestsso query strings and JSON bodies are encoded safely, and always pass atimeout. - Wrap multi-request workflows in
with requests.Session() as s:to persist cookies, shareAuthorizationheaders, and reuse connections. - Call
raise_for_status(), verifyContent-Type, and use.get()when reading parsed JSON payloads. - Keep automated testing strictly within authorised lab scope and respect rate limits.