Andromeda
Note

Requests Module (Python)

Definition

The industry-standard third-party module for making HTTP requests in Python, abstracting the complexity of URLs and networking.

Why It Matters

The ‘requests’ module is the ‘human-friendly’ interface to the modern web. Without it, interacting with APIs requires handling low-level socket data and complex headers manually. It is the tool that makes the ‘Internet of Data’ accessible to any programmer, enabling the automation of the global information layer.

Core Concepts

  • Making Requests: res = requests.get(url) downloads the content.
  • Error Handling: Always call res.raise_for_status() immediately after a request. This raises an exception if the download failed, preventing the program from continuing with “garbage” data.
  • Response Properties:
    • res.status_code: The HTTP status (e.g., 200 for success, 404 for not found).
    • res.text: The content as a string.
  • Downloading Large Files: Use the Iterative Chunking pattern to prevent memory crashes.
import requests

url = "https://api.github.com/events"
res = requests.get(url)

try:
    res.raise_for_status()
    data = res.json()
    print(f"Status: {res.status_code}")
except Exception as exc:
    print(f"There was a problem: {exc}")

Connected Concepts