Code Reference

Requests

Python · Reference cheat sheet

Requests

Python · Reference cheat sheet


📋 Overview

requests is the popular third-party HTTP client. Install: pip install requests. Use it for GET/POST, JSON APIs, headers, and timeouts. For stdlib-only code, see urllib — most apps prefer requests.

🔧 Core concepts

APIRole
requests.get(url, ...)HTTP GET
requests.post(url, ...)HTTP POST
params=Query string dict
json=Encode body as JSON + set content-type
data= / files=Form body / multipart
headers=Custom headers
timeout=Connect/read timeout (seconds)
r.raise_for_status()Raise on 4xx/5xx
r.json() / r.text / r.contentParse response
requests.Session()Reuse cookies/connection

💡 Examples

GET + JSON:

import requests

r = requests.get(
    "https://httpbin.org/get",
    params={"q": "python"},
    timeout=10,
)
r.raise_for_status()
print(r.json()["args"])

POST JSON:

import requests

r = requests.post(
    "https://httpbin.org/post",
    json={"name": "Ada", "active": True},
    headers={"X-Client": "demo"},
    timeout=10,
)
r.raise_for_status()
print(r.json()["json"])

Session:

import requests

with requests.Session() as s:
    s.headers.update({"Accept": "application/json"})
    r = s.get("https://httpbin.org/headers", timeout=10)
    print(r.json()["headers"]["Accept"])

Error handling:

import requests

try:
    r = requests.get("https://httpbin.org/status/404", timeout=5)
    r.raise_for_status()
except requests.HTTPError as e:
    print("http error", e.response.status_code)
except requests.RequestException as e:
    print("network/other", e)

⚠️ Pitfalls

  • Always set timeout= — otherwise calls can hang forever.
  • Check status: raise_for_status() or inspect r.status_code.
  • r.json() fails on empty/non-JSON bodies — catch ValueError.
  • Don’t disable TLS verify (verify=False) in production.
  • Third-party package: pin versions in requirements; not in the stdlib.

On this page