BaseHTTPRequestHandler: how to return JSON from post request

115 views Asked by At

I'm new in API creation and cannot create correct server code to return JSON data from POST request. I have a Python class that inherits BaseHTTPRequestHandler and implements the method do_POST.

import json
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests

class RequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        content_length = int(self.headers["Content-Length"])
        post_data = self.rfile.read(content_length)
        json_data = json.loads(post_data)
        
        response_data = {
            "message": "Received POST request",
            "data": json_data
        }

        self.send_response(200)
        self.send_response(2)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(response_data).encode(encoding='utf_8'))

def run_server():
    host = "localhost"
    port = 8000
    server = HTTPServer((host, port), RequestHandler)
    print(f"Server running on {host}:{port}")
    server.serve_forever()

if __name__ == "__main__":
    run_server()

Here is my request:

requests.post('http://localhost:8000', json = {'key': 'value'})

Server returns status 200, but without JSON.

0

There are 0 answers