Python's http.server
Learn to use Python's built-in HTTP server module.
How to Read Code Blocks
In this lesson:
- Filename in header (e.g.,
simple_server.py) = Write this code to that file - bash blocks = Commands to run in your terminal
- "Expected Output" = What you should see (don't write this)
The http.server Module
Python includes a fully-featured HTTP server in its standard library. No external dependencies needed! The key classes are:
HTTPServer— The server that listens for connectionsBaseHTTPRequestHandler— Handles individual requests
Your First Server
Create a file called simple_server.py:
python
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHandler(BaseHTTPRequestHandler):
"""Handle HTTP requests."""
def do_GET(self):
"""Handle GET requests."""
# Send response status
self.send_response(200)
# Send headers
self.send_header("Content-Type", "text/plain")
self.end_headers()
# Send body
message = f"Hello! You requested: {self.path}"
self.wfile.write(message.encode())
def run_server(port=8080):
"""Start the HTTP server."""
server_address = ("localhost", port)
httpd = HTTPServer(server_address, SimpleHandler)
print(f"Server running on http://localhost:{port}")
httpd.serve_forever()
if __name__ == "__main__":
run_server()
Run the Server
bash
python simple_server.py
Then test it in another terminal:
bash
curl http://localhost:8080/test
# Output: Hello! You requested: /test
curl http://localhost:8080/any/path
# Output: Hello! You requested: /any/path
Understanding the Handler
The BaseHTTPRequestHandler provides several useful attributes:
python
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Request information
print(f"Path: {self.path}") # "/api/test"
print(f"Headers: {self.headers}") # All request headers
print(f"Method: {self.command}") # "GET"
# Response methods
self.send_response(200) # Set status code
self.send_header("Key", "Value") # Add header
self.end_headers() # Finish headers
self.wfile.write(b"body") # Write response body
HTTP Methods
Define methods for each HTTP verb you want to handle:
python
class MultiMethodHandler(BaseHTTPRequestHandler):
def do_GET(self):
"""Handle GET requests."""
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"This is a GET response")
def do_POST(self):
"""Handle POST requests."""
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"This is a POST response")
def do_DELETE(self):
"""Handle DELETE requests."""
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"This is a DELETE response")
Method Naming
The method names must be do_GET, do_POST, etc.
The framework automatically routes requests based on the HTTP method.