Table of Contents

    Http Status codes

    1. Http Status codes

    Run the simple python server and execute the following curl commands to get an idea about the HTTP methods and their status codes.

    curl-i http://localhost:5000/get

    curl --H "Content-Type: application/json" -X POST -d '("username":"user", "password": "pass"}" http://localhost:5000/post

    curl-i-H "Content-Type: application/json" -X POST -d "("username":"wrong", "password": "wrong")' http://localhost:5000/post

    curl-i http://localhost:5000/redirect

    curl -i http://localhost:5000/divide_by_zero

    curl-i http://localhost:5000/unavailable_resource

    Steps to do the handson:

    Install the necessary requirements (run -> install) Run the server(run -> run)

    
    from http.server import BaseHTTPRequestHandler, HTTPServer
    
    class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            if self.path == '/get':
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write(b"GET request received")
    
            elif self.path == '/redirect':
                self.send_response(302)
                self.send_header('Location', 'http://www.example.com')
                self.end_headers()
    
            elif self.path == '/divide_by_zero':
                This will intentionally raise a ZeroDivisionError
                result = 1 / 0
    
            else:
                self.send_response(404)
                self.end_headers()
    
        def do_POST(self):
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            if self.path == '/post':
                if post_data.decode('utf-8') == '{"username":"user", "password": "pass"}':
                    self.send_response(200)
                    self.send_header('Content-type', 'application/json')
                    self.end_headers()
                    self.wfile.write(b"POST request received with correct credentials")
                else:
                    self.send_response(401)
                    self.send_header('Content-type', 'application/json')
                    self.end_headers()
                    self.wfile.write(b"Unauthorized")
            else:
                self.send_response(404)
                self.end_headers()
    
    def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=5000):
        server_address = ('', port)
        httpd = server_class(server_address, handler_class)
        print("Starting server on port {}...".format(port))
        httpd.serve_forever()
    
    
    if __name__ == "__main__":
        app.run(debug=True)