← Knowledge Base
PythonReference note1 min read · updated 2026-11-27

Python: call an HTTP API with requests

GET and POST with timeouts, status checks, JSON and sessions.

pythonrequestsapi
import requests

r = requests.get("https://api.github.com/users/octocat", timeout=15,
                 headers={"Accept": "application/vnd.github+json"})
r.raise_for_status()                 # raises for 4xx/5xx
data = r.json()
print(data["login"], r.headers.get("X-RateLimit-Remaining"))

with requests.Session() as s:        # reuses connections
    s.headers["User-Agent"] = "my-script/1.0"
    resp = s.post("https://httpbin.org/post", json={"a": 1}, timeout=15)

Always set a timeout: by default requests waits forever. Handle requests.RequestException. Respect rate limits and read the API's terms; cache responses you reuse. Keep tokens in environment variables (os.environ["TOKEN"]), never in the source.