Build and Operate HTTP APIs
Design, test, deploy, and operate an HTTP API that another engineer can use.
import and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.
Which promises does a TypeScript type make about a value received over the network?
Type annotations check assumptions in source code and are erased at runtime. A type guard inspects actual fields before the program treats outside data as a known shape.
Receive an unknown content block
Check the discriminant and required property types
Handle it as the matching block type or reject it
Receive an unknown content block
Check the discriminant and required property types
Handle it as the matching block type or reject it
Given Receive an unknown content block and Handle it as the matching block type or reject it, write down the missing step that connects them.
Check the discriminant and required property types
Now take Check the discriminant and required property types and the result above. Write an input and an implementation that could produce this trace.
Receive an unknown content block. Check that your implementation produces the result shown above.
An incoming block declares type "text" but its text is the number 7. Should the text-block guard accept it?
No. Check both the type tag and that text is a string. The outside input can violate a compile-time interface.
Check this when debugging. Thinking TypeScript checks types while the program runs.
You will read more TypeScript than you write. SDK examples, MCP servers and front-end code are often TypeScript, and a Python programmer who can read it can use all of them. The good news is that TypeScript is JavaScript with notes written beside the names: the notes say what kind of value each name holds, a checker reads them before the program runs, and then they are removed. This lesson teaches reading: modules, a package file, classes, and the types you will see most, ending on a small tool server that you map line by line to the Python one you met in the MCP phase.
import { z } from "zod"; and has function area(w: number, h: number): number. What are the : number parts?Notes about types, checked before the program runs and then removed
They are TypeScript type annotations. A checker reads them before the program runs, and then they are removed, so the JavaScript that runs has none of them.
This rests on JavaScript for Python programmers, which mapped Python to JavaScript, and Async JavaScript: promises, await and fetch, whose await and fetch appear in every TypeScript example. A project of several files needs three things Python gives you with import, a package manager and a type checker. In JavaScript the first is modules: a file that writes export function f() {} offers f, and another that writes import { f } from "./tools.js" takes it. The second is package.json, a file at the project's root that names the project and its dependencies, and, with "type": "module", tells Node that its files use import. npm install reads it, as pip install -r requirements.txt does. The third is TypeScript: you write name: string beside a name, the compiler checks that every use agrees, and a file ending .ts becomes plain JavaScript with the notes removed. The picture shows three files of a small project. A small project also rewards a few habits: read the package.json first, since it names the entry file and the commands, and look for a tsconfig.json, which sets how strictly the compiler checks, so a project with strict settings rejects code that a lax one would accept.
The import names the file as ./tools.js, even though the source is tools.ts: it names the JavaScript the compiler will write.
"2" + 1?"21"
+ joins as soon as one side is text, so the number is turned into text and joined: "21". TypeScript's types exist to catch this kind of slip before the program runs.
Write a sentence or two, then compare it with a good answer in the lesson.
A class groups data with the functions that use it, as in Python. The differences to read past: the constructor is called constructor, not __init__; the instance is this, not self, and you must write it; a name starting with # is private; and get value() makes a property that is computed when read. Run the cell, then change the numbers.
class Cart { #items = []; constructor(owner) { this.owner = owner; } add(sku, qty = 1) { this.#items.push({ sku, qty }); return this; } get count() { return this.#items.reduce((n, item) => n + item.qty, 0); } } const cart = new Cart("ana").add("TENT").add("MUG", 2); console.log(cart.owner, cart.count);
add returns this, so calls chain. count is read without parentheses, because it is a getter.
Now the same shape with the notes TypeScript adds. This block is shown, not run: the page runs JavaScript. Read the notes, and read what each protects.
class Cart { #items: { sku: string; qty: number }[] = []; constructor(public owner: string) {} add(sku: string, qty: number = 1): this { this.#items.push({ sku, qty }); return this; } get count(): number { return this.#items.reduce((n, item) => n + item.qty, 0); } }
{ sku: string; qty: number }[] is an array of objects with those two fields, public owner: string declares and sets the field in one go, and : number after the parentheses says what add and count return. With these notes, cart.add(42) is a compile error: 42 is not a string.
function ship(order: Order | undefined): string. Which call does the compiler accept?ship(undefined); ship(null); ship(42); ship("TENT");
ship(undefined) only, since the others are not an Order or undefined
The parameter is an Order or undefined. null is a different value, 42 is a number, and "TENT" is a string, so only ship(undefined) and a real Order are accepted.
The type you will meet most is the union, a value that is one of several shapes. A reply's content is a list of blocks, and a block is either a text block or a tool call, told apart by one field. Read this and the cell after it together: the type is a note, and the if in the cell is the same check, made while the program runs.
type Block = | { type: "text"; text: string } | { type: "tool_use"; name: string; input: Record<string, unknown> };
const blocks = [ { type: "text", text: "Let me look that up." }, { type: "tool_use", name: "get_stock", input: { sku: "MUG-01" } }, ]; for (const block of blocks) { if (block.type === "text") { console.log("text:", block.text); } else { console.log("tool:", block.name, JSON.stringify(block.input)); } }
Inside if (block.type === "text") the compiler knows block.text exists, and in the else it knows block.name does. That is called narrowing. Two more notes appear everywhere: ? after a name means optional (input?: string), and <T> marks a generic, a type that takes a type, so Promise<string> is a promise of a string and Array<number> is number[].
const block = { type: "text", text: "Hi" };
console.log(block.type === "tool_use" ? block.name : "no tool", Object.keys(block));no tool [ 'type', 'text' ]
The type is "text", so the test is false and the else side runs. block.name is never read. In TypeScript the compiler narrows the type inside each branch, so reading .name on the text side would be an error.
A Map is JavaScript's dictionary with any key type. In TypeScript it is written Map<string, string[]>: a map from strings to arrays of strings.
const groups = new Map(); for (const word of ["tent", "tarp", "mug", "map"]) { const key = word[0]; groups.set(key, [...(groups.get(key) ?? []), word]); } console.log([...groups]); console.log(groups.get("t").length, groups.has("z"));
groups.get(key) ?? [] is groups.get(key, []): a missing key gives an empty array to extend. The spread [...] copies it and adds the word, as Python's groups.get(key, []) + [word] would. The map ends with two keys: t has two words and m has two.
const stock = { "TENT-2P": 4, "MUG-01": 0 };
console.log(stock["MUG-01"] ?? 9, stock["LAMP-1"] ?? 9, stock["MUG-01"] || 9);0 9 9
?? replaces only undefined and null, so a real 0 stays 0, and the missing key becomes 9. || replaces every falsy value, so 0 becomes 9 too. That is why the tool server writes ?? 0.
Write the class Basket: add(sku, qty = 1) adds a line and returns this; remove(sku) deletes every line with that sku and returns this; the getter count is the total quantity. Keep the lines in a private #lines array.
class Basket { #lines = []; add(sku, qty = 1) { return this; } remove(sku) { return this; } get count() { return 0; } } const b = new Basket().add("TENT").add("MUG", 2).remove("TENT"); console.log(b.count);
Write describe(block): for a block with type text return text: <its text>; for type tool_use return tool: <name>(<the keys of input, joined by commas>); for anything else return the word unknown.
function describe(block) {
return "unknown";
}
console.log(describe({ type: "text", text: "Hi" }));
console.log(describe({ type: "tool_use", name: "get_stock", input: { sku: "M" } }));A TypeScript type protects you from your own mistakes, not from the world: data from a model or a network is whatever it is, and the notes are gone at run time. So code that reads outside data still checks it. A type guard is a function that does that check. The exercise below is one.
Write a sentence or two, then compare it with a good answer in the lesson.
An MCP server is a program that offers tools to a model, and the SDK's examples are often TypeScript. This one is about thirty lines. Each idea is one you know from Python, with different spellings, and Build a server: tools builds the same server in Python. Read it from the top and say, for each line, what it does.
async ({ sku }) => { ... }. What does ({ sku }) do?Pulls the sku field out of the input object into a name
It is destructuring: the handler receives one object, and { sku } takes its sku field into a local name. It is the same as async (input) => { const sku = input.sku; ... }.
Three situations. Copying an SDK example and wanting to know what ! after a name means (it tells the compiler "trust me, this is not undefined"). A type error you did not expect when a function that returns string | undefined is used as a string, which is the compiler catching a real bug. Reading a front end that renders a model's reply, whose types describe the blocks. In each, the types are a map of what the code expects. Goes deeper in: Build a server: tools writes this server in Python, The same server with the official SDKs uses the official SDKs, and A chat front end in the browser reads a reply in a page.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What does TypeScript do to a type annotation such as : number before the program runs?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
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