return a json response from a http server with a specific status code in python

To return a JSON response from an HTTP server with a specific status code in Python, you can do the following:

main.py
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

class HTTPRequestHandler(BaseHTTPRequestHandler):
    
    def _set_headers(self, status_code):
        self.send_response(status_code)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        response = {'message': 'Hello, World!'}
        self._set_headers(200)
        self.wfile.write(json.dumps(response).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=HTTPRequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd server on port {port}')
    httpd.serve_forever()

if __name__ == '__main__':
    run()
744 chars
24 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