Requests Module

Requests Module in Python: In the modern world, programs rarely live in isolation. They need to talk to the internet—fetching data from an API, uploading a…

Concept Explanation

In the modern world, programs rarely live in isolation. They need to talk to the internet—fetching data from an API, uploading a file to a server, or automating a form submission. While Python has a built-in library called urllib, it is notoriously difficult to use.

Enter Requests. It is one of the most downloaded Python packages of all time because it makes interacting with the web incredibly simple. With Requests, sending an HTTP request doesn't require complex manual configuration of headers, cookies, and data streams; it just works.

Key Features:

  • Simple Syntax: requests.get() and requests.post() are intuitive.
  • Automatic JSON Parsing: Converts API responses to Python dictionaries automatically.
  • Status Code Checking: Built-in ways to verify if a request was successful.
  • Authentication & Headers: Easy way to add security or identify your app to a server.

Syntax or Core Structure

The Response Object

Every request returns a "Response" object containing three main things:

  1. r.status_code: 200 (OK), 404 (Not Found), 500 (Server Error).
  2. r.text: The raw HTML or string content.
  3. r.json(): The content parsed as a Python Dictionary.
import requests

# Sending a basic GET request
r = requests.get("https://api.github.com/events")

# Checking success
if r.status_code == 200:
    print("Success!")
    data = r.json() # Automatically turns JSON into a Python list/dict

Code Example #1 (Basic)

Performing a GET request with parameters (Query Strings).

import requests

url = "https://httpbin.org/get"
data_params = {
    "search": "Python",
    "page": 2
}

# The URL becomes: https://httpbin.org/get?search=Python&page=2
response = requests.get(url, params=data_params)

print(f"Final URL: {response.url}")
print(f"Content: {response.json()['args']}")

Code Example #2 (Intermediate)

Sending data to a server using a POST request.

import requests

endpoint = "https://httpbin.org/post"
payload = {
    "username": "Harsh",
    "apiKey": "xyz123"
}

# Sending JSON data
r = requests.post(endpoint, json=payload)

if r.ok: # Shortcut for status_code < 400
    print("Post successful!")
    print(r.json()["json"])

Real World Example

Price Tracker: Imagine you want to fetch the current price of Bitcoin from a public crypto API.

import requests

def get_crypto_price(coin="bitcoin"):
    url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd"
    
    try:
        response = requests.get(url)
        response.raise_for_status() # Raise error if status is not 2xx
        
        data = response.json()
        price = data[coin]["usd"]
        return price
    except Exception as e:
        return f"Error: {e}"

bitcoin_price = get_crypto_price()
print(f"Current Bitcoin Price: ${bitcoin_price} USD")

Common Mistakes

  1. Forgetting to install: Requests is NOT built-in. You must run pip install requests in your terminal first.
  2. Ignoring Timeouts: If a website is down, your program might "hang" forever. Always use a timeout: requests.get(url, timeout=5).
  3. Using .text for binary data: If you are downloading an image or a PDF, use r.content (bytes) instead of r.text (string).
  4. Security: Never "hardcode" your API keys directly in the script. Use environment variables (which we'll cover in the next section).

Best Practices

  • Timeout Everything: Always specify a timeout to prevent your app from freezing.
  • Session Reuse: If you are making many requests to the same site, use requests.Session() to speed up connection times.
  • Custom User-Agent: Some websites block Python scripts. Adding a headers={'User-Agent': '...'} can help identify your app as a real browser.

Practice Exercises

  1. The Status Checker: Write a list of 5 URLs. Create a script that loops through them and prints "ONLINE" or "OFFLINE" based on their status codes.
  2. JSON Searcher: Fetch data from https://jsonplaceholder.typicode.com/todos. Print only the titles of tasks that are NOT completed.
  3. The Poster: Find a free "Webhook" service (like Webhook.site) and send a POST request with your name and a "Hello" message.