http
import http.client / from http.server import HTTPServer The http module is a foundational part of Python’s standard library for working with the HTTP protocol. It provides two main submodules: http.client for making HTTP requests (acting as an HTTP client) and http.server for creating HTTP servers. These building blocks give you low-level control over HTTP communication without needing third-party libraries like requests or httpx.
http.client
The http.client module implements the client side of HTTP. It provides the HTTPConnection class for connecting to web servers and the HTTPSConnection class for secure SSL/TLS connections. While higher-level libraries like requests are more convenient, http.client is useful when you need fine-grained control over connection behavior or want to understand how HTTP works under the hood.
HTTPConnection
The primary class for making HTTP requests. Create a connection to a host, then use its methods to send requests.
http.client.HTTPConnection(host, port=None, timeout=None, source_address=None)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
host | str | — | The server host to connect to |
port | int | 80 | The port number (80 for HTTP, 443 for HTTPS) |
timeout | float | None | Socket timeout in seconds |
source_address | tuple | None | Source address (host, port) for the connection |
Returns: An HTTPConnection object.
HTTPSConnection
Secure HTTP connection using SSL/TLS. Use this for HTTPS URLs.
http.client.HTTPSConnection(host, port=None, key_file=None, cert_file=None, timeout=None, source_address=None, context=None)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
host | str | — | The server host to connect to |
port | int | 443 | The port number for HTTPS |
key_file | str | None | Path to PEM-formatted private key file |
cert_file | str | None | Path to PEM-formatted certificate file |
timeout | float | None | Socket timeout in seconds |
context | ssl.SSLContext | None | SSL context for certificate verification |
Returns: An HTTPSConnection object.
HTTPConnection Methods
| Method | Description |
|---|---|
request(method, url, body=None, headers={}) | Send an HTTP request |
getresponse() | Get the response from the server |
send(data) | Send data to the server |
close() | Close the connection |
set_debuglevel(level) | Set debug output level (0-3) |
http.server
The http.server module provides classes for building HTTP servers. It includes HTTPServer for basic server functionality and BaseHTTPRequestHandler for handling HTTP requests. These classes are the foundation for building custom web servers or REST APIs from scratch.
HTTPServer
Creates an HTTP server that listens for incoming connections.
http.server.HTTPServer(server_address, RequestHandlerClass)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
server_address | tuple | — | A (host, port) tuple specifying the address to bind to |
RequestHandlerClass | class | — | A subclass of BaseHTTPRequestHandler to handle requests |
Returns: An HTTPServer object.
BaseHTTPRequestHandler
Base class for handling HTTP requests. Override its methods to implement custom request handling.
from http.server import BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Handle GET requests
pass
Key Methods to Override:
| Method | Description |
|---|---|
do_GET() | Handle GET requests |
do_POST() | Handle POST requests |
do_PUT() | Handle PUT requests |
do_DELETE() | Handle DELETE requests |
do_HEAD() | Handle HEAD requests |
log_message(format, *args) | Custom logging |
SimpleHTTPRequestHandler
A ready-to-use request handler for serving static files from the current directory.
from http.server import SimpleHTTPRequestHandler
Examples
Making a GET request with http.client
import http.client
# Create an HTTP connection
conn = http.client.HTTPSConnection("example.com")
# Send a GET request
conn.request("GET", "/")
# Get the response
response = conn.getresponse()
print(f"Status: {response.status}")
print(f"Reason: {response.reason}")
print(f"Body: {response.read().decode('utf-8')}")
conn.close()
Status: 200
Reason: OK
Body: <!doctype html>
<html>...
Making a POST request with JSON data
import http.client
import json
# Prepare request data
payload = json.dumps({"name": "Alice", "score": 95})
headers = {"Content-Type": "application/json"}
# Create connection and send request
conn = http.client.HTTPSConnection("api.example.com")
conn.request("POST", "/submit", body=payload, headers=headers)
# Get response
response = conn.getresponse()
data = response.read().decode("utf-8")
print(f"Response: {data}")
conn.close()
Creating a simple HTTP server
from http.server import HTTPServer, BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(b"<html><body><h1>Hello, World!</h1></body></html>")
else:
self.send_response(404)
self.end_headers()
# Start the server
server = HTTPServer(("localhost", 8000), MyHandler)
print("Server running on http://localhost:8000")
server.serve_forever()
Server running on http://localhost:8000
Using SimpleHTTPRequestHandler to serve files
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
# Change to the directory you want to serve
os.chdir("/path/to/your/files")
# Start server
server = HTTPServer(("0.0.0.0", 8000), SimpleHTTPRequestHandler)
print("Serving files on http://localhost:8000")
server.serve_forever()
Creating an API endpoint with JSON response
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class APIHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/api/users":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
self.wfile.write(json.dumps(users).encode())
else:
self.send_response(404)
self.end_headers()
server = HTTPServer(("localhost", 8080), APIHandler)
server.serve_forever()
# GET /api/users returns:
# [{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
Common Patterns
Handling query parameters manually
import http.client
from urllib.parse import urlencode
params = urlencode({"page": 1, "limit": 10})
conn = http.client.HTTPSConnection("api.example.com")
conn.request("GET", f"/items?{params}")
response = conn.getresponse()
data = response.read()
conn.close()
Custom headers and authentication
import http.client
import base64
# Create basic auth header
credentials = base64.b64encode(b"username:password").decode()
headers = {
"Authorization": f"Basic {credentials}",
"Accept": "application/json"
}
conn = http.client.HTTPSConnection("api.example.com")
conn.request("GET", "/protected", headers=headers)
response = conn.getresponse()
conn.close()
Using timeout for slow connections
import http.client
# Set a 5-second timeout
conn = http.client.HTTPConnection("slow-server.com", timeout=5.0)
try:
conn.request("GET", "/")
response = conn.getresponse()
print(response.status)
except http.client.HTTPException as e:
print(f"Request failed: {e}")
finally:
conn.close()
Errors
- http.client.HTTPException — Base exception for all HTTP client errors
- http.client.NotConnected — Raised when trying to use a closed connection
- http.client.IncompleteRead — Raised when response is truncated
- http.client.BadStatusLine — Raised when server sends invalid status line
- http.client.RemoteDisconnected — Raised when connection is closed unexpectedly
For server errors:
- OSError — Raised when the server fails to bind to the specified address (e.g., port already in use)
See Also
- socket — Low-level socket APIs that http.client builds upon
- json — Work with JSON data in HTTP requests and responses
- urllib.parse — Parse and build URLs for HTTP requests