Перейти к основному содержимому
Python HTTP Requests, Sessions & REST APIs
Урок 5 из 10

Python HTTP Requests, Sessions & REST APIs

Automate multi-step HTTP workflows, cookie sessions, and REST API requests safely in Python using the requests and json libraries.

Средний 25 мин Программирование
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.

Цели обучения

  • Construct parameterised GET and JSON POST requests with explicit timeouts and headers
  • Maintain authentication cookies and connection pooling across requests with requests.Session
  • Parse REST API JSON responses safely and handle HTTP error status codes
  • Test multi-step web workflows and authorisation checks responsibly in lab environments

Рекомендуется заранее: Python Fundamentals for Security TasksPython Sockets & Binary Protocol Clients

#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
python
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.

Authenticated workflow with requests.SessionAuthenticated workflow with requests.SessionClientAppPOST /api/login (username, password)200 OK + Set-Cookie: sid=abc123; HttpOnlySession stores sid=abc123 automaticallyGET /api/profile (Cookie: sid=abc123)200 OK {"user": "student", "role": "viewer"}

Use a with requests.Session() as s: context manager so pooled sockets close cleanly when your script ends:

python
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():

python
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 items

Using .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 leaves requests waiting forever if a server stalls.
  • Setting verify=False and silencing TLS certificate warnings permanently instead of trusting a lab CA certificate via verify="/path/to/lab-ca.pem".
  • Passing a dictionary to data= when the API expects JSON, which sends form-encoded text instead of application/json.
  • Calling requests.post() and requests.get() separately and wondering why the login cookie disappeared.
  • Calling resp.json() without checking status_code or Content-Type, causing json.JSONDecodeError on HTML login redirects.

#Summary

  • Use params and json arguments in requests so query strings and JSON bodies are encoded safely, and always pass a timeout.
  • Wrap multi-request workflows in with requests.Session() as s: to persist cookies, share Authorization headers, and reuse connections.
  • Call raise_for_status(), verify Content-Type, and use .get() when reading parsed JSON payloads.
  • Keep automated testing strictly within authorised lab scope and respect rate limits.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания