http
The Python http package is a collection of modules for working with HTTP. The module for making HTTP requests and handling responses is http.client. Other modules include http.server for building HTTP servers and http.cookies for handling cookies.
Here’s a quick example:
>>> from http.client import HTTPConnection
>>> conn = HTTPConnection("www.example.com")
>>> conn.request("GET", "/")
>>> response = conn.getresponse()
>>> response.status
200
>>> conn.close()
Key Features
- Sends HTTP requests
- Receives HTTP responses
- Handles HTTP headers and status codes
- Supports HTTP/1.1 protocol
- Supports building HTTP servers
- Provides tools for parsing and generating cookies
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
HTTPConnection |
Class | Handles HTTP connections |
HTTPSConnection |
Class | Handles HTTPS connections |
HTTPResponse |
Class | Represents the response from an HTTP request |
responses |
Dictionary | Maps HTTP status codes to status messages |
Examples
Sending a simple HTTP GET request:
>>> from http.client import HTTPConnection
>>> conn = HTTPConnection("www.example.com")
>>> conn.request("GET", "/")
>>> response = conn.getresponse()
>>> response.status
200
>>> response.read()
b'<!doctype html>...'
Handling HTTP headers:
>>> from http.client import HTTPConnection
>>> conn = HTTPConnection("www.example.com")
>>> conn.request("GET", "/")
>>> response = conn.getresponse()
>>> response.getheaders()
[('Content-Type', 'text/html; charset=UTF-8'), ...]
Common Use Cases
- Making HTTP requests to web servers
- Retrieving and processing HTTP responses
- Managing HTTP headers and status codes
- Implementing HTTP clients and servers
- Handle cookies
Real-World Example
Suppose you need to download the HTML content of a web page and save it to a file. You can achieve this using the http package:
>>> from http.client import HTTPConnection
>>> conn = HTTPConnection("www.example.com")
>>> conn.request("GET", "/")
>>> response = conn.getresponse()
>>> with open("example.html", "wb") as file:
... file.write(response.read())
...
>>> conn.close()
In this example, the http package is used to send an HTTP GET request to a server, retrieve the HTML content, and save it to a local file, demonstrating how to perform basic HTTP client tasks.
Related Resources
Tutorial
Python's urllib.request for HTTP Requests
In this tutorial, you'll be making HTTP requests with Python's built-in urllib.request. You'll try out examples and review common errors encountered, all while learning more about HTTP requests and Python in general.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated July 9, 2025