API Navigator Logo

Basic Python HTTP Request Example

Author: Newtum

This guide provides a foundational example of how to make a simple HTTP request in Python using the standard library's `http.client` module. While `requests` is often preferred, understanding the basics is valuable.

Using `http.client` for a GET Request

The `http.client` module provides a low-level interface for working with HTTP. You need to establish a connection, send the request, and then read the response.

import http.client
import json

# Establish a connection to the host
conn = http.client.HTTPSConnection("jsonplaceholder.typicode.com")

# Send a GET request for a specific resource
conn.request("GET", "/todos/1")

# Get the response
response = conn.getresponse()

# Read the response data
data = response.read()

# Decode the data and parse the JSON
todo_item = json.loads(data.decode("utf-8"))

print("Status:", response.status, response.reason)
print("Response Body:")
print(json.dumps(todo_item, indent=2))

# Close the connection
conn.close()

Why `requests` is more common

As you can see, `http.client` is more verbose than the `requests` library. `requests` handles connection management, JSON decoding, and other details automatically, making it a more convenient choice for most applications.

import requests

# The equivalent request using the 'requests' library
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
print(response.json())