Show contents
Chapter 5 of 7 · 20 min
HTTP and HTTPS
By the end of this chapter, you'll be able to
- Read and write an HTTP request and response
- Recognise the methods and the families of status codes
- Parse an HTTP message in Python
- Explain what HTTPS protects, and what it does not
A request, a response
HTTP works by request and response: the client (the browser) sends a request, the server sends back a response. Each message is text, line by line:
GET /courses/networks HTTP/1.1
Host: www.shop.example
Accept-Language: en
- the first line gives the method (
GET), the requested path and the version; - then come the headers, in the format
Name: value; - an empty line ends the headers, and a body can follow (to send a form, for example).
The response has the same shape, with a status code:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 1532
<!doctype html>…
The main methods: GET (read), POST (send, create), PUT (replace), DELETE (remove). Status codes come in families:
| Family | Meaning | Examples |
|---|---|---|
| 2xx | success | 200 OK, 201 Created |
| 3xx | redirection | 301 Moved Permanently |
| 4xx | client error | 400 Bad Request, 401 Unauthorized, 404 Not Found |
| 5xx | server error | 500 Internal Server Error, 503 Service Unavailable |
It sends back the status code, the headers and the HTML, which the browser displays.
Text description of the animation
- The user clicks a link.
- The browser resolves the name (DNS), then opens a TCP connection, encrypted with TLS for HTTPS.
- It sends the request, with its headers.
- The server prepares the requested page.
- It sends back the status code, the headers and the HTML, which the browser displays.
Parse an HTTP message
Since HTTP is text, a few lines of Python are enough to take it apart. Careful: lines are separated by \r\n (carriage return then line feed), a legacy of typewriters:
raw = (
"POST /login HTTP/1.1\r\n"
"Host: www.shop.example\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: 32\r\n"
"\r\n"
"email=awa%40example.sn&code=4821"
)
def parse(request):
head, _, body = request.partition("\r\n\r\n")
first, *lines = head.split("\r\n")
method, path, version = first.split(" ")
headers = {}
for line in lines:
name, _, value = line.partition(": ")
headers[name.lower()] = value
return method, path, headers, body
method, path, headers, body = parse(raw)
print(method, path)
print(headers["host"], headers["content-type"])
print("body:", body)
POST /login
www.shop.example application/x-www-form-urlencoded
body: email=awa%40example.sn&code=4821
partition("\r\n\r\n")cuts at the empty line: before it, the head; after it, the body;- header names are case-insensitive (
Hostorhost): we lower-case them; - in the body,
%40is the encoding of@: some characters are encoded in forms.
This message contains a login and a code. Who can read it on the way?
A mini-server without a network
On the server side, the job is to match each request with a response. Here is a minimal router, without a network, that shows what web frameworks do:
pages = {"/": "Home", "/courses": "List of courses", "/contact": "Write to us"}
def respond(method, path):
if method != "GET":
return "HTTP/1.1 405 Method Not Allowed", ""
if path not in pages:
return "HTTP/1.1 404 Not Found", "Page not found"
return "HTTP/1.1 200 OK", pages[path]
for method, path in [("GET", "/courses"), ("GET", "/prices"), ("DELETE", "/courses")]:
status, body = respond(method, path)
print(f"{method} {path:<8} → {status} | {body}")
GET /courses → HTTP/1.1 200 OK | List of courses
GET /prices → HTTP/1.1 404 Not Found | Page not found
DELETE /courses → HTTP/1.1 405 Method Not Allowed |
405 means the resource exists, but not for this method: here, the list of courses cannot be deleted.
Mini-lab: build your responsePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: sorting the responses
A server log contains status codes: [200, 200, 404, 500, 301, 200, 403, 503, 200, 404]. Write a function that groups them by family ("2xx", "3xx", "4xx", "5xx") and computes the percentage of server errors. Above 5%, print an alert.
Hint 1
code // 100 gives the first digit: 404 // 100 is 4.Hint 2
collections.Counter counts the families in one line.Show the solution and common mistakes
from collections import Counter
codes = [200, 200, 404, 500, 301, 200, 403, 503, 200, 404]
def report(codes, threshold=5):
families = Counter(f"{c // 100}xx" for c in codes)
server_errors = families["5xx"] / len(codes) * 100
print(dict(sorted(families.items())))
print(f"server errors: {server_errors:.0f}%")
if server_errors > threshold:
print("ALERT: the server is having problems")
report(codes)
{'2xx': 4, '3xx': 1, '4xx': 3, '5xx': 2}
server errors: 20%
ALERT: the server is having problems
404 and 403 are client errors: a missing page, a refused access. They do not necessarily signal a failure. 5xx codes indicate a server-side problem: those are the ones that trigger alerts.
Common mistakes:
- Counting all errors (4xx and 5xx) together: a bot probing missing pages would set the alert off for nothing.
- Using
code / 100: you get 4.04 instead of 4, and the families do not group together.
Summary
- 1HTTP is a text request-response protocol: method, path, headers, empty line, body.
- 2The main methods are GET, POST, PUT and DELETE.
- 3Status codes read by family: 2xx success, 3xx redirection, 4xx client error, 5xx server error.
- 4In plain HTTP, everything travels in clear text; HTTPS encrypts the journey with TLS and authenticates the server.
- 5HTTPS protects the journey, not the site's honesty: a padlock does not guarantee a site is trustworthy.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.