Skip to main content
Albero Academy

HTTP with requests

Call web APIs and handle responses with the requests library.

APIs10 min

Most programs eventually talk to the web — fetching data, calling services, posting updates. The requests library is the de-facto standard for HTTP in Python: a clean, human-friendly API over the messy details of the protocol.

GET and POST

requests
import requests
# GET with query parameters
r = requests.get("https://api.example.com/students",
params={"limit": 10}, timeout=10)
data = r.json() # parse the JSON response body
# POST JSON, with an auth header
requests.post("https://api.example.com/students",
json={"name": "Ana"},
headers={"Authorization": "Bearer TOKEN"})

Handling the response

Check the status, then parse. raise_for_status() turns a 4xx/5xx into an exception so failures don't pass silently:

robust calls
r = requests.get(url, timeout=10)
r.status_code # 200
r.raise_for_status() # raises on 4xx/5xx
r.json() # parsed body (or r.text for raw)

Key takeaways

  1. 01requests.get/post/put/delete call HTTP APIs cleanly.
  2. 02params= adds query string; json= sends a JSON body; headers= adds headers.
  3. 03r.json() parses the response; r.status_code / raise_for_status() check success.
  4. 04Always set a timeout, and handle non-2xx responses and network errors.
  5. 05It is the de-facto standard HTTP client for Python.

Finished this chapter?

Mark it complete to track your progress through Python.