Skip to content
Index Ai Academy
Phase 8 · Building APIs

Build an API server from scratch

Routing, handlers and responses, with no framework.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers7

First principles

How does a basic server decide which function to call for a request?

A router matches a method and path to a handler. The handler builds a response from the matching route and whatever data the request carries.

  1. Starting point

    Receive GET /reports/9

  2. What changes

    Look up GET and the report route and extract ID 9

  3. Result

    The matching handler returns a response

Compare all three steps
  1. Starting point

    Receive GET /reports/9

  2. What changes

    Look up GET and the report route and extract ID 9

  3. Result

    The matching handler returns a response

Complete and reverse the trace

Given Receive GET /reports/9 and The matching handler returns a response, write down the missing step that connects them.

Compare with the worked step

Look up GET and the report route and extract ID 9

Now take Look up GET and the report route and extract ID 9 and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Receive GET /reports/9. Check that your implementation produces the result shown above.

Try it on a new case

If the path exists for GET only, what should a POST to it return?

Show worked reasoning

Return 405 Method Not Allowed and advertise the allowed methods. The resource path matched but the requested operation did not.

Run, change, and build

Check this when debugging. Returning 404 when the path exists but the method doesn't.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. If the path exists for GET only, what should a POST to it return?

Why it matters

Frameworks like FastAPI and Flask feel like magic until you have built the core yourself. It is smaller than you would think: a loop that reads requests, a table of routes, and functions that return responses. Once you have written it, a framework's docs read like a list of conveniences on top of something you understand. It matters for AI work because a model behind an API is exactly this shape, one function from a request to a response, and every serving problem, a hung request, a missing header, a slow start, is easier to place when you know the loop.

What you'll be able to do

  • Describe a web server as a loop around one function: request in, response out
  • Route requests by method and path, including path parameters like /campaigns/{id}
  • Return 404 and 405 correctly, with the Allow header
  • Write a WSGI and an ASGI app by hand, and call a server you built
Quick check
Stripped to its core, what is a web server?
  1. A program that stores every web page in a database
  2. A special computer that can only run websites
  3. A browser that runs on a machine without a screen
  4. A loop that reads requests, looks up a route and calls a function
Show the answer

A loop that reads requests, looks up a route and calls a function

A server waits for a request, matches its method and path against a table of routes, calls the matching function and sends back its response, then waits again. Frameworks add conveniences around that loop.

The idea: a loop around one function

This rests on HTTP from the wire up, where you parsed a request from bytes. Picture a waiter in a small restaurant. They wait for someone to sit down and take the order, pass it to the kitchen, bring back the food, then wait for the next person. A web server does the same, forever:

  1. Wait for a client to connect.
  2. Read the request bytes and parse them.
  3. Call a function that turns the request into a response. That is the kitchen.
  4. Send the response bytes back, and go to 1.

Steps 1, 2 and 4 are plumbing, the same for every app. Step 3 is where your application lives, and it is an ordinary function from a request object to a response object. Here is the plumbing with Python's socket module (shown, not run: the academy's Python can't open ports).

import socket

with socket.create_server(("127.0.0.1", 8000)) as server:
    while True:
        conn, addr = server.accept()               # 1. wait for a client
        with conn:
            raw = conn.recv(65536)                 # 2. read the request
            response = handle(parse_request(raw))  # 3. YOUR app
            conn.sendall(response)                 # 4. send the answer

create_server opens a door on port 8000, and accept waits until someone knocks. Watch one request go through it.

Try it now

Everything in a web framework is built around this loop.

Routing, 404 and 405

Think of an office switchboard. A call comes in asking for sales, and the operator looks up the extension. The router does that job. Each route is a row in its table: a method, a path pattern and a handler. A pattern can hold path parameters in braces: /campaigns/{id} matches /campaigns/cmp_103 and captures id = "cmp_103". Matching works one segment at a time, a segment being the text between slashes. Literal segments must match exactly, {id} accepts any non-empty text, and paths with a different number of segments never match.

There are two different ways to be turned away. 404 Not Found means no pattern matches the path at all, as with the typo GET /campaings. 405 Method Not Allowed means the path matches but not with this method, as with DELETE /campaigns when only GET and POST exist there. A 405 must carry an Allow header listing the methods that work, such as Allow: GET, POST, so the client learns what it can do instead. Pick a case and watch the request leave at the right check.

