Skip to main content

One Handler per Route

Routing decides which code answers which request. The standard http.server has no router built in — and none is needed for the everyday cases: do_GET looks at self.path and dispatches.

A path parameter is the piece of the URL that is data: in /users/7, the 7. Splitting the path into segments hands it to you: "/users/7".strip("/").split("/") gives ['users', '7']. Frameworks add pattern routers on top, but this is what they do underneath.


Routes and Path Values

Two routes: the list at /users and one user at /users/7. The id segment is the path parameter — the part of the URL that carries data.

A route with a path parameter

The same do_GET sends /users to one branch and /users/7 to another — one split, and the second segment delivers the 7.

Prompt
Write a Python program whose do_GET splits the URL path into segments to route GET /users to a list line and GET /users/7 to a one-user line that uses the id segment as the path parameter. Serve on a free port, request both paths and print the responses.
Output: complete Python program

Query Parameters

The part after ? holds query parameters — options for the request, like a search text or a limit: /search?q=python&limit=2. urlparse splits them off the path and parse_qs turns them into a dict of lists — always strings, with .get covering the missing ones.

The rule of thumb: the path says which resource, the query says how — filters, sorting, paging.

Reading the query string

The handler reads q and limit from the query. The second request skips limit, so the handler falls back to a default — missing parameters are normal, plan for them.

Prompt
Write a Python program with a /search handler that reads the q and limit query parameters using urlparse and parse_qs, with a default limit when it is missing. Serve on a free port, request it once with both parameters and once with only q, printing the responses.
Output: complete Python program