Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 01 · 30 minutes

Build a tiny web server and call it

After this lesson you can
  • 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
Lab files of this lesson (2)

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.

PartJobExample
ClientSends requests, shows answersA browser, curl, a phone app
ServerRuns your code, decides what to answerA Python program
DatabaseKeeps data after the program stopsSQLite, PostgreSQL
One request, from client to server and back
ClientServerGET /api/hellorun the code, build the answer200 and a JSON bodyClientServer123
  1. Client → Server: GET /api/hello
  2. Server: run the code, build the answer
  3. Server → Client: 200 and a JSON body

One request, traced from end to end:

  1. 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.
The URL that the client starts from
http://scheme: the rules to use127.0.0.1host: this computer only:8300port: which service/api/hellopath: what to ask forhttp://scheme: the rules to use127.0.0.1host: this computer only:8300port: which service/api/hellopath: what to ask for
  1. 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.
  2. The server code reads the request, asks the database when it needs data, and builds an answer.
  3. It sends an HTTP response: a status code (200), headers and a body.
  4. 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-apis

2. Write the server

Create server.py. The program uses three things from the standard library, the code that comes with Python:

  • http.server is a module (a file of ready-made code) that listens on a port and gives each request to your code.
  • BaseHTTPRequestHandler is a class (a pattern for objects) that you extend. The server calls its method do_GET for every GET request, and self.path holds the path that the client asked for.
  • json.dumps turns 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.py

The 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 request line and the first header
GETmethod: what to do/api/hellopath: which resourceHTTP/1.1version of the rulesHost: 127.0.0.1:8300header: name and valueGETmethod: what to do/api/hellopath: which resourceHTTP/1.1version of the rulesHost: 127.0.0.1:8300header: name and value

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/nothing
404 application/json

7. 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.

  1. Add the path /api/ping. It answers status 200, the content type application/json and the body {"pong": true}. (In Python the value is True; json.dumps writes it as true.)
  2. Stop the server, start it again and call the new path with curl.
  3. Call /api/ping/ (with a slash at the end) and /api/ping?x=1 (with a query). Compare self.path with 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.server module is for learning. It has no TLS (the encryption that turns http into https), 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/html can 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.