Quick check
Your server has routes for GET /campaigns and POST /campaigns. A client sends DELETE /campaigns. Which status fits?
  1. 200 OK, ignoring the method and returning the campaigns
  2. 405 Method Not Allowed, with an Allow header listing GET and POST
  3. 400 Bad Request, since the request is wrong
  4. 404 Not Found, since there is no DELETE route
Show the answer

405 Method Not Allowed, with an Allow header listing GET and POST

The path exists, so it is not 404. The method is not supported there, and the Allow header tells the client what is.

Quick check
Recall: Content-Length counts the body's bytes, not its characters. What does this print for a body with one accented letter?
body = '{"name": "Café"}'
print(len(body), len(body.encode("utf-8")))
  1. 16 17
  2. 17 16
  3. 16 16
  4. 14 15
Show the answer

16 17

The body has 16 characters, and the é takes two bytes in UTF-8, so it is 17 bytes on the wire. A server that read 16 would stop one byte short of the end of the JSON.

In your own words
What is the difference between a 404 and a 405?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: objects, a router and an app you can call

Nobody wants to pick through raw bytes in every function, so parse the bytes once and pass around small objects. A handler is a function from a Request to a Response: one dish on the menu. The router below picks the handler.

Run the request and response as plain data, and read what each one holds.

Setup (runs before every cell) · 59 lines

The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.

import json

CAMPAIGNS = {"cmp_1": {"id": "cmp_1", "name": "Spring sale", "budget": 500}}
SEED = json.loads(json.dumps(CAMPAIGNS))
ROUTES = []


def route(method, pattern):
    def register(handler):
        ROUTES.append((method, pattern, handler))
        return handler
    return register


def match_pattern(pattern, path):
    p_parts, parts = pattern.strip("/").split("/"), path.strip("/").split("/")
    if len(p_parts) != len(parts):
        return None
    params = {}
    for p, a in zip(p_parts, parts):
        if p.startswith("{") and p.endswith("}"):
            if not a:
                return None
            params[p[1:-1]] = a
        elif p != a:
            return None
    return params


@route("GET", "/campaigns")
def list_campaigns(params, body):
    return 200, {"data": list(CAMPAIGNS.values())}


@route("GET", "/campaigns/{id}")
def get_campaign(params, body):
    c = CAMPAIGNS.get(params["id"])
    return (200, c) if c else (404, {"error": f"no campaign {params['id']}"})


@route("POST", "/campaigns")
def create_campaign(params, body):
    new_id = f"cmp_{len(CAMPAIGNS) + 1}"
    CAMPAIGNS[new_id] = {"id": new_id, **body}
    return 201, CAMPAIGNS[new_id]


def handle(method, path, body=None):
    allowed = []
    for m, pattern, handler in ROUTES:
        params = match_pattern(pattern, path)
        if params is None:
            continue
        if m == method:
            return handler(params, body)
        allowed.append(m)
    if allowed:
        return 405, {"error": "method not allowed", "allow": sorted(allowed)}
    return 404, {"error": "not found"}
from dataclasses import dataclass, field
import json

@dataclass
class Request:
    method: str
    path: str
    query: dict = field(default_factory=dict)
    headers: dict = field(default_factory=dict)
    body: bytes = b""

    def json(self):
        return json.loads(self.body or b"null")

@dataclass
class Response:
    status: int
    body: object = None
    headers: dict = field(default_factory=dict)

def hello(req):
    name = req.query.get("name", "world")
    return Response(200, {"message": f"Hello, {name}!"})

print(hello(Request("GET", "/hello", query={"name": "Ada"})))
It runs right here in your browser, with nothing to install.
Quick check
What does this print?
from dataclasses import dataclass

@dataclass
class Response:
    status: int
    body: object = None

r = Response(404)
print(r.status, r.body)
  1. 404 None
  2. 404 {}
  3. 404
  4. Response(404)
Show the answer

404 None

A dataclass field with a default keeps it when the caller leaves it out, so body is None. Handlers fill it in.

Drill

Parse a query string

Write parse_query(query): turn "tag=rain&page=2&tag=sale" into {"tag": ["rain", "sale"], "page": ["2"]}. A name can repeat, so every value goes in a list; a pair with no = gets the value ""; empty pieces (from &&) are skipped. Decode each part with urllib.parse.unquote_plus.

