Notes
All notes

Learn the Basics (API Design #1)

Your team ships a mobile app that shows delivery status. The app has no database of packages; it asks someone else’s system: “Where is package 8421?” and gets back {"status": "out_for_delivery", "eta": "14:35"}. That question-and-answer exchange crosses a network, between two pieces of software owned by different teams, and it works because both sides agreed — in advance — on exactly how to ask and exactly what the answer looks like.

That agreement is an API (Application Programming Interface), and this whole course is about designing agreements that survive scale, change, and misuse. This chapter covers the substrate every web API stands on: what makes a network service an API at all, the HTTP request/response cycle, methods and status codes, headers and content negotiation, and the plumbing underneath — DNS, TCP/IP, TLS, cookies, CORS, and caching.

By the end you will be able to read a raw HTTP exchange line by line, predict what each part does, and explain where every millisecond of an API call goes.

What makes something an API

Not every program that answers network requests is an API worth the name. A useful API has three properties:

  1. A stable contract. The shape of valid requests and responses is documented and changes carefully, with versions. Clients are written against the contract, not against today’s behavior of your server.
  2. Statelessness. Each request carries everything the server needs to handle it. No “remember what you told me last call” — that is what auth tokens and resource IDs are for.
  3. Self-describing responses. A response tells you what happened (status code), what format the payload is in (Content-Type), and how long you may keep it (Cache-Control) — not just the payload.

The payoff is independence. The app team and the platform team ship on different schedules because both code against the contract. Break the contract without warning and you get what engineers call integration hell: every deploy is a game of “which client broke this time.”

APIs predate the web — database APIs (JDBC), OS APIs (POSIX), library APIs (stdlib) all follow the same contract idea. This course is about web APIs: contracts spoken over HTTP, almost always with JSON payloads.

The HTTP request/response cycle

Every web API call is one HTTP request followed by one HTTP response. Strip away the frameworks and this is what actually crosses the wire:

GET /packages/8421?fields=status,eta HTTP/1.1
Host: api.logistics.example
Accept: application/json
Authorization: Bearer eyJhbGciOi...
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=30

{"id": "8421", "status": "out_for_delivery", "eta": "14:35"}

Read the request line by line. GET is the method — the verb. /packages/8421 is the path — which resource. ?fields=status,eta is the query string — modifiers of the request. The headers carry metadata: what format you accept, who you are. The response answers with a status code, its own headers, and a body.

Here is the whole cycle as a picture:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.4cm, minimum height=0.75cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (c) at (0,0) {client};
  \node[b, fill=orange!16] (s) at (7,0) {server};
  \draw[a] (c.north) to[bend left=25] node[above, font=\rmfamily\scriptsize, align=center] {request: method + path + headers (+ body)} (s.north);
  \draw[a] (s.south) to[bend left=25] node[below, font=\rmfamily\scriptsize, align=center] {response: status + headers + body} (c.south);
  \node[b, dashed, fill=gray!8, minimum width=4.6cm] (k) at (3.5,1.8) {API contract\\(both sides agree)};
  \draw[dashed, gray] (k.west) -- (c.north east);
  \draw[dashed, gray] (k.east) -- (s.north west);
\end{tikzpicture}

One formula worth memorizing is where the time goes in that single round trip:

\[ T_{\text{total}} = T_{\text{DNS}} + T_{\text{TCP}} + T_{\text{TLS}} + T_{\text{server}} + T_{\text{transfer}} \]

On a cold connection, DNS resolution (~20–120 ms), the TCP handshake (one round trip), and the TLS handshake (one to two round trips) can dwarf the server’s actual work (~5 ms for a cached read). This is why connection reuse (keep-alive, HTTP/2) matters more than shaving microseconds off your handler — Chapter 10 goes deep on performance.

Methods and URLs: the verb and the noun

The method declares intent; the URL names the resource. The five you will use constantly:

Method Intent Has body? Idempotent? Typical success
GET read a resource no yes 200
POST create / trigger an action yes no 201
PUT replace a resource wholesale yes yes 200
PATCH modify part of a resource yes no* 200
DELETE remove a resource no yes 204

Idempotent means repeating the call has the same effect as calling it once. It matters because networks fail: if your DELETE /packages/8421 times out, retrying is safe. If your POST /payments times out, retrying might charge twice — which is why POST needs extra machinery (idempotency keys, Chapter 14).

URLs decompose into parts, and each part has a job:

https://api.logistics.example:443/v2/packages/8421?fields=status,eta
\___/   \_____________________/ \_/ \___________/ \______________/
 scheme        host            port     path          query string

The classic mistake is putting identity in the query (/package?id=8421 for a specific package) or verbs in the path (/getPackage). Chapter 2 develops resource modeling properly.

Status codes: the verdict

The three-digit status code is the server’s structured verdict. Learn the five classes and the handful of codes that do real work:

Class Meaning Codes you will actually use
2xx success 200 OK, 201 Created, 204 No Content, 202 Accepted
3xx go elsewhere 301 Moved Permanently, 304 Not Modified
4xx your fault (client) 400, 401, 403, 404, 409 Conflict, 422, 429 Too Many Requests
5xx my fault (server) 500, 502 Bad Gateway, 503 Service Unavailable, 504

Two distinctions pay rent immediately. 401 Unauthorized means “I don’t know who you are” (missing/bad credentials); 403 Forbidden means “I know who you are, and no” — Chapters 5 and 6. And 429 with a Retry-After header is how a server says “slow down” without banning you — smart clients honor it with backoff instead of hammering.

Well-behaved clients branch on specific codes, not just “2xx vs not”:

import time, requests

def get_package(pid: str):
    for attempt in range(4):
        r = requests.get(f"https://api.logistics.example/v2/packages/{pid}",
                         headers={"Authorization": "Bearer ..."}, timeout=5)
        if r.status_code == 200:
            return r.json()
        if r.status_code == 404:
            raise LookupError(f"no such package: {pid}")   # don't retry
        if r.status_code in (429, 500, 502, 503, 504):     # transient
            time.sleep(2 ** attempt)                       # back off
            continue
        raise RuntimeError(f"unexpected {r.status_code}: {r.text}")
    raise TimeoutError("gave up after retries")

Notice the logic: 404 is permanent (retrying finds nothing), while 429 and 5xx are transient (retrying with exponential backoff often succeeds).

Headers and content negotiation

Headers are the control channel. A few carry most of the weight:

Accept enables content negotiation: one endpoint, multiple representations. A client that sends Accept: application/json gets JSON; a reporting tool that sends Accept: text/csv can get the same resource as CSV. The server picks the best match and answers with Content-Type stating what it actually sent; if it cannot satisfy any acceptable type, the honest answer is 406 Not Acceptable.

The JSON-vs-anything war is over for most APIs — JSON won on readability and browser support — but negotiation is still how you version representations (Accept: application/vnd.example.v2+json) without minting new URLs.

Under the hood: DNS, TCP/IP, TLS, and HTTP versions

HTTP does not float in space; it rides a stack. Each layer has one job:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=6.4cm, minimum height=0.7cm, align=center, font=\rmfamily\small}]
  \node[b, fill=blue!10]  (h) at (0,0)    {HTTP — requests, responses, semantics};
  \node[b, fill=green!12] (t) at (0,-1.0) {TLS — encryption, server identity (HTTPS)};
  \node[b, fill=orange!14] (c) at (0,-2.0) {TCP — reliable, ordered byte stream};
  \node[b, fill=gray!12] (i) at (0,-3.0) {IP — routing packets between hosts};
  \node[b, dashed, fill=white] (d) at (0,-4.0) {DNS — name $\rightarrow$ IP address (runs before all of this)};
