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

main.py
import http.server
import json

class MyServer(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)

        json_data = json.loads(body)

        # do some processing with json data and create a response
        response_data = {
            'status': 'success',
            'message': 'Received JSON data successfully',
            'data': json_data
        }

        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()

        self.wfile.write(json.dumps(response_data).encode('utf-8'))

if __name__ == '__main__':
    server_address = ('', 8080)
    httpd = http.server.HTTPServer(server_address, MyServer)
    httpd.serve_forever()
814 chars
28 lines

In this code, we create a simple HTTP server that listens on port 8080 for incoming requests. We override the do_POST method to read the request body as JSON, process the data and create a JSON response. The response is then sent back to the client with a 200 OK status code.

gistlibby LogSnag