pythonpython-3.xpostmanartillery

python3 http.server response is not valid (Postman and other tools)


I'm setting up a test server with the basic python3 library http and using the server module.

Testing my server, I've managed to properly get and see the response using curl in the terminal:

$ curl -H "Content-Type: application/json" -X GET "http://localhost:8080/health"                 
{"health": "ok"}HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.7.3
Date: Sun, 12 May 2019 19:52:21 GMT
Content-type: application/json

But if I try to make the request with tools like Postman. With this one, I get the Could not get any response error message (the request does get to the server and it is processed, I can see that in the logging the server does).

Is there a specific way I have to format my response that I'm not seeing at the moment? This is how I do it:

    def _prepare_response(self):
        self._response_body({'health': 'ok'})
        self.send_response(200)
        self.send_header('Content-type','application/json')
        self.end_headers()

Solution

  • If you look at the curl output, it makes no sense: the "body" happens before the status line is even sent.

    You're supposed to send the response body after the headers, not before. That means you must first send the response line, then send the headers, then end the headers, and only then write to wfile with the body content. So the code should look something like that:

     def _prepare_response(self):
            self.send_response(200)
            self.send_header('Content-type','application/json')
            self.end_headers()
            # move what I guess is a helper to after the headers
            self._response_body({'health': 'ok'})
    

    And you probably want to make sure you're properly json-serializing the dict rather than just pass it off to str and hope it's JSON-compatible (I don't know what _response_body does).