Lesson 01 · 30 minutes
Build a tiny web server and call it
- Name the parts of a web application and say what each one does
- Trace one request from the client to the server and back
- Build a server on 127.0.0.1 that returns HTML and JSON, and call it with curl
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
You join a small team that runs an internal portal. A colleague says: "The dashboard shows an error, but I do not know if the fault is in the browser, the server or the database." You cannot answer that until you know what each part does and what a request looks like on the wire. Your task is to build the smallest possible server on your own machine, ask it questions with curl and read both sides of the conversation.
The idea
A web application has three parts.
| Part | Job | Example |
|---|---|---|
| Client | Sends requests, shows answers | A browser, curl, a phone app |
| Server | Runs your code, decides what to answer | A Python program |
| Database | Keeps data after the program stops | SQLite, PostgreSQL |
- Client → Server: GET /api/hello
- Server: run the code, build the answer
- Server → Client: 200 and a JSON body
One request, traced from end to end:
- The client opens a connection to an address and a port (a number that picks one service on a computer). Here it is
127.0.0.1:8300.
- It sends an HTTP request: a method (
GET), a path (/api/hello), headers and sometimes a body. HTTP is the set of rules that clients and servers use to talk. - The server code reads the request, asks the database when it needs data, and builds an answer.
- It sends an HTTP response: a status code (
200), headers and a body. - The client uses the body. A browser draws HTML. A program reads JSON.
The server that you build today keeps no data, so the database step is missing. Lesson 5 adds a database.
The most important fact of the course: everything in a request is written by the client. The path, the headers, the cookies and the body can all be changed by a person who is not your friend. The server must check all of it.
Worked example
1. Make your lab folder
If you did 00-set-up-your-lab, the folder exists. mkdir -p makes it anyway, and cd moves you into it.
mkdir -p ~/krlab/web-apis
cd ~/krlab/web-apis2. Write the server
Create server.py. The program uses three things from the standard library, the code that comes with Python:
http.serveris a module (a file of ready-made code) that listens on a port and gives each request to your code.BaseHTTPRequestHandleris a class (a pattern for objects) that you extend. The server calls its methoddo_GETfor everyGETrequest, andself.pathholds the path that the client asked for.json.dumpsturns a Python dictionary into JSON text. JSON is a plain-text format for data:{"message": "hello"}.
The address 127.0.0.1 means that only your own computer can reach the server. The status 404 means "not found".
server.py
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def send(self, status, ctype, body):
data = body.encode()
self.send_response(status)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path == "/":
self.send(200, "text/html; charset=utf-8", "<h1>Hello from my server</h1>")
elif self.path == "/api/hello":
self.send(200, "application/json", json.dumps({"message": "hello"}))
else:
self.send(404, "application/json", json.dumps({"error": "not found"}))
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()The method send writes a response in the order that HTTP needs: the status line, the headers, an empty line (end_headers) and then the body. serve_forever keeps the server alive until you stop it.
3. Start it
Keep this terminal open. Open a second terminal for the next steps. A new terminal starts in your home folder, so type cd ~/krlab/web-apis first in every terminal you open.
python3 server.pyThe server prints nothing until a request arrives.
4. Ask for the HTML page
curl is a program that sends an HTTP request from the terminal and prints the answer. The option -s (silent) hides the progress meter. The option -i (include) shows the response headers. A header is one line of extra information, in the form Name: value.
curl -si http://127.0.0.1:8300/HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.4
Date: Sat, 21 Nov 2026 08:37:55 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 29
<h1>Hello from my server</h1>HTTP/1.0 200 OK is the status line: the code 200 means success. The Python module answers with the older version 1.0 and closes the connection after each reply, although curl asks with 1.1. Content-Type tells the client how to read the body. A browser that gets text/html draws a heading. Content-Length is the size of the body in bytes. Server and Date are added by the Python module. Your version and time differ.
5. Ask for the JSON answer, and see the request too
The option -v (verbose) shows both directions. A line that starts with > was sent by the client. A line that starts with < came from the server. curl writes this text to the error stream, so 2>&1 sends the error stream into the pipe, and grep can read it. grep -E uses an extended pattern: ^[<>] keeps only the lines that start with < or >.
curl -sv http://127.0.0.1:8300/api/hello 2>&1 | grep -E '^[<>]'> GET /api/hello HTTP/1.1
> Host: 127.0.0.1:8300
> User-Agent: curl/8.18.0
> Accept: */*
>
< HTTP/1.0 200 OK
< Server: BaseHTTP/0.6 Python/3.14.4
< Date: Sat, 21 Nov 2026 08:37:55 GMT
< Content-Type: application/json
< Content-Length: 20
< The client sent three headers. Host names the server that it wants. User-Agent names the program. Accept says which body types it can read. Every line that begins with > came from the client, so a client can write any of them.
6. Ask for a path that does not exist
The option -o /dev/null throws the body away. The option -w (write out) prints a value after the transfer, here the status and the content type.
curl -s -o /dev/null -w '%{http_code} %{content_type}\n' http://127.0.0.1:8300/nothing404 application/json7. Read the server log
Go back to the first terminal. The server wrote one line for each request: client address, time, request line, status.
127.0.0.1 - - [21/Nov/2026 08:37:55] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2026 08:37:55] "GET /api/hello HTTP/1.1" 200 -
127.0.0.1 - - [21/Nov/2026 08:37:55] "GET /nothing HTTP/1.1" 404 -Press Ctrl+C to stop the server. Remember this log: lesson 3 shows how a log can leak a secret.
Your turn
Your colleague wants a health check for the portal. Extend your own server.py. There are no steps here.
- Add the path
/api/ping. It answers status 200, the content typeapplication/jsonand the body{"pong": true}. (In Python the value isTrue;json.dumpswrites it astrue.) - Stop the server, start it again and call the new path with
curl. - Call
/api/ping/(with a slash at the end) and/api/ping?x=1(with a query). Compareself.pathwith the same==test that the other paths use. Read your code to see why they behave as they do.
Last, look at the log. The query ?x=1 is in it. Lesson 7 shows why that can be a problem.
Check yourself
A browser and curl ask for the same path. Why may the answers differ?
The request is not only the path. The headers differ: the browser sends cookies, an Accept header and a different User-Agent. The server may use any of them to choose the answer.
Why is the server bound to 127.0.0.1 and not to 0.0.0.0?
127.0.0.1 is the loopback address. Only programs on your own computer can connect to it. 0.0.0.0 means every network interface, so other computers on your network could reach a server that has no protection yet.
The page says "Hello". Is a check in the browser enough to keep bad data out?
No. A check in the browser runs on the client, and the client belongs to the person who sends the request. They can skip the browser and call the server with curl. Every check that matters must run on the server.
Why did /api/ping?x=1 give a 404, although the path is the same?
self.path holds the path and the query together, and the code compares the whole string. A real server splits them first. Be careful: code that compares or checks a path must know which of the two it holds.
Field notes
- The Python
http.servermodule is for learning. It has no TLS (the encryption that turnshttpintohttps), no limits and handles one request at a time. In production, run the application behind a hardened server or reverse proxy (a front server that takes the requests first) that adds TLS, timeouts and size limits. - The
Server:header shows the software and its version. Remove or hide it in production: it helps an attacker choose an exploit. This is part of OWASP Top 10 "Security Misconfiguration". OWASP is a non-profit group that publishes the Top 10 lists of web and API flaws. - Content-Type matters for safety. A JSON answer sent as
text/htmlcan be treated as a page by the browser. Always send the type that matches the body. - Treat the request line, headers and body as untrusted input at every layer, including the layers inside your own network. The OWASP API Security Top 10 category "Unrestricted Resource Consumption" starts here: a client controls how large and how frequent its requests are.