pythonhttp.server

How do I get the body of a PUT request in SimpleHTTPRequestHandler


I have this super simple HTTP server to test some REST endpoints:

import http.server

class MyHandler(http.server.SimpleHTTPRequestHandler):
    def do_PUT(self):
        self.send_response(200)
        self.end_headers()

    def do_POST(self):
        self.send_response(409)
        self.end_headers()

server_address = ('', 8000)
httpd = http.server.HTTPServer(server_address, MyHandler)
httpd.serve_forever()

But, now I want to check if my PUT call sends the correct body, so I want to just print the request body in the do_PUT method. I tried looking for more info in the documentation, but it doesn't even mention the do_PUT method in the SimpleHTTPRequestHandler class (or any other class for that matter).

How can I access the request body in the do_PUT method of a inherited SimpleHTTPRequestHandler ?


Solution

  • You can do it similarly to accessing a POST request's body

    import http.server
    
    
    class MyHandler(http.server.SimpleHTTPRequestHandler):
        def do_PUT(self):
            content_len = self.headers.get("Content-Length")
            if content_len is not None:
                body = self.rfile.read(int(content_len))
                print(body)
            self.send_response(200)
            self.end_headers()
    
        def do_POST(self):
            self.send_response(409)
            self.end_headers()
    
    
    server_address = ("", 8000)
    httpd = http.server.HTTPServer(server_address, MyHandler)
    httpd.serve_forever()