Uses the setup above, 59 lines.

from urllib.parse import unquote_plus


def parse_query(query):
    return dict(pair.split("=") for pair in query.split("&"))


print(parse_query("tag=rain&page=2&tag=sale"))
In the lesson, your code is checked as you write it.

The lesson's setup holds a complete tiny API: a @route decorator that adds a handler to the table (decorators are from Closures and decorators), match_pattern from the picture above, and handle, which tries each route. A path match with the wrong method is noted for the 405, and no match at all is a 404.

Worked example

A complete tiny API

Three handlers and a handle function, with no framework. The data lives in a dict standing in for a database.

Uses the setup above, 59 lines.

CAMPAIGNS.clear()
CAMPAIGNS.update(SEED)
print(handle("POST", "/campaigns", {"name": "Autumn", "budget": 300}))
print(handle("GET", "/campaigns/cmp_2"))
print(handle("DELETE", "/campaigns"))
print(handle("GET", "/campaings"))
In the lesson you can change this and run it.

@route(...) ran when each handler was defined and added it to the route table. The POST made cmp_2, the GET found it, the DELETE got a 405 that lists the allowed methods, and the typo got a 404.

The stepper runs the routing loop on the 405 case. Watch allowed fill as the loop passes a pattern that matches the path, and watch the else branch run only because the loop never hit break.

Quick check
What does this print?
routes = {"/items": ["GET"]}
path, method = "/items", "DELETE"
if path not in routes: print(404)
elif method not in routes[path]: print(405)
else: print(200)
  1. 405
  2. 200
  3. 404
  4. DELETE
Show the answer

405

The path exists, but not with that method, so it is 405 rather than 404.

WSGI and ASGI: the standard plug

Any lamp works in any wall socket, because everyone agreed on the shape of the plug. Python web servers and frameworks agreed on one for step 3, so any server can run any framework. WSGI is the classic plug: an app is a function app(environ, start_response). environ is a dict describing the request, and the app calls start_response(status, headers) and returns a list of body bytes. Flask and Django speak WSGI, and Gunicorn runs them.

Quick check
Why can Gunicorn run both Flask and Django apps?
  1. Gunicorn has special code built in for each framework it supports
  2. Gunicorn converts them both to JavaScript before running them
  3. Both speak WSGI, the standard interface between Python servers and apps
  4. Flask and Django are really the same framework under two names
Show the answer

Both speak WSGI, the standard interface between Python servers and apps

WSGI (and ASGI for async apps) is the agreed plug shape, so any server can run any framework that speaks it.

ASGI is the newer one, for async code, and FastAPI, Starlette and Uvicorn speak it. An ASGI app is an async function of three arguments: scope, a dict that describes the connection (its type, method and path); receive, an async function that returns the next piece of the request; and send, an async function the app calls with each piece of the reply. A reply is at least two messages, http.response.start (status and headers) and http.response.body. Because the app awaits receive and send, one process can hold thousands of open connections, including streams, and it can send a body in several pieces. Streaming from the server uses that.

Both are plain function calls, which is why a server's job is small and why test clients exist: they call your app the same way. Here is each one called by hand, with a fake receive and send for ASGI. (asyncio.run works on browsers with JSPI and in the validator; older browsers can't run the ASGI cell.)

Run the app once with a fake WSGI environment, the way a real server would call it.

Uses the setup above, 59 lines.

from wsgiref.util import setup_testing_defaults

def wsgi_app(environ, start_response):
    body = f"You asked for {environ['PATH_INFO']}".encode()
    headers = [("Content-Type", "text/plain"), ("Content-Length", str(len(body)))]
    start_response("200 OK", headers)
    return [body]

environ = {"PATH_INFO": "/campaigns", "REQUEST_METHOD": "GET"}
setup_testing_defaults(environ)
captured = {}
result = wsgi_app(environ, lambda s, h: captured.update(status=s, headers=h))
print(captured["status"], b"".join(result))

Uses the setup above, 59 lines.

import asyncio

async def asgi_app(scope, receive, send):
    assert scope["type"] == "http"
    body = f"You asked for {scope['path']}".encode()
    await send({"type": "http.response.start", "status": 200,
                "headers": [(b"content-type", b"text/plain")]})
    await send({"type": "http.response.body", "body": body})

sent = []

async def fake_receive():
    return {"type": "http.request", "body": b"", "more_body": False}

