Python BaseHTTPRequestHandler: Respond with JSON

SomethingSomething picture SomethingSomething · Jan 2, 2017 · Viewed 15k times · Source

I have a Python class that inherits BaseHTTPRequestHandler and implements the method do_POST.

I currently only succeed to respond with an integer status, e.g. 200, using the following command at the end of the method:

self.send_response(200)

I am trying to also send some string as a part of the response. How should I do it?

Answer

BrainOverflow picture BrainOverflow · Feb 25, 2019

At least in my environment (Python 3.7) i have to use

self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json_str.encode(encoding='utf_8'))

otherwise this error will be thrown: TypeError: a bytes-like object is required, not 'str'