# Python, create a Web (HTTP) server

> Learn how to create an HTTP server in Python with the http.server module, from the quick python -m http.server command to a custom request handler class.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-02-10 | Topics: [Python](https://flaviocopes.com/tags/python/) | Canonical: https://flaviocopes.com/python-http-server/

[Python](https://flaviocopes.com/python-introduction/) makes it super easy to create an HTTP server, via the `http` module of the standard library.

In particular, the `http.server` object is the thing we're going to use.

First, I want to mention one quick way to run an HTTP server from any folder, without writing any code:

```sh
python -m http.server --cgi 8000
```

This will run an HTTP server on port 8000, serving the files in the current folder. Of course it's not an HTTP server fully featured like Nginx or Apache, but that's often good enough for prototypes, or for your own test projects.

Let's now use that module in our code to make it programmatically serve an "Hello, World!" string to anyone connecting on port `8000`:

```python
from http.server import BaseHTTPRequestHandler, HTTPServer

class handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()

        message = "Hello, World!"
        self.wfile.write(bytes(message, "utf8"))

with HTTPServer(('', 8000), handler) as server:
    server.serve_forever()
```

After running this program locally you can try connecting using a Web browser to port <http://localhost:8000>.

This serves the same `Hello, World!` string to anyone visiting the site on `http://localhost:8000`, on GET requests to _any_ URL, complete with a 200 response and a `Content-type: text/html` header.

We write to `wfile`, which contains the output stream for writing a response back to the client.

It works on GET requests because we implemented the handler `do_GET` method.

You can also implement `do_HEAD()`, `do_POST()` and any other HTTP method:

```python
from http.server import BaseHTTPRequestHandler, HTTPServer

class handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()

        message = "Hello, World! Here is a GET response"
        self.wfile.write(bytes(message, "utf8"))
    def do_POST(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()

        message = "Hello, World! Here is a POST response"
        self.wfile.write(bytes(message, "utf8"))

with HTTPServer(('', 8000), handler) as server:
    server.serve_forever()
```

Python has lots of different libraries we can use to handle applications built on top a Web server, including the very popular Flask and Django.
