Real-World Examples with Requests

The Requests library simplifies various tasks in Python, making it a powerful tool for real-world applications. Below are some practical examples showcasing its capabilities:


Using APIs with Requests

APIs (Application Programming Interfaces) enable seamless data exchange between applications. With Requests, you can interact with APIs like GitHub or OpenWeatherMap.

Example: Fetching Weather Data from OpenWeatherMap

import requests
 
API_KEY = "your_openweathermap_api_key"
city = "Delhi"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
 
response = requests.get(url)
 
if response.status_code == 200:
    data = response.json()
    print("City:", data["name"])
    print("Temperature:", data["main"]["temp"], "°C")
    print("Weather:", data["weather"][0]["description"])
else:
    print("Failed to fetch weather data")

Automating Form Submissions

Automating form submissions is useful for testing or interacting with web services that require form inputs.

Example: Automating a Login Form

import requests
 
url = "https://example.com/login"
data = {
    "username": "your_username",
    "password": "your_password"
}
 
response = requests.post(url, data=data)
 
if response.status_code == 200:
    print("Login successful")
    print("Response:", response.text)
else:
    print("Login failed")

Scraping Data from Web Pages

While Requests doesn’t parse HTML, it can be paired with libraries like BeautifulSoup to scrape data from web pages.

Example: Scraping Titles from a Blog

import requests
from bs4 import BeautifulSoup
 
url = "https://example-blog.com"
response = requests.get(url)
 
if response.status_code == 200:
    soup = BeautifulSoup(response.content, "html.parser")
    titles = soup.find_all("h2", class_="post-title")
    for i, title in enumerate(titles, 1):
        print(f"Post {i}: {title.text.strip()}")
else:
    print("Failed to fetch webpage data")

Try It Yourself

Problem 1: Fetch GitHub User Data

Fetch and display the public repositories of a GitHub user using the GitHub API.

Show Solution
import requests
 
username = "octocat"
url = f"https://api.github.com/users/{username}/repos"
 
response = requests.get(url)
 
if response.status_code == 200:
    repos = response.json()
    print(f"{username}'s Repositories:")
    for repo in repos:
        print("-", repo["name"])
else:
    print("Failed to fetch data")

Problem 2: Automate a Contact Form Submission

Send a POST request to a fake contact form endpoint and display the server response.

Show Solution
import requests
 
url = "https://httpbin.org/post"
data = {
    "name": "John Doe",
    "email": "john.doe@example.com",
    "message": "Hello, I am interested in your services."
}
 
response = requests.post(url, data=data)
 
print("Server Response:", response.json())

By combining Requests with other libraries and techniques, you can automate a variety of tasks, interact with APIs, and scrape useful data for real-world applications.