Simple HTTP Server in Python (http.server Examples)

A simple HTTP server in Python is one command: open a terminal in the folder you want to share and run python -m http.server. It serves the files at http://localhost:8000 until you press Ctrl+C:

python -m http.server                                      # port 8000, all interfaces
python -m http.server 8080 --bind 127.0.0.1 --directory site   # your own port, local only

Every server here ran on my machine with Python 3.12.5, and I made real requests to it so you can see the responses and log lines.

We’ll start the built-in server, view it in a browser, then write custom handlers that return JSON and accept POST data, and finish with what it’s not safe to use it for.

Start a simple HTTP server with python -m http.server

The options you’ll use most are the port, --bind to choose which address listens, and --directory to serve a folder other than the current one. This script starts the server and requests three paths:

import subprocess, sys, time, urllib.request

# same as typing: python -m http.server 8000 --bind 127.0.0.1 --directory site
server = subprocess.Popen([sys.executable, "-m", "http.server", "8000", "--bind", "127.0.0.1", "--directory", "site"],
                          stderr=subprocess.PIPE, text=True)
time.sleep(1)
for path in ["/", "/prices.csv", "/missing.txt"]:
    try:
        with urllib.request.urlopen("http://127.0.0.1:8000" + path) as resp:
            print(path, resp.status, resp.headers["Content-Type"])
    except urllib.error.HTTPError as err:
        print(path, err.code, err.reason)
server.terminate()
print("--- server log ---")
print("".join(line.split("] ", 1)[-1] for line in server.stderr.readlines()), end="")

Output:

Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) ...
/ 200 text/html; charset=utf-8
/prices.csv 200 application/vnd.ms-excel
/missing.txt 404 File not found
--- server log ---
"GET / HTTP/1.1" 200 -
"GET /prices.csv HTTP/1.1" 200 -
code 404, message File not found
"GET /missing.txt HTTP/1.1" 404 -
Command Prompt output of python -m http.server answering requests with 200 and 404 status codes and printing its access log
A folder listing, a CSV file and a missing file, plus the server’s own log lines.

Content types are guessed from the file extension, and on Windows the registry can override them, which is why my CSV came back as application/vnd.ms-excel. On Windows, use py -m http.server if python isn’t on your PATH; see how to run a Python script.

The Python HTTP server in a browser

When a folder has no index.html, the server shows a clickable listing of its files. With an index.html, it serves that page instead:

Browser showing the directory listing page served by Python's http.server with links to menu.html, notes.txt and prices.csv
The real listing page from http.server, opened in Microsoft Edge.

This is handy for testing a static website, sharing files with another device on your network, or checking HTML that needs to load over HTTP instead of from a file path.

Custom Python HTTP server that returns JSON

For anything dynamic, subclass BaseHTTPRequestHandler and write a do_GET method. Here’s a tiny price API for a coffee shop:

import json, threading, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs

PRICES = {"coffee": 3.75, "bagel": 2.50, "muffin": 3.25}

class PriceHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        url = urlparse(self.path)
        item = parse_qs(url.query).get("item", [""])[0]
        if url.path != "/api/price" or item not in PRICES:
            return self.send_json(404, {"error": "unknown item"})
        self.send_json(200, {"item": item, "price": PRICES[item], "currency": "USD"})

    def send_json(self, status, data):
        body = json.dumps(data).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):          # shorter log line
        print("  server:", fmt % args)

server = ThreadingHTTPServer(("127.0.0.1", 8001), PriceHandler)
threading.Thread(target=server.serve_forever, daemon=True).start()

for q in ["coffee", "bagel", "pizza"]:
    try:
        with urllib.request.urlopen(f"http://127.0.0.1:8001/api/price?item={q}") as resp:
            print(resp.status, json.loads(resp.read()))
    except urllib.error.HTTPError as err:
        print(err.code, json.loads(err.read()))
server.shutdown()

Output:

  server: "GET /api/price?item=coffee HTTP/1.1" 200 -
200 {'item': 'coffee', 'price': 3.75, 'currency': 'USD'}
  server: "GET /api/price?item=bagel HTTP/1.1" 200 -
200 {'item': 'bagel', 'price': 2.5, 'currency': 'USD'}
  server: "GET /api/price?item=pizza HTTP/1.1" 404 -
404 {'error': 'unknown item'}
Command Prompt output of a Python BaseHTTPRequestHandler JSON API returning prices with 200 and a 404 error for an unknown item
Two prices come back as JSON, and an unknown item gets a 404 with an error message.

ThreadingHTTPServer handles each request in its own thread, so one slow client doesn’t block the rest. Overriding log_message lets you shorten or silence the log.

How do you handle a POST request?

Add a do_POST method, read exactly Content-Length bytes from rfile, and send a response. This one totals an order with Austin sales tax:

import json, threading, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

class OrderHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        order = json.loads(self.rfile.read(length))
        subtotal = sum(i["price"] * i["qty"] for i in order["items"])
        reply = {"subtotal": round(subtotal, 2), "tax": round(subtotal * 0.0825, 2),
                 "total": round(subtotal * 1.0825, 2)}
        body = json.dumps(reply).encode()
        self.send_response(201)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):
        pass

server = ThreadingHTTPServer(("127.0.0.1", 8002), OrderHandler)
threading.Thread(target=server.serve_forever, daemon=True).start()

order = {"customer": "Emily", "items": [{"name": "coffee", "price": 3.75, "qty": 2}, {"name": "bagel", "price": 2.50, "qty": 3}]}
req = urllib.request.Request("http://127.0.0.1:8002/orders", data=json.dumps(order).encode(),
                             headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req) as resp:
    print(resp.status, json.loads(resp.read()))
server.shutdown()

Output:

201 {'subtotal': 15.0, 'tax': 1.24, 'total': 16.24}
Command Prompt output of a Python http.server POST handler receiving a JSON order and returning subtotal, tax and total
The server read the JSON order and replied with 201 Created and the totals in dollars.

Reading JSON safely is covered more in Python with open. For calling real web APIs, see web scraping with Python.

Is http.server safe for production?

No. The Python docs warn that http.server only implements basic security checks. Use it for local testing and quick file sharing, and keep it on 127.0.0.1 unless you trust everyone on the network.

NeedUse
Share a folder or test static filespython -m http.server
A quick mock API in testsBaseHTTPRequestHandler
A real web app or APIFlask, FastAPI or Django behind a production server
HTTPSA reverse proxy such as nginx, or a framework’s deployment setup

When you outgrow it, a Flask app is the natural next step; see how to create an app using Python.

More guides on networking and running Python:

Frequently asked questions

How do I start a simple HTTP server in Python?

Run python -m http.server in the folder you want to serve, then open http://localhost:8000.

How do I change the port?

Add the port number: python -m http.server 8080.

How do I serve a different folder?

Use --directory, for example python -m http.server --directory site.

How do I stop the server?

Press Ctrl+C in the terminal where it’s running.

Can other computers reach my server?

By default it listens on all interfaces, so devices on your network can connect if your firewall allows it. Use --bind 127.0.0.1 to keep it local.

Where is http.server documented?

See http.server in the Python docs.