Of course! Let's break down putrequest in Python.

Summary
In Python, putrequest is a method used with the legacy http.client library. Its primary job is to initiate an HTTP request by sending the request line and the headers to the server.
It's a low-level method. You will almost always use it as part of the process of making an HTTP request with http.client, but you won't typically call it directly in modern applications.
Key Context: The http.client Library
First, it's important to understand where putrequest lives. It's part of Python's built-in http.client module, which is a low-level library for making HTTP requests.
- Low-Level: You are responsible for constructing the entire HTTP message: the request line (e.g.,
GET /path HTTP/1.1), the headers (e.g.,Host: example.com), and the body (if any). - Blocking: By default, it performs blocking network I/O, meaning your program will wait until the server responds.
- Legacy: For most new applications, especially those requiring more features like connection pooling, automatic redirects, or a cleaner API, the third-party
requestslibrary is the standard. It's built on top ofhttp.clientand other libraries to provide a much more user-friendly experience.
The Role of putrequest
When you make an HTTP request, you send a structured text message to the server. putrequest helps you build the beginning of that message.

The standard HTTP request format is:
METHOD /path/to/resource HTTP/Version
Header-Name: Header-Value
Another-Header: Another-Value
[Optional Request Body]
The putrequest method handles the first line: the request line.
Method Signature
http_client.putrequest(method, url, skip_host=False, skip_accept_encoding=False)
Parameters
method(string): The HTTP method you want to use. This is the action you're asking the server to perform. Common values are:"GET""POST""PUT""DELETE""HEAD""PATCH"
url(string): The path you are requesting on the server. This is just the path, not the full URL likehttp://example.com/api/data. TheHostheader must be set separately to specify the domain.skip_host(boolean, optional, defaultFalse): IfTrue, theputrequestmethod will not automatically add theHost: <host>header. You would be responsible for adding it yourself withputheader(). You usually want this to beFalse.skip_accept_encoding(boolean, optional, defaultFalse): IfTrue, it will not automatically add theAccept-Encoding: identityheader. This is also usually left asFalse.
A Practical Example: Making a GET Request
Let's walk through a complete example of using http.client to make a GET request. This will show you where putrequest fits into the entire process.
import http.client
import sys
# --- Configuration ---
host = 'www.python.org'
path = '/'
try:
# 1. Create a connection object
# We use HTTPSConnection for secure connections (HTTPS)
# For HTTP, you would use HTTPConnection(host)
print(f"Connecting to {host}...")
connection = http.client.HTTPSConnection(host)
# 2. Initiate the request with putrequest()
# This sends the line: "GET / HTTP/1.1"
# It also prepares the connection to receive headers.
print("Sending request line...")
connection.putrequest("GET", path)
# 3. Add necessary headers using putheader()
# The Host header is crucial for virtual hosting.
# putheader() adds a header line.
connection.putheader("Host", host)
connection.putheader("User-Agent", "My-Python-App/1.0")
connection.putheader("Accept", "text/html")
# 4. Signal that headers are finished with endheaders()
# This sends a blank line, which is required to separate headers from the body.
# For a GET request, there is no body, so this just finalizes the request.
print("Sending headers...")
connection.endheaders()
# 5. Get the response from the server
# This sends the request and waits for the server's response.
print("Getting response...")
response = connection.getresponse()
# 6. Process the response
print(f"Response status: {response.status} {response.reason}")
print("-" * 20)
# You can read the response body
if response.status == 200:
body = response.read()
print(f"Response body (first 100 bytes): {body[:100]}")
else:
print("Did not receive a successful response.")
# 7. Close the connection
connection.close()
print("Connection closed.")
except http.client.HTTPException as e:
print(f"HTTP Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
Output of the Example:
Connecting to www.python.org...
Sending request line...
Sending headers...
Getting response...
Response status: 200 OK
--------------------
Response body (first 100 bytes): b'<!doctype html>\n<!--[if IE]><html class="no-js ie ie9" lang="en-US" > <![endif]-->\n<!--[if !(IE)]><!--><html class="no-js" lang="en-US" > <!--<![endif]-->\n<head>\n\t<meta charset="UTF-8">\n\t<meta name="viewport" content="width=device-width, initial-scale=1">\n\t<title>Wel'
Connection closed.
putrequest vs. requests Library
This is the most important comparison for a modern Python developer.

| Feature | http.client (with putrequest) |
requests Library |
|---|---|---|
| Level | Low-level. You manage the raw HTTP message. | High-level. You provide data, and it builds the message for you. |
| Simplicity | Complex. Requires multiple steps (putrequest, putheader, endheaders, getresponse). |
Extremely simple. A single line of code: requests.get('http://...'). |
| URL Handling | You must parse the URL to get the host and path. | You pass the full URL string directly. |
| Body/Data | You must encode the data and manage Content-Length headers manually. |
You pass a dict or json object to the json= or data= parameter, and it handles encoding and headers automatically. |
| Response | You get a response object and must call .read() to get the body. |
The response object has a .text or .json() property for easy access to decoded content. |
| Features | Basic HTTP/HTTPS. No built-in support for sessions, cookies, or connection pooling. | Rich feature set: sessions, cookies, authentication, automatic retries, connection pooling, etc. |
Example: Same Task with requests
As you can see, the requests version is dramatically simpler and more readable.
import requests
url = 'https://www.python.org'
try:
# This single line handles everything: connection, request, headers, and response parsing.
response = requests.get(url)
# Raise an exception for bad status codes (4xx or 5xx)
response.raise_for_status()
print(f"Response status: {response.status_code}")
print("-" * 20)
print(f"Response text (first 100 chars): {response.text[:100]}")
except requests.exceptions.RequestException as e:
print(f"An error occurred with the requests library: {e}")
Conclusion
- What is
putrequest? It's a low-level method inhttp.clientused to send the initial request line (e.g.,GET / HTTP/1.1) of an HTTP request. - When should you use it? You should use it when you are working directly with the
http.clientlibrary. This is rare today. - What should you use instead? For almost all Python applications, you should use the
requestslibrary. It is the de-facto standard for making HTTP requests in Python because it is powerful, easy to use, and handles all the low-level details for you.
