How To Create A Simple Web Server with Python?

Create HTTP Server Python

This is a quick tutorial on how to set up a simple HTTP Web server with Python. Learn to create a web server in any desired directory a single command.

Note. This article has been written considering Python Version 3. For earlier versions, please refer here.

Creating a simple HTTP Server with Python

You can create a simple web server using a single command with the help of Python’s built-in HTTP module.

Using Command Line

Open command prompt or terminal in any desired directory for which you want to create a simple HTTP Server and enter the following command.

python -m http.server

or python3 -m http.server

This command will start the server in the current directory.

Example. Here I’ve opened the command prompt and changed the directory to the desktop using the cd command. Then I’ve simply used the command mentioned above to start the server.

Create HTTP Server In Python Example

As soon I pressed the enter key to execute the command, it started the webserver on the IP Address and port 8000. That’s localhost:8000. Now you can enter this IP address with the port number in any of the browsers installed on your local system and you’ll be able to see the file structure of the directory for which you have created this web server.

HTTP Server Directory Listing

Note. You need to make sure if the port you’re using for the server is not being used by any other process or application currently running on your system. If you’re having any port conflicts, things may not work as they should be.

You may specify a custom port number yourself as well. You just need to slightly modify your command by additionally specifying the desired port number in the command as described below. The command given below will start the server on localhost port 5000.

python -m http.server 5000

For a detailed reference of the Python HTTP server module, please visit this link.

Using a Python File

If you want to initiate an HTTP server with Python using a .py file, here’s the code.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

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