Python’s built-in http.server
module is a powerful tool that allows you to create a web server with a single command, directly from your terminal. This functionality is incredibly useful for developers who need a quick way to serve files for local development, share files over a network, or prototype simple web applications without the overhead of setting up a full-fledged web server like Apache or Nginx. It’s an essential utility for any Python developer’s toolkit, providing a straightforward method to get a server running in seconds.
In this tutorial, you will learn how to use Python’s http.server
to create a simple HTTP server from any directory on your system. We will cover how to start the server, access it from your browser, and serve files. You will also explore the differences between the SimpleHTTPServer
in Python 2 and the http.server
module in Python 3. Furthermore, we will discuss how to extend the server’s functionality to handle specific requests, serve files over a network, and even add a layer of security with SSL.
Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.
Key takeaways:
http.server
module can turn any directory into a simple HTTP web server for local development or file sharing.python -m http.server 8000
.http.server
in Python 3 is the successor to the SimpleHTTPServer
module from Python 2.SimpleHTTPRequestHandler
.Python’s http.server is a built-in module that allows you to create a simple HTTP server to serve files from a directory. It’s a convenient tool for testing, development, and sharing files over a network. It is not recommended for production use.
Using a simple HTTP server in Python is beneficial for several reasons:
To start a simple HTTP server in Python, use the following one-liner command in your terminal or command prompt:
python -m http.server 8000
This command starts a server on port 8000
, serving files from the current directory.
While the one-liner command is excellent for quick tasks, you can also start the server from within a Python script. This approach gives you more control and allows you to integrate the server into larger applications or automated testing workflows.
To do this, you’ll use Python’s built-in http.server
and socketserver
modules.
Here is a basic script to launch the server:
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
# Start the server and keep it running until you stop the script
httpd.serve_forever()
In this script:
socketserver.TCPServer
creates a TCP server. The first argument ("", PORT)
tells the server to listen on all available network interfaces on the specified port, making it accessible to other devices on your local network.http.server.SimpleHTTPRequestHandler
is the default handler that serves files and directory listings.httpd.serve_forever()
starts the server and keeps it running until you interrupt it (e.g., with Ctrl+C).Save this code as a Python file (e.g., server.py
) and run it from your terminal:
python server.py
You will see the output Serving at port 8000, and the server will be active.
To serve files from a specific directory, navigate to that directory in your terminal or command prompt and run the server command. For example, if you want to serve files from a directory named myproject
, navigate to myproject
and run:
python -m http.server 8000
This will serve files from the myproject
directory.
By default, the server runs on port 8000
. If you want to use a different port, specify it as an argument after the server command. For example, to run the server on port 9000
:
python -m http.server 9000
Python SimpleHTTPServer
supports only two HTTP methods - GET and HEAD. So it’s a good tool to share files over network. Python SimpleHTTPServer
has been migrated to the http.server
module in Python 3, we will learn about both of these modules today and see how easy it is to work with them. Suppose you and your friend are on the same local network. You have some files that you want to share with your friend. Instead of copying them to a portable hard disk, you can use Python’s SimpleHTTPServer
to share them directly. In this tutorial, we will learn about basics of Python SimpleHTTPServer
so that you can use it your day-to-day life.
If you are using Windows operating system then go to your desired folder or directory that you want to share. Now, use shift+right click
. You will find an option to open Command Prompt in that directory. Just click on that and open command prompt there. However, if you are using Ubuntu, just right click into that directory and open terminal. After that, execute the following command:
python -m SimpleHTTPServer 9000
You can run python http server on any port, default port is 8000. Try to use port number greater than 1024 to avoid conflicts. Then open your favourite browser and type localhost:9000
. Yeah! You’re done!!! Now know your ip address and then replace localhost with your ip address and then share it with your friend.
If you are running Python 3, you will get error as No module named SimpleHTTPServer
. It’s because in Python 3, SimpleHTTPServer
has been merged into http.server
module. You can use the following command to run a HTTP server in Python 3.
python3 -m http.server 9000
SimpleHTTPServer
ExampleThe following images show the Python SimpleHTTPServer
output in terminal and browser.
Note that if there is any
index.html
file then it will be served to the browser, otherwise directory listing will be shown as in above image.
Below image shows the terminal output for the Python 3 http.server
module. Browser output remains same as in above images.
As you can see from terminal output, the Python 3 http,server
module is cleaner, and provides clear messages. Python http.server
module doesn’t show all the Python modules details on quitting from keyboard, that is a more clean approach. That’s all about Python SimpleHTTPServer
in Python 2 and http.server
in Python 3. If you don’t have Python installed in your system and want to give it a try, please go through Python tutorial for beginners to get started. Reference: Official Documentation
When using Python’s http.server
, it’s essential to consider the security implications. Since the server is designed for development and testing purposes, it’s not recommended for production use. Here are some security considerations to keep in mind:
To mitigate these risks, use the server only for local development and testing, and ensure that you’re not serving sensitive data.
As the existing Security Considerations section highlights, the default HTTP server is unencrypted and insecure. While it should never be exposed to the public internet, you can significantly improve its security for local network use by adding SSL/TLS encryption, turning your http://
server into an https://
server.
To do this, you need an SSL certificate. For local development, a self-signed certificate is sufficient.
You can generate a self-signed certificate using OpenSSL. If you don’t have it, you may need to install it first. Run the following command in your terminal:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
This command will prompt you for some information (like country, organization, etc.), but you can leave them blank for local use. It will create two files in your current directory:
key.pem
: Your private key.cert.pem
: Your public certificate.Keep your key.pem
file secure, as it is your private key.
Next, modify the programmatic server script to use Python’s built-in ssl
module to wrap the server’s socket with your SSL certificate.
import http.server
import socketserver
import ssl
PORT = 8000
HANDLER = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), HANDLER) as httpd:
httpd.socket = ssl.wrap_socket(
httpd.socket,
keyfile="key.pem",
certfile="cert.pem",
server_side=True
)
print(f"Serving securely on https://localhost:{PORT}")
# Start the server
httpd.serve_forever()
Make sure the key.pem
and cert.pem
files are in the same directory as this script, or provide the correct paths.
Run the script:
python secure_server.py
Now, open your web browser and navigate to https://localhost:8000
.
Your browser will display a security warning because the certificate is self-signed (i.e., not issued by a trusted Certificate Authority). This is expected. For local development, you can safely proceed by clicking “Advanced” and choosing to continue to the site. Your connection to the local server is now encrypted.
Here are some use cases and best practices for using Python’s http.server:
To spin up a local dev server to test front-end changes, navigate to your project directory and run:
python -m http.server 8000
This will start a server on port 8000, serving files from your project directory.
To serve static files during hackathons or project demos, navigate to the directory containing your static files and run:
python -m http.server 8000
This will allow you to quickly share your project with others over a local network.
To use Python’s http.server on a Raspberry Pi to serve files over a LAN, follow these steps:
python -m http.server 8000
http://<Raspberry Pi's IP address>:8000
.To quickly test webhooks or CORS headers, you can use Python’s http.server
to simulate a server environment. For example, you can create a simple HTML file with a webhook or CORS request and serve it using the server.
The default SimpleHTTPRequestHandler
is limited to serving files with GET
and HEAD
requests. For more advanced functionality, such as handling POST
requests or adding custom headers, you can create your own request handler by subclassing SimpleHTTPRequestHandler
.
Subclassing allows you to override the default methods or add new ones to define custom server behavior.
Here’s how you can create a basic custom handler that overrides the do_GET
method to log a custom message:
import http.server
import socketserver
PORT = 8000
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
print("A custom GET request was received.")
# Call the parent class's do_GET method to serve the file
super().do_GET()
with socketserver.TCPServer(("", PORT), CustomHandler) as httpd:
print(f"Serving at port {PORT} with a custom handler")
httpd.serve_forever()
When you run this script and access http://localhost:8000
in your browser, the terminal will print “A custom GET request was received” for each file requested by the browser, while still serving the files as usual.
A common requirement is to handle data submitted via POST
requests. You can add this capability by implementing the do_POST
method in your custom handler. This method is called automatically whenever the server receives a POST
request.
In the do_POST
method, you can read the incoming data, process it, and send a response back to the client.
The following example demonstrates a custom handler that can receive and process simple text-based POST
data:
import http.server
import socketserver
PORT = 8000
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
print(f"Received POST data: {post_data.decode('utf-8')}")
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
response_message = b"POST request received successfully!"
self.wfile.write(response_message)
with socketserver.TCPServer(("", PORT), CustomHandler) as httpd:
print(f"Serving at port {PORT}, ready to handle POST requests")
httpd.serve_forever()
To test this server, run the script and then use a tool like curl
from another terminal to send a POST request:
curl -X POST -d "Hello, Server!" http://localhost:8000
The server’s terminal will display:
Received POST data: Hello, Server!
And the curl
command will receive the response: POST request received successfully!
The simple Python HTTP server can be a surprisingly effective tool in modern AI and machine learning development workflows. It provides a lightweight foundation for creating API endpoints for models, testing interfaces, and building AI-powered tools.
You can use a custom request handler to wrap a pre-trained machine learning model (e.g., from scikit-learn or Hugging Face Transformers) and expose it as a basic API endpoint. The server listens for POST
requests containing input data, passes it to the model for inference, and returns the prediction as JSON.
This approach is perfect for quickly prototyping a model’s behavior before deploying it with a more robust framework like FastAPI.
Leverage Large Language Models (LLMs) to accelerate the development of your server. Instead of writing custom handlers from scratch, you can use prompts to generate the necessary code. This is especially useful for creating mock API endpoints or complex request parsing logic.
Example Prompt for an LLM:
"Write a Python script using the http.server module. Create a custom handler that responds to GET requests at the path /api/v1/users by returning a JSON array with three fake user objects. Each user object should have an id, name, and email."
This allows you to focus on the application logic while AI handles the boilerplate server setup.
You can configure your custom server to log every request to a file. Then, you can use a separate AI-powered script to analyze these logs. This script could:
404 Not Found
errors from a specific IP address, which could indicate a security scan.The http.server
module is an excellent way to host a simple front-end for an AI chatbot.
index.html
file with JavaScript. This page contains a text input for the user and a display area for the chat history.POST
handler at an endpoint like /chat
.fetch
API to send the user’s message to your /chat
endpoint.This creates a fully self-contained, locally-hosted chatbot application perfect for experimentation and learning.
The command to start a simple HTTP server in Python 3 is:
python -m http.server 8000
This starts a server on port 8000, serving files from the current directory.
To specify a custom port, add the port number as an argument after the server command. For example, to run the server on port 9000:
python -m http.server 9000
To serve a different directory, navigate to that directory in your terminal or command prompt before running the server command. For example, if you want to serve files from a directory named myproject
, navigate to this directory using the command cd myproject
and run:
python -m http.server 8000
This will serve files from the myproject
directory.
No, Python’s http.server
is not recommended for production use due to security concerns. It’s designed for development and testing purposes only.
To serve files over a network, not just localhost, ensure that your server is configured to listen on a network interface and that the necessary network ports are open. Additionally, you may need to configure your router to forward incoming requests to your server.
Here is a Python program that can help you serve files over a network:
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
This program will serve files from the current directory on port 8000. You can change the port number and directory as needed.
In this tutorial, you learned to use Python’s http.server
to quickly launch a simple web server for local development and file sharing. We covered starting the server, serving files, securing it with SSL for local use, and extending its functionality with custom request handlers.
While http.server
is excellent for development and prototyping, it is not intended for production environments due to its inherent lack of security and performance features. For production needs, it’s best to use a robust web server and framework. To continue your journey in web development, consider exploring the following tutorials:
These tutorials will help you expand your knowledge of Python and its applications in networking and web development.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix
With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.
thanks pankaj i dont know why the below error is causing.while running http server command “/usr/bin/python: No module named SimpleHTTPServer” after reading your article it get clear because it was due to python3 & python3 have different command
- anonymous
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.