create a http server and read the request body as json in python

main.py
import http.server
import socketserver
import json

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        data = json.loads(body)
        print(data) # do something with the data
        
PORT = 8000
Handler = MyHttpRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
519 chars
18 lines

In the above code, we create an HTTP server that listens on port 8000. When a POST request is received, we read the request body using self.rfile.read(content_length) and decode it as UTF-8. We then parse the JSON data in the body with json.loads(body). Finally, we print the JSON data, but you can do whatever you want with it.

gistlibby LogSnag