To return a JSON response from an HTTP server with a specific status code in Python, you can do the following:
main.py744 chars24 lines
In this example, we define an HTTPRequestHandler class that inherits from BaseHTTPRequestHandler, and overrides the do_GET method to return a JSON response with a 200 status code. The _set_headers
method is used to set the HTTP headers for the response.
To start the server, we define a run
function that creates an instance of HTTPServer and passes in the HTTPRequestHandler
class. We then call the serve_forever
method to start the server.
You can customize the response message and status code as needed by updating the response
dictionary and passing in a different status code to the _set_headers
method.
gistlibby LogSnag