http.server.HTTPServer()
http.server is a simple HTTP server provided by the Python standard library. It lets you start an HTTP server without any external packages, making it useful for development, testing, and serving static files. It is not intended for production use. Use a dedicated WSGI server such as gunicorn or uvicorn in production.
Syntax
from http.server import HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler
# Static file server (serves the current directory)
server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
server.serve_forever()
# Custom request handler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello!')
Classes and Methods
| Class / Method | Description |
|---|---|
| HTTPServer((host, port), handler) | Creates an HTTP server bound to the specified host and port. |
| server.serve_forever() | Starts the server and keeps accepting requests indefinitely. |
| server.shutdown() | Stops the server started by serve_forever(). |
| SimpleHTTPRequestHandler | A handler that serves static files from the current directory. |
| BaseHTTPRequestHandler | The base class for building custom request handlers. |
| handler.do_GET() | Handles GET requests. Override this method to add custom logic. |
| handler.do_POST() | Handles POST requests. Override this method to add custom logic. |
| handler.send_response(code) | Writes the status code to the response. |
| handler.send_header(key, val) | Adds a response header. |
| handler.end_headers() | Sends the blank line that marks the end of the headers. |
| handler.wfile.write(data) | Sends the response body as bytes. |
| handler.rfile.read(length) | Reads the request body. Used with POST requests. |
| handler.path | The request path, including the query string. |
| handler.headers | A dictionary of request headers. |
Sample Code
from http.server import HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlparse
import json
import threading
# Start a static file server from the command line (Python built-in command)
# python -m http.server 8000
# Start a static file server from a script
server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
print("Server started: http://localhost:8000")
# server.serve_forever() # Serves files from the current directory
# Custom HTTP handler
class MyAPIHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
path = parsed.path
params = parse_qs(parsed.query)
if path == '/':
self._send_json({'message': 'Hello!', 'status': 'ok'})
elif path == '/greet':
name = params.get('name', ['Guest'])[0]
self._send_json({'greeting': f'Hello, {name}!'})
else:
self._send_json({'error': 'Not Found'}, status=404)
def do_POST(self):
# Read the request body
length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(length)
try:
data = json.loads(body.decode('utf-8'))
self._send_json({'received': data, 'status': 'ok'})
except json.JSONDecodeError:
self._send_json({'error': 'Invalid JSON'}, status=400)
def _send_json(self, data, status=200):
"""Helper method to send a JSON response."""
body = json.dumps(data, ensure_ascii=False).encode('utf-8')
self.send_response(status)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
"""Suppress the default access log (remove this to re-enable it)."""
pass
# Start the server in a background thread
server = HTTPServer(('localhost', 8080), MyAPIHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
print("API server started: http://localhost:8080")
# Test request
from urllib import request
with request.urlopen('http://localhost:8080/greet?name=Alice') as res:
print(res.read().decode()) # {"greeting": "Hello, Alice!"}
server.shutdown()
Notes
SimpleHTTPRequestHandler is the simplest way to serve files — it serves everything under the current directory. You can start it from the command line with python -m http.server 8000, which is handy for quick file sharing or testing a single-page application locally.
To build a custom handler, subclass BaseHTTPRequestHandler and implement methods such as do_GET() and do_POST(). When sending a response, always follow this order: send_response() → send_header() (repeat as needed) → end_headers() → wfile.write(). Skipping end_headers() omits the required blank line, which breaks the HTTP protocol.
For full-featured web applications or API servers, consider using a framework such as Flask or FastAPI. They provide routing, templating, authentication, and much more, significantly improving developer productivity.
If you find any errors or copyright issues, please contact us.