Python One-Liner Webserver HTTP

Want to create your own webserver in a single line of Python code? No problem, just use this command in your shell:

$ python -m http.server 8000

The terminal will tell you:

Serving HTTP on 0.0.0.0 port 8000

To shut down your webserver, kill the Python program with CTRL+c.

This works if you’ve Python 3 installed on your system. To check your version, use the command python --version in your shell.

You can run this command in your Windows Powershell, Win Command Line, MacOS Terminal, or Linux Bash Script.

You can see in the screenshot that the server runs on your local host listening on port 8000 (the standard HTTP port to serve web requests).

Note: The IP address is NOT 0.0.0.0—this is an often-confused mistake by many readers. Instead, your webserver listens at your “local” IP address 127.0.0.1 on port 8000. Thus, only web requests issued on your computer will arrive at this port. The webserver is NOT visible to the outside world.

Python 2: To run the same simple webserver on Python 2, you need to use another command using SimpleHTTPServer instead of http:

$ python -m SimpleHTTPServer 8000
Serving HTTP on 0.0.0.0 port 8000 ...

If you want to start your webserver from within your Python script, no problem:

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()

You can execute this in our online Python browser (yes, you’re creating a local webserver in the browser—how cool is that)!

This code comes from the official Python documentation—feel free to read more if you’re interested in setting up the server (most of the code is relatively self-explanatory).

Related Resources:

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!