\end{tikzpicture}

Cookies and CORS: the browser’s two rules

Two mechanisms exist only because browsers run untrusted code on behalf of users.

Cookies are small state tokens the server sets (Set-Cookie) and the browser attaches automatically to every later request to that origin. They power session-based login (Chapter 5). Because they ride every request, they need flags: HttpOnly (invisible to JavaScript), Secure (HTTPS only), SameSite (limits cross-site sending, blunting CSRF).

CORS (Cross-Origin Resource Sharing) is the relaxation valve on the browser’s same-origin policy. By default, JavaScript on app.example.com cannot read responses from api.example.com. The API opts in with headers:

Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Authorization, Content-Type

For non-simple requests (JSON bodies, custom headers) the browser first sends a OPTIONS preflight; the API must answer it correctly or the real request never fires. When a teammate says “the API is broken, works in curl but not the browser” — it is CORS, almost always.

HTTP caching: the free performance

The cheapest API call is the one never made. HTTP has caching built in:

The economics compound. If a resource changes every \(\bar{c}\) seconds on average and clients poll every \(p\) seconds, a naive client transfers the body \(1/p\) times per second, while a client using validators transfers it at most \(1/\bar{c}\) times — the 304 responses in between are a few hundred bytes of headers. Chapter 10 turns this into a full caching strategy.

Pitfalls

QQuestionSelf-check

What are the three properties that make a network service a real API? A client gets 401 on one endpoint and 403 on another — what is the difference, and what should it do next in each case? Using \(T_{\text{total}} = T_{\text{DNS}} + T_{\text{TCP}} + T_{\text{TLS}} + T_{\text{server}} + T_{\text{transfer}}\), why does reusing connections beat micro-optimizing the handler for a chatty client?

ASolution

A stable contract, statelessness, and self-describing responses. 401 means unauthenticated — obtain or refresh credentials and retry; 403 means authenticated but not allowed — retrying with the same identity will never work, so escalate or request access. The handshake terms (DNS, TCP, TLS) are paid per new connection and often total 100 ms+, while a warm handler may take single-digit milliseconds; keep-alive and HTTP/2 multiplexing amortize the handshakes, which is a bigger win than shaving the handler.

Next: Different API Styles (API Design #2) — REST, SOAP, GraphQL, and gRPC as four answers to the same contract question.