BeginnerLesson 1 of 126 min read

What a Back End Does: A Real Server, a Real Request, a Real Response

See what happens between a browser and a server by running a real HTTP server in Python, sending it a request as plain text over a socket, and reading the status line, headers and body that come back.

In this lesson you will

  • Explain the request and response cycle
  • Read an HTTP request and response as text
  • Write a minimal server
  • Check a server with an independent client

About 28 minutes

Kofi’s tool library needs a brain

Kofi runs a neighbourhood tool library: people borrow drills, ladders and sanders for a few days. He keeps a notebook of who has what, and it is a mess. A back end is the part of an application that runs on a server, out of sight: it stores the data, applies the rules, checks who is allowed to do what, and answers requests from the front end, which runs in the visitor’s browser or phone. The front end shows buttons, the back end decides whether a tool is really available.

Front end and back end talk using HTTP, a simple text protocol. The client sends a request: a first line with a method such as GET and a path, then headers, then an optional body. The server answers with a response: a status line with a numeric code such as 200 for success or 404 for not found, headers, and a body. That is all a web server does, over and over. Frameworks make it comfortable, but they sit on top of this exchange, and seeing it as raw text once removes the mystery. In this course the back end is written in Python with its standard library only, so that every example runs with nothing to install, and the same ideas apply in any language.

Part Example Meaning
Request line GET /tools?kind=drill HTTP/1.1 Method, path and query
Request header Host: example.test Extra information
Status line HTTP/1.0 200 OK Result code
Response header Content-Type: application/json Describes the body
Body {“tools”: 3} The data
import threading, json, socket
from http.server import BaseHTTPRequestHandler, HTTPServer

TOOLS = [{"id": 1, "name": "Drill", "available": True}, {"id": 2, "name": "Ladder", "available": False}, {"id": 3, "name": "Sander", "available": True}]

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/tools":
            body = json.dumps(TOOLS).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
        else:
            body = b'{"error": "not found"}'
            self.send_response(404)
            self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def log_message(self, *args): pass

server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()

def raw(path):
    s = socket.create_connection(("127.0.0.1", port))
    s.sendall(("GET %s HTTP/1.1\r\nHost: tools.test\r\nConnection: close\r\n\r\n" % path).encode())
    data = b""
    while chunk := s.recv(4096):
        data += chunk
    s.close()
    head, _, body = data.partition(b"\r\n\r\n")
    lines = [l for l in head.decode().split("\r\n") if not l.startswith(("Date:", "Server:"))]
    return lines, body.decode()

lines, body = raw("/tools")
print("REQUEST : GET /tools HTTP/1.1 / Host: tools.test")
print("RESPONSE:")
for l in lines: print("  " + l)
print("  body:", body)
lines2, body2 = raw("/nothing")
print("status for /nothing:", lines2[0], "| body:", body2)
data = json.loads(body)
print("DATA " + json.dumps({"status": lines[0], "headers": lines[1:], "count": len(data), "available": [t["name"] for t in data if t["available"]], "status2": lines2[0], "port": port}))
server.shutdown()
REQUEST : GET /tools HTTP/1.1 / Host: tools.test
RESPONSE:
  HTTP/1.0 200 OK
  Content-Type: application/json
  Content-Length: 144
  body: [{"id": 1, "name": "Drill", "available": true}, {"id": 2, "name": "Ladder", "available": false}, {"id": 3, "name": "Sander", "available": true}]
status for /nothing: HTTP/1.0 404 Not Found | body: {"error": "not found"}

The program starts a real HTTP server on a free port of this computer and sends it a request written by hand over a plain socket, to show that no magic is involved. The request is two lines of text. The response came back as a status line, HTTP/1.0 200 OK, headers that include the content type and the length of the body, a blank line, and the body: a JSON list of 3 tools, of which Drill and Sander are available. The same server answered the path /nothing with HTTP/1.0 404 Not Found, because the handler had no rule for it, which is the standard way to say that a resource does not exist.

Notice what the back end did and did not do. It parsed the request line, chose a rule based on the path, built a JSON body, and set the status and headers: Content-Type tells the client how to read the body, and Content-Length tells it where the body ends. It did not draw anything. Presentation is the front end’s job. This separation is why one back end can serve a website, a phone app and another company’s program at once, all using the same JSON.

Independent check: a second client, curl, which knows nothing about the Python code, requests the same URL below, and the first answer is compared with the one that the first program printed. The check is done by the lesson’s script, so the claim is tested, not assumed.

GET /tools    -> 200 application/json
GET /nothing  -> 404
body equals the list of 3 tools: True

curl reported 200 application/json for /tools and 404 for /nothing, and the body it received was identical to the list of tools in the program. Two different clients agree about what the server says.

Check by hand: the list holds a drill and a sander as available and a ladder as not, so two tools are available out of three. The status 404 means “not found” and 200 means “OK”, two of the five families of status codes: 2xx for success, 3xx for redirection, 4xx for a client error and 5xx for a server error.

Never trust the client

Everything in a request, the path, the headers, the body and cookies, is written by whoever sends it, and can be false or malicious. The back end must check every value, as the next lessons show.

Learn to read raw HTTP

When something is wrong, look at the actual request and response with curl -i or the Network panel of your browser. Most mysteries become obvious once you see the real text.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour.

Practice

Add a route /tools/2 that returns only the ladder, and a 404 for any id that does not exist. Run the program, then request the route with curl -i and read the headers. Change the status of the response to 500 and see how curl reports it.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is a back end?

  1. The visual layout
  2. The part of an application that runs on a server and holds data and rules
  3. A browser extension
  4. A kind of database only

The front end shows, the back end decides.

What does the status code 404 mean?

  1. Not found
  2. Success
  3. Server error
  4. Redirect

4xx are client errors.

What does Content-Length tell the client?

  1. Where the body ends
  2. The colour
  3. The language
  4. The method

The size of the body in bytes.

Is HTTP a binary or a text protocol (HTTP/1.x)?

  1. Binary only
  2. Encrypted only
  3. A database
  4. A text protocol

Which is why a socket and a few lines are enough.

Why check with a second client such as curl?

  1. It is faster
  2. It is required by HTTP
  3. It formats JSON
  4. It is independent of your code

It shows what any client would see.

Summary

  • The front end shows, the back end stores, decides and answers.
  • HTTP is a text conversation of requests and responses.
  • Status codes group results: 2xx, 3xx, 4xx and 5xx.
  • Verify behaviour with an independent client.

Next lesson

Lesson 2 covers HTTP methods and REST routes.

Questions

Which language should I use for a back end?

Any of them can. Python, JavaScript, Java, C#, PHP, Go and Ruby are all common. The ideas in this course apply to all, so use the one you know or need.

Do I need a framework?

Not to learn. Frameworks save time in real projects, and understanding the plain request and response first makes them easier to use. Check the documentation of the one you choose.

Where does the back end run?

On a server, which can be your own computer, a rented virtual machine or a cloud service. The Hosting and servers course covers that.

Progress is saved in this browser.