Vibe coding with Claude Code course Β· Module 14: Pinterest clone
Trade Routes: API Routes with a Spec from an Interview
In this lesson12
The boards already lie in the database but the pins still sail the old route. The home page and GET /api/pins read the list from lib/pins.ts, a new pin cannot be added, and a single pin cannot be fetched by its id. API routes are a contract with everyone who knocks on them: who may add a pin, which fields we accept, what code a stranger gets, how we split the list into pages. If you write only "make a pins API", Claude will quietly make each of these decisions, and you will find them only in the code. That is why you start with an interview, as in lessons 0_5 and 1_6, and the build comes only from a written contract.
What you will learn
- run an interview that produces a
SPEC.mdfor the API; - start the build in a fresh session, in plan mode, from the specification alone;
- recognise mass assignment (
data: body) and replace it with a list of allowed fields; - tell the responses 400, 401, 404 and 201 apart and prove them with
curl; - judge when GraphQL is worth reaching for instead of REST routes.
Request for Claude Code: the interview
Switch the session to Manual: the interview changes nothing, and Claude will ask for permission only before writing a file.
Request for Claude Code:
I want API routes for pins in Treasure Map: a paginated list, adding
a pin and one pin by id. The database client is in @lib/prisma.ts,
boards in @lib/boards.ts, the session in @lib/session.ts. Interview
me, at most three questions at a time: who may do what, which error
codes we return, how pagination works, which fields we accept from the
client and which the server sets. Then write SPEC.md: goal, routes,
fields, errors, what we do not do, how we will check it. Do not write
code.The Claude Code best practices describe this pattern as follows: Claude comes back with multiple-choice questions about things you have not settled yet, and keeps asking until the answers add up to a specification. It asks with the AskUserQuestion tool. You pick a ready answer or type your own in the Other row. For an API the questions may look like this:
1. Who may add a pin?
a) any logged-in user b) only the board owner c) anyone
2. What does a client get who sends a field outside the list?
a) 400 with the field name b) the field is silently dropped
3. How do we split the pin list into pages?
a) a cursor like in lesson 13_1 b) a page numberYou answer each question with an attacker in mind, not only a browser: a field you did not foresee is a field someone will eventually send.
What Claude wrote: SPEC.md
Open SPEC.md in Cursor. Your file will use other words, but it should record the same decisions. The most important part may look like this:
## Routes
- GET /api/pins?cursor=<id>: 12 pins and nextCursor (null at the end), for everyone.
- GET /api/pins/<id>: one pin or 404. The id is a string, never a number.
- POST /api/pins: logged-in users only (401). Fields: title, src (from /pins/),
width, height, dominantColor, tags (at most 5).
## Set by the server
- id, ownerId and author from the session, createdAt. A field outside the list: 400 with its name.
## What we do not do
- editing and deleting pins, uploading images.The specification says "what", not "how": it has no file names and no order of work. The "Set by the server" section is the most important part of this contract, and you will come back to it in the review.
A fresh session and a plan from the spec
The conversation from the interview is full of rejected ideas. The Claude Code documentation advises building in a fresh session, with a clean context and a written definition of "done". Type /clear: the old conversation stays available to resume, and the new one knows only what you give it. Then:
/plan Build the pin routes according to @SPEC.md. First the validation
tests for POST /api/pins: a field outside the list, ownerId in the
body, an empty title, numbers sent as strings, no session. Then the
code. Validate with a Zod schema, as in lesson 6_1. The home page
should take the first page of pins from the same function as the
route. At the end tests, lint, npx tsc --noEmit and npm run build.With @SPEC.md Claude gets the contract without the noise of the earlier conversation. In the plan check that the tests come before the code and that the pin owner comes from getCurrentUserId(). Claude will add the zod library to the project.
What Claude wrote: the list of allowed fields
Open lib/pinInput.ts. An allowlist names everything the client may send. Whatever is not on it does not pass:
// lib/pinInput.ts
export const pinInputSchema = z.strictObject(
{
title: z.string().trim().min(1, "Enter a title.").max(100, "The title has 100 characters at most."),
src: z.string().startsWith("/pins/", "The image must live in /pins/."),
width: pixels,
height: pixels,
dominantColor: z.string().regex(/^#[0-9a-f]{6}$/, "A colour in #rrggbb format."),
tags: z.array(z.string().trim().min(1).max(30)).max(5, "At most 5 tags.").default([]),
},
{ error: (issue) => (issue.code === "unrecognized_keys" ? `Unknown fields: ${issue.keys.join(", ")}` : undefined) },
);You know the Zod schema from lesson 6_1. z.strictObject differs from z.object in one thing: an unknown key is an error, not a quietly dropped field. The last argument turns that error into a message with the field name. pixels is a constant from this file: an integer from 1 to 10000, so the string "600" will not pass. startsWith("/pins/") lets in only images from our own port. Five tests guard these rules.
A typical agent mistake: data: body
The shortest route an agent can write, and the one from the old version of this lesson, looks like this:
// app/api/pins/route.ts (the agent version)
const body = await request.json();
const pin = await prisma.pin.create({ data: body });This is mass assignment: the client decides about every column. We passed a body with "ownerId": "captain" and "author": "Captain Redbeard" to create this way, and Prisma obediently saved the pin to the captain's account, even though the body could have come from Polly. Our model happened to reject the role field with an Unknown argument error, which in a route ends as a 500. But in a users table with a role column the same line would let anyone grant themselves administrator rights. The trap also has a spread version: in { ownerId: viewerId, ...body } the body overwrites the owner, because whatever comes later wins. In our run the pin landed with the captain again.
What Claude wrote: POST
Open app/api/pins/route.ts. The checks go one after another, and only what passed through the schema reaches the database:
// app/api/pins/route.ts
export async function POST(request: Request) {
const viewerId = await getCurrentUserId();
if (!viewerId) return Response.json({ error: "Log in." }, { status: 401 });
const body = await request.json().catch(() => null);
if (body === null) return Response.json({ error: "Send the pin as a JSON object." }, { status: 400 });
const result = pinInputSchema.safeParse(body);
if (!result.success) {
const { formErrors, fieldErrors } = z.flattenError(result.error);
return Response.json({ error: formErrors[0] ?? "Fix the fields.", fields: fieldErrors }, { status: 400 });
}
const pin = await createPin(result.data, viewerId);
return Response.json(pin, { status: 201 });
}createPin from lib/pinStore.ts assembles the data from result.data plus ownerId and author from the session. A 400 always carries a reason, and fields says which field to fix, which you know from the forms in lesson 6_1. The route also does not reveal database error details, because nothing unchecked reaches the database. The test most worth reading:
// app/api/pins/route.test.ts
test("ownerId in the body: 400 and nothing reaches the database", async () => {
const res = await post({ ...valid, ownerId: "captain" });
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ error: "Unknown fields: ownerId" });
expect(db.create).not.toHaveBeenCalled();
});The test replaces @/lib/prisma and @/lib/session with vi.mock, as in lesson 8_3, so it runs without a database. The last line checks the most important thing: nothing reached create.
What Claude wrote: one pin and a 404
Open app/api/pins/[id]/route.ts:
// app/api/pins/[id]/route.ts
export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const pin = await getPin(id);
if (!pin) return Response.json({ error: "No such pin." }, { status: 404 });
return Response.json(pin);
}In Next.js 16 params is a Promise, so await is mandatory. Identifiers are strings (p07 or a generated cmw...), so there is no parseInt here. The old version of this lesson turned them into numbers: parseInt("cmw...") gives NaN, and Prisma answers with an exception and a 500. A missing pin is a 404 with a reason, not a 200 with null that the client would trip over.
The list works on the cursor from lesson 13_1, only the cursor is now the id of the first pin of the next page. getPinPage fetches 13 pins: twelve it returns, and the thirteenth points to the next page. The home page calls the same function, so PinFeed noticed nothing.
Captain's review
- Only allowed fields. Search the project for
data: bodyand...body. There is none in the routes, andcreategetsresult.dataand the fields from the session. - Codes with a reason. With
npm run devrunning, send a pin with someone else as the owner:
curl -s -b demo-user=polly -H 'Content-Type: application/json' -d '{"title":"Market Map","src":"/pins/treasure-10.jpg","width":600,"height":700,"dominantColor":"#986848","ownerId":"captain"}' localhost:3000/api/pinsIn our run {"error":"Unknown fields: ownerId","fields":{}} came back with a 400. The same body without ownerId gave 201, without the cookie 401, and GET /api/pins/42 and GET /api/pins/missing gave 404.
3. Parameters. await params in every route with [id] and no parseInt on the identifier.
4. The owner from the session. Search for body.ownerId. A typical agent mistake is taking the owner from the form "because it is more convenient to test".
/security-review as a habit
Write routes are where you always run the security review from lesson 8_7: commit, then /security-review. The review reads only the changes of the branch, compared with the default origin branch. We did not run that command on this branch, so we show no report. You check every finding in Cursor, as in lesson 8_7. Remember too that the demo session from lesson 11_3 is an unsigned cookie that anyone can set for themselves. If the report is silent about it, that does not mean the problem is absent. A review can skip a real but low-impact finding. Real login is shown by the optional lesson about Supabase.
What about GraphQL?
The old version of this lesson promised GraphQL in its title, though it never showed it. To be honest: GraphQL is a different way of building an API. Instead of many addresses there is one, and the client sends a query that names exactly the fields it needs, including those of related objects. The server describes its data with a type schema. It pays off when many different clients, for example a mobile app and a website, need different slices of the same nested data. Then one API replaces a dozen routes tailored to each. The cost is more work: a schema, resolver functions for each field, protection against queries that are too deep, and harder caching, because everything goes through one address. Treasure Map has one client and a few routes, so REST in route handlers is enough.
Next step
When the review passes, ask for a commit "Pin routes according to SPEC.md". The next small step starts from the specification, not from code: "Add pin deletion to SPEC.md: owner only, a stranger gets 404, then build it in a fresh session". In the editor below waits the route tester: send requests with different bodies and cookies, then switch on the agent version with data: body and watch whose pin lands in the table.
Remember: a trade route without a guard is an invitation to pirates, so write the contract down before the caravans set out, and let in only the goods on the list.
Code for this lesson: App.tsx
// Trade routes in miniature: send a request to the pin routes and see the response code
import { useState } from 'react';
interface Pin {
id: string;
title: string;
src: string;
width: number;
height: number;
dominantColor: string;
tags: string[];
ownerId: string;
}
interface ApiResult {
status: number;
body: unknown;
pins: Pin[];
}
const START: Pin[] = [
{ id: 'p07', title: 'Lagoon', src: '/pins/treasure-07.jpg', width: 600, height: 800, dominantColor: '#a8c808', tags: ['lagoon'], ownerId: 'polly' },
{ id: 'p10', title: 'Old map', src: '/pins/treasure-10.jpg', width: 600, height: 700, dominantColor: '#986848', tags: ['map'], ownerId: 'captain' },
];
const ALLOWED = ['title', 'src', 'width', 'height', 'dominantColor', 'tags'];
const COLUMNS = [...ALLOWED, 'id', 'ownerId', 'author', 'createdAt'];
const VALID = '{"title": "Market map", "src": "/pins/treasure-10.jpg", "width": 600, "height": 700, "dominantColor": "#986848"}';
const PRESETS = [
{ label: 'GET one pin', method: 'GET', path: '/api/pins/p07', body: '' },
{ label: 'GET missing pin', method: 'GET', path: '/api/pins/42', body: '' },
{ label: 'POST valid', method: 'POST', path: '/api/pins', body: VALID },
{ label: 'POST with ownerId', method: 'POST', path: '/api/pins', body: VALID.replace('}', ', "ownerId": "captain"}') },
{ label: 'POST with role', method: 'POST', path: '/api/pins', body: VALID.replace('}', ', "role": "admin"}') },
{ label: 'POST bad fields', method: 'POST', path: '/api/pins', body: '{"title": " ", "src": "https://example.com/a.jpg", "width": "600", "height": 700, "dominantColor": "red"}' },
];
function isPositiveInt(value: unknown) {
return Number.isInteger(value) && (value as number) >= 1 && (value as number) <= 10000;
}
// The whitelist, like pinInputSchema from the lesson: anything outside the list is a 400 error
function validate(body: Record<string, unknown>) {
const unknownKeys = Object.keys(body).filter((key) => !ALLOWED.includes(key));
const fields: Record<string, string> = {};
if (typeof body.title !== 'string' || body.title.trim() === '') fields.title = 'Enter a title.';
if (typeof body.src !== 'string' || !body.src.startsWith('/pins/')) fields.src = 'The image must live in /pins/.';
if (!isPositiveInt(body.width)) fields.width = 'Enter a number of pixels.';
if (!isPositiveInt(body.height)) fields.height = 'Enter a number of pixels.';
if (typeof body.dominantColor !== 'string' || !/^#[0-9a-f]{6}$/.test(body.dominantColor)) fields.dominantColor = 'A colour in #rrggbb format.';
return { unknownKeys, fields };
}
function send(method: string, path: string, rawBody: string, session: string, agentVersion: boolean, pins: Pin[]): ApiResult {
if (method === 'GET') {
const id = path.split('/').pop() ?? '';
const pin = pins.find((p) => p.id === id);
return pin ? { status: 200, body: pin, pins } : { status: 404, body: { error: 'No such pin.' }, pins };
}
let body: unknown = null;
try {
body = JSON.parse(rawBody);
} catch {
body = null;
}
if (agentVersion) {
// the agent version: prisma.pin.create({ data: body }), no session and no field list
const data = (body ?? {}) as Record<string, unknown>;
const extra = Object.keys(data).find((key) => !COLUMNS.includes(key));
if (extra) return { status: 500, body: { error: 'Unknown argument ' + extra + '.' }, pins };
const created = { tags: [], author: '', ...data, id: 'new' + (pins.length + 1) } as unknown as Pin;
if (!created.ownerId) return { status: 500, body: { error: 'Argument ownerId is missing.' }, pins };
return { status: 201, body: { id: created.id }, pins: [...pins, created] };
}
if (!session) return { status: 401, body: { error: 'Log in.' }, pins };
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
return { status: 400, body: { error: 'Send the pin as a JSON object.' }, pins };
}
const input = body as Record<string, unknown>;
const { unknownKeys, fields } = validate(input);
if (unknownKeys.length > 0) return { status: 400, body: { error: 'Unknown fields: ' + unknownKeys.join(', ') }, pins };
if (Object.keys(fields).length > 0) return { status: 400, body: { error: 'Fix the fields.', fields }, pins };
const created: Pin = {
id: 'new' + (pins.length + 1),
title: String(input.title).trim(),
src: String(input.src),
width: Number(input.width),
height: Number(input.height),
dominantColor: String(input.dominantColor),
tags: Array.isArray(input.tags) ? input.tags.map(String) : [],
ownerId: session, // the owner comes from the session, never from the body
};
return { status: 201, body: { id: created.id }, pins: [...pins, created] };
}
export default function App() {
const [pins, setPins] = useState<Pin[]>(START);
const [preset, setPreset] = useState(0);
const [rawBody, setRawBody] = useState(PRESETS[0].body);
const [session, setSession] = useState('polly');
const [agentVersion, setAgentVersion] = useState(false);
const [result, setResult] = useState<ApiResult | null>(null);
const request = PRESETS[preset];
function choose(i: number) {
setPreset(i);
setRawBody(PRESETS[i].body);
setResult(null);
}
function submit() {
const next = send(request.method, request.path, rawBody, session, agentVersion, pins);
setPins(next.pins);
setResult(next);
}
return (
<div className="min-h-screen space-y-4 bg-amber-50 p-4 text-zinc-900">
<h1 className="text-xl font-bold">Trade routes: the pin route tester</h1>
<div className="flex flex-wrap gap-2">
{PRESETS.map((p, i) => (
<button key={p.label} type="button" onClick={() => choose(i)} className={i === preset ? 'rounded-full bg-red-600 px-3 py-1 text-sm text-white' : 'rounded-full bg-zinc-200 px-3 py-1 text-sm'}>
{p.label}
</button>
))}
</div>
<p className="font-mono text-sm">
{request.method} {request.path}
</p>
{request.method === 'POST' && (
<label className="block text-sm">
Request body (JSON, you can edit it):
<textarea value={rawBody} onChange={(e) => setRawBody(e.target.value)} rows={4} className="mt-1 w-full rounded border border-zinc-300 bg-white p-2 font-mono text-xs" />
</label>
)}
<div className="flex flex-wrap items-center gap-3 text-sm">
<label className="flex items-center gap-2">
Session cookie:
<select value={session} onChange={(e) => setSession(e.target.value)} className="rounded border border-zinc-300 px-2 py-1">
<option value="polly">polly</option>
<option value="captain">captain</option>
<option value="">none</option>
</select>
</label>
<label className="flex items-center gap-2">
<input type="checkbox" checked={agentVersion} onChange={(e) => setAgentVersion(e.target.checked)} />
The agent version: data: body
</label>
<button type="button" onClick={submit} className="rounded-full bg-red-600 px-4 py-2 font-semibold text-white">
Send
</button>
</div>
{result && (
<div role="status" className={result.status < 300 ? 'rounded-xl bg-emerald-100 p-3 text-sm' : 'rounded-xl bg-red-100 p-3 text-sm'}>
<p className="font-bold">Status {result.status}</p>
<p className="break-all font-mono text-xs">{JSON.stringify(result.body)}</p>
</div>
)}
<table className="w-full rounded-xl bg-white text-left text-sm">
<caption className="text-left font-semibold">The Pin table in the database</caption>
<thead>
<tr>
<th className="p-1">id</th>
<th className="p-1">title</th>
<th className="p-1">ownerId</th>
</tr>
</thead>
<tbody>
{pins.map((pin) => (
<tr key={pin.id} className="border-t border-zinc-200">
<td className="p-1 font-mono">{pin.id}</td>
<td className="p-1">{pin.title}</td>
<td className="p-1">{pin.ownerId}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you add a GET /api/pins/[id] route in the App Router?
2. Where does the handler in app/api/pins/[id]/route.ts get the pin id from?
Hands-on tasks in the game
- Click in order
Click the elements to build the line that answers with a 404 when the pin does not exist:
- Horizontal ordering
Arrange the elements of one line that returns the created pin with status 201:
- Code editor
Create REST API endpoints