Python 24-Day Course - Day 18: HTTP Requests

Day 18: HTTP Requests

Installing the requests Library

pip install requests

GET Request

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)  # 200
print(response.headers["content-type"])

data = response.json()
print(data["title"])

HTTP Methods

MethodPurposerequests Function
GETRetrieve datarequests.get()
POSTCreate datarequests.post()
PUTUpdate data (full)requests.put()
PATCHUpdate data (partial)requests.patch()
DELETEDelete datarequests.delete()

POST Request

new_post = {
    "title": "New Post",
    "body": "Sending HTTP requests from Python",
    "userId": 1
}

response = requests.post(
    "https://jsonplaceholder.typicode.com/posts",
    json=new_post
)
print(response.status_code)  # 201
print(response.json()["id"])

Query Parameters and Headers

# Query parameters
params = {"userId": 1, "_limit": 5}
response = requests.get(
    "https://jsonplaceholder.typicode.com/posts",
    params=params
)

# Custom headers
headers = {
    "Authorization": "Bearer YOUR_TOKEN",
    "Content-Type": "application/json"
}
response = requests.get(url, headers=headers)

Error Handling

def fetch_data(url):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()  # Raises exception for 4xx, 5xx errors
        return response.json()
    except requests.exceptions.Timeout:
        print("Request timed out")
    except requests.exceptions.HTTPError as e:
        print(f"HTTP error: {e}")
    except requests.exceptions.ConnectionError:
        print("Cannot connect to server")
    return None

Today’s Exercises

  1. Write a program that fetches weather data from a public API and displays it.
  2. Use the GitHub API to retrieve a specific user’s repository list.
  3. Create a function that fetches data sequentially from multiple URLs and merges it.

Was this article helpful?