async def fake_send(message):
    sent.append(message)

scope = {"type": "http", "method": "GET", "path": "/campaigns"}
asyncio.run(asgi_app(scope, fake_receive, fake_send))
print([m["type"] for m in sent], sent[1]["body"])
Drill

A WSGI app by hand

Any WSGI server can run a function shaped like app(environ, start_response). Write one: for GET /health, call start_response("200 OK", [("Content-Type", "application/json")]) and return [b'{"ok": true}']; for any other path, start "404 Not Found" with the same header and return [b'{"error": "not found"}']. The method is environ["REQUEST_METHOD"] and the path environ["PATH_INFO"].

Uses the setup above, 59 lines.

def app(environ, start_response):
    start_response("200 OK", [])
    return ["ok"]


calls = []
print(
    app(
        {"REQUEST_METHOD": "GET", "PATH_INFO": "/health"},
        lambda status, headers: calls.append(status),
    ),
    calls,
)
In the lesson, your code is checked as you write it.
Quick check
In an ASGI app, what does await send({"type": "http.response.body", "body": b"hi"}) do?
  1. Reads the next piece of the request
  2. Starts the reply by sending the status
  3. Sends a piece of the reply body to the client
  4. Closes the server
Show the answer

Sends a piece of the reply body to the client

send carries the reply out, one message at a time. The start message sends the status and headers, and each body message sends bytes. receive is the one that reads the request.

In your own words
What are scope, receive and send in an ASGI app?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: the same loop behind a model

A production server wraps your app in the same loop with more staff: many workers (copies of the process), time limits, limits on body size and protection from slow clients. You don't write those parts. You plug your app into Gunicorn (WSGI) or Uvicorn (ASGI). A model behind an API is one more handler, a function from a request to a response, so the lessons about routing, 404 and 405 apply to POST /predict exactly as to GET /campaigns.

The picture shows where this lesson sits in a service. Then you call the server you just wrote.

serve(app) from the academy's devserver takes a WSGI or ASGI callable and returns the address to call it at, so requests reaches the app you built. Wrap handle in a WSGI function and call it over HTTP. It is a development server: one request at a time, no TLS.

Uses the setup above, 59 lines.

import json
import requests
from devserver import serve

def app(environ, start_response):
    length = int(environ.get("CONTENT_LENGTH") or 0)
    raw = environ["wsgi.input"].read(length) if length else b""
    body = json.loads(raw) if raw else None
    status, data = handle(environ["REQUEST_METHOD"], environ["PATH_INFO"], body)
    payload = json.dumps(data).encode()
    phrases = {200: "OK", 201: "Created", 404: "Not Found", 405: "Method Not Allowed"}
    headers = [("Content-Type", "application/json")]
    start_response(f"{status} {phrases[status]}", headers)
    return [payload]

base = serve(app)
print(requests.get(f"{base}/campaigns/cmp_1").json())
r = requests.delete(f"{base}/campaigns")
print(r.status_code, r.json())

The DELETE got its 405 over a real HTTP call. That tiny server did the loop's four steps on every call. The wrapper above does not yet add the Allow header your 405 owes the client, which is the exercise's job.

Where this shows up in an engineer's week

Three habits come from this lesson. Answer 404 and 405 correctly: it tells a developer at once whether they misspelled the URL or used the wrong verb. Check your path patterns: /items/{id} must not match /items/, or a handler receives an empty id and may list or delete the wrong thing. Test without a network: an app is a function, so call it directly, which runs thousands of times faster than a real server and cannot fail because a port is busy. Keep a few real end-to-end tests and do the rest this way.

Goes deeper in: A web framework, from the inside builds middleware and decorators on this router, APIs with FastAPI replaces it, and System design fundamentals adds the load balancer in front of many workers.

In your own words
Why does it help to build a server by hand before using a framework?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 6 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What is the difference between a 404 and a 405?

  1. 404: no route matches the path. 405: the path exists but not with this method
  2. 404 is for GET requests that fail, and 405 is for POST requests that fail
  3. 405 means the server is down for now, and 404 means the page has gone for good
  4. They mean the same thing, and which one you get depends on the framework

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

Free Python developer course

Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.

Part of a free course 20 lessons

Build and Operate HTTP APIs

Design, test, deploy, and operate an HTTP API that another engineer can use.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write