Create a simple http server with Python 3

Knowing how to create a simple http server comes in very handy, especially when working on projects where your application has to be accessed by a remote device. It’s not very difficult to create an http server with Python, so let’s dive straight into it.

Python is a very good language to do this, because it runs on Windows, Mac OS X and Linux, which makes your little web server very universal. Especially in a development environment.

To get started, create a new Python script with the following contents:

When you run the script, the server will start on port 8081. If you want to use port 80, for example, you’ll have to run your application with root permissions, so that’s why I’m going with port 8081.

Whenever the server gets a GET request, it’ll run the do_GET function, and return a 200 (success) status code header, as well as the text/html content type header to the client system. Along with an hello world message.

To test the http server, open your web browser and type “http://localhost:8081”, you’ll see this:

Screen Shot 2015-06-03 at 6.56.44 pm

13 Comments

    1. Hi Derek

      The do_GET method is a method that gets called automatically, through the BaseHTTPRequestHandler we’re subclassing from, when a GET request arrives.
      The same can be done with other HTTP methods like do_POST for example.

      I hope that clarifies it a bit.

  1. Holy Maloney! It actually works as seen on the web page! After about 15 “examples” that require lots more work to make work, this one actually did what it was supposed to! I am flabbergasted! Thanks for something that actually works! Clear and straightforward as well.

  2. Make sure to use
    #!/usr/bin/env python3
    (if you don’t use aliases) rather than just
    #!/usr/bin/env python

  3. Just wanted to say thanks for posting this python3 code. I’m going to be using your simple http server for a class tomorrow. It’s an after-school programming class for a non-profit neighborhood center which serves underprivileged high school kids.

    1. Hi Luke, thanks for your comment! I really appreciate it!
      It’s amazing you’re teaching programming to underprivileged kids. I’m glad I could help.
      Let me know if I can do more.

      Kind regards

      Daan

Leave a Reply

Your email address will not be published. Required fields are marked *

Protected with IP Blacklist CloudIP Blacklist Cloud