Skip to content

HTTP Requests with the requests Library

diagram the four things every scripted HTTP call needs mermaid
A request in a script is not a request in a browser: there is nobody watching it, so it has to handle its own failure. A missing timeout can hang forever, a 4xx does not raise on its own, and a retry without a delay turns one failure into a burst. A Session is what makes repeated calls to the same host both faster and consistent.
requests_get.py
import requests
 
r = requests.get("https://httpbin.org/get", timeout=10)
r.raise_for_status()
print(r.status_code)
print(r.json())
requests_headers.py
import requests
 
headers = {"User-Agent": "PythonCentralHubBot/1.0"}
r = requests.get("https://httpbin.org/headers", headers=headers, timeout=10)
print(r.json())
requests_session.py
import requests
 
with requests.Session() as s:
    s.headers.update({"User-Agent": "MyBot/1.0"})
    r = s.get("https://httpbin.org/cookies/set?hello=world", timeout=10)
    r.raise_for_status()
 
    r2 = s.get("https://httpbin.org/cookies", timeout=10)
    print(r2.json())

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading