Advanced·12 min·web · http · requests
HTTP fundamentals with requests
HTTP fundamentals
Every web app is just programs talking over HTTP. requests is the standard Python client — clean API, sensible defaults.
The verbs you'll actually use
- GET — read. Query string via
params=. - POST — create / submit. Body via
json=(auto-sets Content-Type) ordata=(form-encoded). - PUT / PATCH — update.
- DELETE — remove.
Reading the response
r.status_code— 200 OK, 404 not found, 500 server error, 401 unauth, 429 rate-limited.r.json()— parse JSON body (raises if not JSON).r.text— raw string body.r.headers— response headers dict.
Things that bite
- Always set a timeout:
requests.get(url, timeout=10). Otherwise a hung server hangs your program. - Use
r.raise_for_status()to turn 4xx/5xx into exceptions instead of silently succeeding. - Session pooling:
s = requests.Session()— reuses TCP connections, huge speedup for many calls to the same host.
Try it
- Call
https://httpbin.org/status/500and observe the status_code. - Set a header
{"X-PyRun": "hello"}and echo it back from/headers.