Skip to content

An API Query Is an Explicit Contract

The Course
•
18 min study

The decision

A query value can be missing, malformed, or well-formed but unreasonable, and each deserves its own answer. Day 1's pagination clamped a page number past the end. Here the API needs a policy for limit, and there are three choices:

InputChoiceWhy
no limitdefault to 10The caller didn't ask; any documented size is fine.
limit=900clamp to 50The caller wants "as many as possible". Serving 50 is safe, and the response says 50, so the caller can tell.
limit=0, limit=tworeject with 400The caller has a bug. Guessing hides it; a clear error gets it fixed.

Clamping a page past the end, as Day 1 did, is the same reasoning as clamping a big limit: the request makes sense, it only goes further than you allow.

Read, predict, run

lib/contract.js encodes that table. It returns either the limit to use or an error code:

JavaScript
export function run(limit) {
  // Missing: use the documented default.
  if (limit === null) return { limit: 10 };
  const n = Number(limit);
  // Malformed: the caller has a bug, so say so instead of guessing.
  if (!Number.isInteger(n) || n < 1) return { error: "invalid_limit" };
  // Too large: serve the most we allow, and say how many in the response.
  return { limit: Math.min(n, 50) };
}

The handler in app/api/example/route.js turns that into HTTP. It also rejects a repeated limit before the policy runs, because limit=5&limit=6 has no single meaning:

JavaScript
export async function GET(request) {
  const params = new URL(request.url).searchParams;
  if (params.getAll("limit").length > 1) {
    return Response.json({ code: "repeated_limit" }, { status: 400 });
  }
  const result = run(params.get("limit"));
  if (result.error) {
    return Response.json({ code: result.error }, { status: 400 });
  }
  return Response.json(result);
}

Predict what Ask the API answers for limit=900, limit=, and an empty Query box, then try each in the lab.

An API Query Is an Explicit Contract Next.js · 7 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>An API Query Is an Explicit Contract</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [query, setQuery] = useState("limit=5"); const [result, setResult] = useState(""); async function load() { try { const response = await fetch("/api/example?" + query); setResult(response.status + " " + JSON.stringify(await response.json())); } catch { setResult("Request failed"); } } return ( <section> <label> Query{" "} <input value={query} onChange={(event) => setQuery(event.target.value)} /> </label>{" "} <button onClick={load}>Ask the API</button> <p role="status">{result}</p> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } import { run } from "@/lib/contract.js"; export async function GET(request) { const params = new URL(request.url).searchParams; // Repeated keys are a handler decision: reject them before the policy runs. if (params.getAll("limit").length > 1) { return Response.json({ code: "repeated_limit" }, { status: 400 }); } const result = run(params.get("limit")); if (result.error) { return Response.json({ code: result.error }, { status: 400 }); } return Response.json(result); } export function run(limit) { // Missing: use the documented default. if (limit === null) return { limit: 10 }; const n = Number(limit); // Malformed: the caller has a bug, so say so instead of guessing. if (!Number.isInteger(n) || n < 1) return { error: "invalid_limit" }; // Too large: serve the most we allow, and say how many in the response. return { limit: Math.min(n, 50) }; } export const examples = [ [null, { limit: 10 }], ["5", { limit: 5 }], ["900", { limit: 50 }], ["0", { error: "invalid_limit" }], ["two", { error: "invalid_limit" }], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • limit=900 → 200 {"limit":50}: clamped.
  • limit= → 400 {"code":"invalid_limit"}. The key is there with an empty value, so get returns "", not null, and Number("") is 0.
  • An empty box → 200 {"limit":10}: get("limit") is null, the default.

The failure to avoid

Number(limit) || 10 looks like a default but folds two different inputs together: a missing limit and limit=0 both become 10, so a caller with a bug never finds out. And trusting the number directly lets one request ask for a million rows.

Exercise

A deliberate keyword

A mobile client sends limit=all. Decide it explicitly: treat all as the largest page, 50. Every other non-number must still be rejected, and the rest of the table must not change.

Edit lib/contract.js and add the acceptance cases to examples:

  • Input "all" must return {"limit": 50}.
  • Input "lots" must return {"error": "invalid_limit"}.
Your working space Next.js · 7 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import ApiProbe from "./ApiProbe.jsx"; import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>An API Query Is an Explicit Contract</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <ApiProbe /> <Cases /> </main> ); } "use client"; import { useState } from "react"; export default function ApiProbe() { const [query, setQuery] = useState("limit=5"); const [result, setResult] = useState(""); async function load() { try { const response = await fetch("/api/example?" + query); setResult(response.status + " " + JSON.stringify(await response.json())); } catch { setResult("Request failed"); } } return ( <section> <label> Query{" "} <input value={query} onChange={(event) => setQuery(event.target.value)} /> </label>{" "} <button onClick={load}>Ask the API</button> <p role="status">{result}</p> </section> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } import { run } from "@/lib/contract.js"; export async function GET(request) { const params = new URL(request.url).searchParams; // Repeated keys are a handler decision: reject them before the policy runs. if (params.getAll("limit").length > 1) { return Response.json({ code: "repeated_limit" }, { status: 400 }); } const result = run(params.get("limit")); if (result.error) { return Response.json({ code: result.error }, { status: 400 }); } return Response.json(result); } export function run(limit) { // Missing: use the documented default. if (limit === null) return { limit: 10 }; const n = Number(limit); // Malformed: the caller has a bug, so say so instead of guessing. if (!Number.isInteger(n) || n < 1) return { error: "invalid_limit" }; // Too large: serve the most we allow, and say how many in the response. return { limit: Math.min(n, 50) }; } export const examples = [ [null, { limit: 10 }], ["5", { limit: 5 }], ["900", { limit: 50 }], ["0", { error: "invalid_limit" }], ["two", { error: "invalid_limit" }], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

all is a new, named input with its own row in the table, not a looser number check. Making Number accept more would let lots through as well.

Hint 2: a first step

Add one if for limit === "all", next to the missing-limit check and before Number runs. Run the table: "lots" should still be an error.

Show one solution
JavaScript
export function run(limit) {
  if (limit === null) return { limit: 10 };
  if (limit === "all") return { limit: 50 };
  const n = Number(limit);
  if (!Number.isInteger(n) || n < 1) return { error: "invalid_limit" };
  return { limit: Math.min(n, 50) };
}

The keyword is checked before Number, because Number("all") is NaN and would be rejected. Returning 50 rather than "everything" keeps the cap that protects the server, and the caller sees "limit": 50 in the answer. Write the keyword into the API's documentation too: it's part of the contract now.

Explain it without the code

A caller sends limit=50.5. Write what the API answers and which row of the table it falls under.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.