create a http server and read the request body in python

Here's an example of how to create an HTTP server and read the request body in Python using the built-in http.server module:

main.py
from http.server import BaseHTTPRequestHandler, HTTPServer

class MyServer(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        response = f'Received request body: {body.decode("utf-8")}'
        self.wfile.write(response.encode('utf-8'))

if __name__ == '__main__':
    host_name = 'localhost'
    port = 8000
    my_server = HTTPServer((host_name, port), MyServer)
    print(f'Server started at http://{host_name}:{port}')
    my_server.serve_forever()
625 chars
18 lines

In this example, we define a custom request handler class MyServer that inherits from BaseHTTPRequestHandler and overrides the do_POST() method to handle POST requests.

Inside this method, we read the Content-Length header to determine the length of the request body, then read that many bytes from the request using self.rfile.read().

We then send a 200 OK response with self.send_response() and self.end_headers(), followed by a simple response message containing the received request body. Finally, we send this message to the client using self.wfile.write().

When we run this script, it will start a web server listening on http://localhost:8000. You can test it by sending a POST request to this URL with a request body using a tool like curl or httpie. For example:

main.py
$ echo "hello world" | http -v --form POST localhost:8000
POST / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Content-Length: 11
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Host: localhost:8000
User-Agent: HTTPie/2.3.0

hello world

HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.8.6
Date: Thu, 19 Aug 2021 17:21:05 GMT

Received request body: hello world
383 chars
17 lines

related categories

gistlibby LogSnag