pythonbasehttpserverbasehttprequesthandler

Python BaseHTTPRequestHandler: Respond with JSON


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?


Solution

  • It turns out to be pretty simple, though there aren't many examples for it.

    Just use:

    self.wfile.write(YOUR_STRING_HERE)
    

    Specifically for the case of json:

    import json
    json_string = json.dumps(YOUR_DATA_STRUCTURE_TO_CONVERT_TO_JSON)
    self.wfile.write(json_string)