Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

Create a python script that would spawn an rest api server using native modules. All GET…

  1. User

    Create a python script that would spawn an rest api server using native modules. All GET posts should respond 200 and echo back the query strings in json. All POST requests should respond 200 and echo back the query strings and post body in json.

  2. Assistant

    To create a REST API server using native Python modules, you can use the built-in http.server module in Python 3. This example demonstrates a simple server that responds to GET and POST requests and echoes back the query string and post body in JSON format.

    import json
    from http.server import BaseHTTPRequestHandler, HTTPServer
    from urllib.parse import parse_qs, urlparse
    
    class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    
        def _send_response(self, response_dict):
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", len(json.dumps(response_dict)))
            self.end_headers()
            self.wfile.write(json.dumps(response_dict).encode())
    
        def do_GET(self):
            parsed_path = urlparse(self.path)
            query_string = parse_qs(parsed_path.query)
            response_dict = {"query_string": query_string}
            self._send_response(response_dict)
    
        def do_POST(self):
            parsed_path = urlparse(self.path)
            query_string = parse_qs(parsed_path.query)
            content_length = int(self.headers.get("Content-Length", 0))
            post_body_raw = self.rfile.read(content_length) if content_length > 0 else b""
            post_body = json.loads(post_body_raw) if post_body_raw else {}
            response_dict = {"query_string": query_string, "post_body": post_body}
            self._send_response(response_dict)
    
    if __name__ == "__main__":
        host = "localhost"
        port = 8000
        server = HTTPServer((host, port), SimpleHTTPRequestHandler)
        print(f"Starting server on http://{host}:{port}")
        server.serve_forever()
    

    To test this API server, you can use curl or any API client like Postman.

    For a GET request, you can use:

    curl "http://localhost:8000?param1=value1&param2=value2"
    

    For a POST request, you can use:

    curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2": "value2"}' "http://localhost:8000?param1=value1&param2=value2"
    

    Both requests should return the requested query strings and the POST request should also return the post body.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.