Building a basic HTTP Server from scratch in Python (original) (raw)

Last Updated : 15 Mar, 2021

In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC, or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network.

Installation:

On the terminal run the following statement:

python -m http.server

For accessing the server locally we need to visit http://localhost:8000/ or http://127.0.0.1:8000/ Here we can see all the directories of your local storage along with all the data. You can also access an HTML page, It will be rendered by your web browser as you access it.

Functions Used:

Step-by-step Approach:

Implementation:

Python3 `

importing all the functions

from http.server module

from http.server import *

creating a class for handling

basic Get and Post Requests

class GFG(BaseHTTPRequestHandler):

# creating a function for Get Request
def do_GET(self):
  
    # Success Response --> 200
    self.send_response(200)
    
    # Type of file that we are using for creating our
    # web server.
    self.send_header('content-type', 'text/html')
    self.end_headers()
    
    # what we write in this function it gets visible on our
    # web-server
    self.wfile.write('<h1>GFG - (GeeksForGeeks)</h1>'.encode())

this is the object which take port

number and the server-name

for running the server

port = HTTPServer(('', 5555), GFG)

this is used for running our

server as long as we wish

i.e. forever

port.serve_forever()

`

How to start our HTTP-Server:

Use the following command in the terminal

python file_name.py

In the browser go to http://localhost:5555/ or http://127.0.0.1:5555/