Skip to content

Module 04 · Lesson 4.4

Implementing Endpoints with Validation

45 minUpdated 19 Nov 2026Part of Data Modeling, APIs and Backend · New Project Creation
On this page
  1. What you will learn
  2. Validate every request on the server
  3. Handler, service and SQL: three layers
  4. Cancel: ownership, notice period and one statement
  5. Test the endpoints end to end
  6. Step-by-step workflow
  7. Working with an assistant on endpoints
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

A bank cashier looks at your paying-in slip before counting any money. Is it filled in? Is the amount a number? Is the account real? Only then does the real work start. Your endpoints need the same front desk, because anyone on the internet can send them anything.

In this lesson you build two Tidewell endpoints from the contract: book a slot and cancel a booking. You validate the input, keep the business rules in a service, and write a booking and its history record in one SQL statement. Then you run real requests through the code and see the 201, 400, 404, 409 and 422 answers.

What you will learn

  • Validate input on the server with plain TypeScript checks, and know when a schema library helps.
  • Structure an endpoint as a route handler, a service and parameterised SQL.
  • Write a booking change and its history row in a single statement, so they succeed or fail together.
  • Test endpoints end to end with real Request objects, and read the status codes they return.

Before you start

  • Completed Designing an API Contract, or have a contract of your own.
  • Access to any capable AI assistant.
  • Optional: Node.js and the project from earlier lessons, if you want to run the examples.

Validate every request on the server

Validation means checking that input is well formed before you use it. The browser can check too, and that helps people fix mistakes quickly. But anyone can skip your page and send a request straight to the address. Only the server's checks always run, so they are the ones that count.

Validation answers one question: is this request shaped the way the contract says? It is different from a business rule, which asks whether the request is allowed. The two get different status codes.

QuestionExampleAnswer if it fails
Is it well formed?slotId is missing, or is text.400 invalid-request, with the field named.
Does it exist, and is it yours?No such booking, or it belongs to someone else.404 not-found.
Does it clash with current state?Someone else already holds the slot.409 slot-taken.
Does a rule allow it?The appointment is under 24 hours away.422 notice-period.
Check them in this order. Cheap checks come first, and nothing touches the database until the input is well formed.

Here is the validation for Tidewell. It returns a result that is either 'ok, here is the clean value' or 'not ok, here are the problems', like a pass-or-fail slip.

TypeScriptsrc/features/bookings/validation.ts
// src/features/bookings/validation.ts
export interface FieldError {
  field: string;
  message: string;
}

export type Parsed<T> = { ok: true; value: T } | { ok: false; errors: FieldError[] };

function isPositiveInteger(value: unknown): value is number {
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
}

export function parseCreateBooking(body: unknown): Parsed<{ slotId: number }> {
  if (typeof body !== "object" || body === null || Array.isArray(body)) {
    return { ok: false, errors: [{ field: "body", message: "Send a JSON object." }] };
  }
  const { slotId } = body as Record<string, unknown>;
  if (slotId === undefined) {
    return { ok: false, errors: [{ field: "slotId", message: "slotId is required." }] };
  }
  if (!isPositiveInteger(slotId)) {
    return { ok: false, errors: [{ field: "slotId", message: "slotId must be a whole number above zero." }] };
  }
  return { ok: true, value: { slotId } };
}

// Path parameters always arrive as text, so check the text before using it.
export function parseBookingId(text: string): Parsed<number> {
  const id = /^[0-9]{1,9}$/.test(text) ? Number(text) : 0;
  if (id === 0) {
    return { ok: false, errors: [{ field: "bookingId", message: "bookingId must be a whole number above zero." }] };
  }
  return { ok: true, value: id };
}
  • The input arrives as unknown, which means 'could be anything'. The code proves what it is before using it.
  • isPositiveInteger accepts only real whole numbers above zero. The text "2" fails, and so do 0, 1.5 and null.
  • parseCreateBooking rejects a body that is not an object, then a missing slotId, then a bad slotId. Each answer names the field and says what to fix.
  • parseBookingId is for the address. Path parameters always arrive as text, so it checks the text for one to nine digits first. A short limit also keeps huge numbers out of the database.
  • Extra fields in the body are ignored. Only the fields the contract names are read.

The same rule with a schema library

A schema library, such as Zod, lets you describe the shape once and gets the checks and the TypeScript type from it. It saves effort when you have many fields. Plain checks are easier to follow while you are learning, and they need no extra package.

TypeScriptvalidation-zod.ts
import { z } from "zod";

// The same rule as parseCreateBooking, written with a schema library.
export const createBookingSchema = z.object({
  slotId: z.number().int().positive(),
});

export type CreateBookingInput = z.infer<typeof createBookingSchema>;
Zod and the hand-written check agreeCaptured from a real run
{"slotId":2} | zod: ok | by hand: ok
{"slotId":"2"} | zod: Expected number, received string | by hand: slotId must be a whole number above zero.
{} | zod: Required | by hand: slotId is required.

Both accept the same body and reject the same two. Their messages differ, so Tidewell's own wording is kept for the response. If you use a library, map its issues into the problem format. Check the Zod docs (opens in a new tab) for the version you install.

Handler, service and SQL: three layers

Split the work in three. Think of a hotel. The route handler is the reception desk: it takes the request, checks it and hands over the key or an apology. The service is the back office, where the rules live. The SQL is the filing room, which stores and finds the records.

The route file in Next.js is only a few lines: it calls the handler with the real database and the real clock. The handler below uses only the web-standard Request and Response, so exactly the same code runs in a plain Node test. Everything it needs, the database, the clock and the patient, is passed in.

TypeScriptsrc/app/api/bookings/handlers.ts (create)
// src/app/api/bookings/handlers.ts: parse, validate, call the service, map the result.
import type { Db } from "./db";
import { errorResponse, invalidRequest } from "./problem";
import { cancelBooking, createBooking } from "./service";
import { parseBookingId, parseCreateBooking } from "./validation";

export interface Deps {
  db: Db;
  now: () => Date;
  patientId: number; // TEMPORARY: comes from getCurrentPatientId() until sign-in exists (Module 6)
  log: (line: string) => void;
  newRef: () => string;
}

async function readJson(request: Request): Promise<unknown> {
  try {
    return await request.json();
  } catch {
    throw invalidRequest([{ field: "body", message: "The body must be valid JSON." }]);
  }
}

export async function handleCreateBooking(request: Request, deps: Deps): Promise<Response> {
  try {
    const parsed = parseCreateBooking(await readJson(request));
    if (!parsed.ok) throw invalidRequest(parsed.errors);
    const ctx = { db: deps.db, patientId: deps.patientId, now: deps.now() };
    return Response.json(await createBooking(ctx, parsed.value.slotId), { status: 201 });
  } catch (error) {
    return errorResponse(error, { route: "POST /api/bookings", log: deps.log, newRef: deps.newRef });
  }
}
  • Deps lists what the handler is given. patientId is a marked stand-in until sign-in exists in Module 6.
  • readJson turns unreadable JSON into a 400 problem instead of a crash.
  • The handler parses, validates, builds a context and calls the service. A good result becomes Response.json(..., { status: 201 }).
  • Anything thrown goes to one place, errorResponse, which you meet in the next lesson. The handler never builds an error response by hand.

The service holds the booking logic. It knows nothing about Request or Response, which makes it easy to test and to reuse from a staff page later.

TypeScriptsrc/features/bookings/service.ts (createBooking)
// bigint columns come back as text from node-postgres, so cast ids to int in the query.
const VIEW_COLUMNS = `b.id::int AS booking_id, b.slot_id::int AS slot_id, c.display_name AS clinician_name,
  s.starts_at, s.ends_at, b.status`;

function isOneLiveBookingViolation(error: unknown): boolean {
  const e = error as { code?: string; constraint?: string };
  return e?.code === "23505" && e.constraint === "one_live_booking_per_slot";
}

export async function createBooking(ctx: BookingContext, slotId: number): Promise<BookingView> {
  const sql = `
    WITH new_booking AS (
      INSERT INTO bookings (slot_id, patient_id, status, created_at)
      SELECT s.id, $2, 'booked', $3 FROM slots s WHERE s.id = $1 AND s.starts_at > $3
      RETURNING id, slot_id, status
    ), change AS (
      INSERT INTO booking_changes (booking_id, action, actor_role, actor_id, to_slot_id, changed_at)
      SELECT id, 'created', 'patient', $2, slot_id, $3 FROM new_booking
    )
    SELECT ${VIEW_COLUMNS}
    FROM new_booking b JOIN slots s ON s.id = b.slot_id JOIN clinicians c ON c.id = s.clinician_id`;
  try {
    const { rows } = await ctx.db.query<BookingRow>(sql, [slotId, ctx.patientId, ctx.now.toISOString()]);
    if (rows.length === 0) throw notFound(); // no such slot, or it has already started
    return toView(rows[0]);
  } catch (error) {
    if (isOneLiveBookingViolation(error)) throw slotTaken();
    throw error;
  }
}

One statement, two writes

FR-05 says every change records who and when. So creating a booking must write two rows: the booking and its change record. If only one of them were saved, the history would lie. The usual tool for this is a transaction, a group of steps that either all happen or none do, like a bank transfer.

PostgreSQL offers a simpler tool here. A single statement is always all-or-nothing. The statement above uses WITH ... RETURNING. The first part inserts the booking and hands back its id. The second part inserts the change row using that id. The last part reads the result. If any part fails, nothing is saved.

  • WHERE s.id = $1 AND s.starts_at > $3 inserts nothing if the slot does not exist or has started. Zero rows back means 404.
  • The partial unique index from migration 002 refuses a second live booking. PostgreSQL reports error code 23505 for the index, and the code turns it into a 409 slot-taken problem.
  • The check constraint === "one_live_booking_per_slot" matters. A unique violation on some other index would be a different problem and must not be called 'slot taken'.
  • b.id::int turns the id into a number. The node-postgres package returns bigint columns as text unless you cast them.

Cancel: ownership, notice period and one statement

The notice-period rule is a business decision that the practice manager confirmed after Module 1: a patient may move or cancel online only if the appointment starts at least 24 hours from now, and exactly 24 hours counts as allowed. It lives in one small file, away from the endpoint code, with a comment that points to the decision.

TypeScriptsrc/features/bookings/rules.ts
// src/features/bookings/rules.ts
// Decision: practice manager, 2026-11-19. Online changes are allowed only if the
// appointment starts at least 24 hours from now; exactly 24 hours is allowed.
export const NOTICE_PERIOD_HOURS = 24;

export function isInsideNoticePeriod(startsAt: Date, now: Date): boolean {
  const earliestAllowed = now.getTime() + NOTICE_PERIOD_HOURS * 60 * 60 * 1000;
  return startsAt.getTime() < earliestAllowed;
}

The comparison uses 'less than', so a start time exactly 24 hours away is not inside the notice period. The cancel service checks ownership first, then the rule, and only then writes.

TypeScriptsrc/features/bookings/service.ts (cancelBooking)
export async function cancelBooking(ctx: BookingContext, bookingId: number): Promise<BookingView> {
  // Ownership check: the patient id is part of the lookup, so other people's bookings are "not found".
  const found = await ctx.db.query<BookingRow>(
    `SELECT ${VIEW_COLUMNS}
     FROM bookings b JOIN slots s ON s.id = b.slot_id JOIN clinicians c ON c.id = s.clinician_id
     WHERE b.id = $1 AND b.patient_id = $2`,
    [bookingId, ctx.patientId],
  );
  if (found.rows.length === 0) throw notFound();
  const current = found.rows[0];
  if (current.status === "cancelled") return toView(current); // cancelling twice changes nothing
  if (isInsideNoticePeriod(current.starts_at, ctx.now)) throw noticePeriod();

  const { rows } = await ctx.db.query<{ id: number }>(
    `WITH cancelled AS (
       UPDATE bookings SET status = 'cancelled', cancelled_at = $3
       WHERE id = $1 AND patient_id = $2 AND status = 'booked'
       RETURNING id, slot_id
     )
     INSERT INTO booking_changes (booking_id, action, actor_role, actor_id, from_slot_id, changed_at)
     SELECT id, 'cancelled', 'patient', $2, slot_id, $3 FROM cancelled
     RETURNING booking_id AS id`,
    [bookingId, ctx.patientId, ctx.now.toISOString()],
  );
  if (rows.length === 0) throw notFound(); // someone else changed it between our two queries
  return toView({ ...current, status: "cancelled" });
}
  • WHERE b.id = $1 AND b.patient_id = $2 is the ownership check. Someone else's booking looks exactly like a missing one, so the answer is the same 404.
  • A booking that is already cancelled is returned as it is. Pressing the button twice does no harm.
  • The notice period is checked before any write. A refusal leaves the booking untouched (FR-02.2).
  • The update and its change row are again one WITH ... RETURNING statement. The status = 'booked' condition makes sure a booking cancelled a moment earlier by someone else is not cancelled twice.

Test the endpoints end to end

A good endpoint test sends a real Request into the handler and looks at the real Response. Here the database is PGlite, a real PostgreSQL engine that runs inside Node, with the three migrations applied and made-up data. The clock is fixed at 30 November 2026, 10:00 UTC, so every run gives the same answers.

TypeScripttest-api.ts (setup)
const db = await freshDatabase();
const logs: string[] = [];
const as = (patientId: number): Deps => ({ db, now: () => NOW, patientId, log: (l) => logs.push(l), newRef: () => "ref-0001" });

const post = (body: string) =>
  new Request("http://localhost/api/bookings", { method: "POST", headers: { "Content-Type": "application/json" }, body });

async function show(label: string, response: Response) {
  console.log(`${label}\n  ${response.status} ${response.headers.get("content-type")}\n  ${await response.text()}`);
}

The slots on 1 December start at 09:00 (23 hours away), 10:00 (exactly 24 hours away) and 11:00. Now the seven calls, one for each case you care about.

TypeScripttest-api.ts (the calls)
await show("1. Patient A books slot 2", await handleCreateBooking(post('{"slotId":2}'), as(1)));
await show("2. slotId sent as text", await handleCreateBooking(post('{"slotId":"2"}'), as(1)));
await show("3. Patient B books the same slot", await handleCreateBooking(post('{"slotId":2}'), as(2)));
await show("4. Patient B cancels booking 1 (Patient A's)", await handleCancelBooking("1", as(2)));
await show("5a. Patient A books slot 1 (23 hours away)", await handleCreateBooking(post('{"slotId":1}'), as(1)));
await show("5b. Patient A cancels booking 3", await handleCancelBooking("3", as(1)));
await show("6. Patient A cancels booking 1 (exactly 24 hours away)", await handleCancelBooking("1", as(1)));

201: a booking is created

Patient A books slot 2Captured from a real run
1. Patient A books slot 2
  201 application/json
  {"bookingId":1,"slotId":2,"clinicianName":"Clinician A","startsAt":"2026-12-01T10:00:00Z","endsAt":"2026-12-01T10:45:00Z","status":"booked"}

400: the input is malformed

slotId sent as textCaptured from a real run
2. slotId sent as text
  400 application/problem+json
  {"type":"https://tidewell.example/problems/invalid-request","title":"Invalid request","status":400,"detail":"The request has problems. See errors for details.","errors":[{"field":"slotId","message":"slotId must be a whole number above zero."}]}

409: the slot is already held

Patient B tries the same slotCaptured from a real run
3. Patient B books the same slot
  409 application/problem+json
  {"type":"https://tidewell.example/problems/slot-taken","title":"Slot already taken","status":409,"detail":"Someone else has just booked this slot. Please choose another time."}

404: not found, or not yours

Patient B tries to cancel Patient A's bookingCaptured from a real run
4. Patient B cancels booking 1 (Patient A's)
  404 application/problem+json
  {"type":"https://tidewell.example/problems/not-found","title":"Not found","status":404,"detail":"We could not find that."}

422: too close to the appointment

Patient A books the 09:00 slot, then tries to cancel itCaptured from a real run
5a. Patient A books slot 1 (23 hours away)
  201 application/json
  {"bookingId":3,"slotId":1,"clinicianName":"Clinician A","startsAt":"2026-12-01T09:00:00Z","endsAt":"2026-12-01T09:45:00Z","status":"booked"}
5b. Patient A cancels booking 3
  422 application/problem+json
  {"type":"https://tidewell.example/problems/notice-period","title":"Too close to the appointment time","status":422,"detail":"Online changes need at least 24 hours of notice. Please phone the clinic on 01632 960 123, Monday to Friday, 8:00 to 18:00."}

200: exactly 24 hours is allowed

Patient A cancels the 10:00 bookingCaptured from a real run
6. Patient A cancels booking 1 (exactly 24 hours away)
  200 application/json
  {"bookingId":1,"slotId":2,"clinicianName":"Clinician A","startsAt":"2026-12-01T10:00:00Z","endsAt":"2026-12-01T10:45:00Z","status":"cancelled"}

That is every status in the contract except 500, which you meet in the next lesson. These calls also cover the three acceptance scenarios for FR-02: the 200 is FR-02.1, the 422 is FR-02.2 and the 404 is FR-02.3.

The history table

Rows in booking_changes after the callsCaptured from a real run
booking_changes: [{"booking_id":1,"action":"created","actor_role":"patient","actor_id":1,"from_slot_id":null,"to_slot_id":2},{"booking_id":3,"action":"created","actor_role":"patient","actor_id":1,"from_slot_id":null,"to_slot_id":1},{"booking_id":1,"action":"cancelled","actor_role":"patient","actor_id":1,"from_slot_id":2,"to_slot_id":null}]

There are three rows: two creations and one cancellation. The refused 409 and 422 attempts left no row, because the single statement never completed, or never ran. Look at the booking ids too. The second booking got id 3, not 2. The failed 409 insert used up number 2. Gaps like this are normal, because the database never hands out the same id twice.

The test calls the requests one after another. The protection against two people acting at the same moment comes from the database rule, which PostgreSQL applies to every write, however they arrive.

Step-by-step workflow

  1. Step 1: Pick one endpoint and its scenarios

    Take the contract entry and the acceptance scenarios for it. Build one endpoint at a time.

    What you should see: A list of cases, each with the status code you expect.

  2. Step 2: Ask for a plan before code

    Use the prompt card. Read the plan: files, rules, statuses and tests. Cut anything that no requirement asks for.

    What you should see: A reviewed plan.

  3. Step 3: Write the validation first

    Write the check for the input and test it with good and bad bodies. Nothing else runs until this passes.

    What you should see: Every malformed input gives a 400 that names the field.

  4. Step 4: Write the service

    Put the rules in the service: ownership, state and the business rule. Use parameters in every query.

    What you should see: A service with no Request or Response in it.

  5. Step 5: Wire the handler

    Parse, validate, call the service and return the response. Send every error through the one mapper.

    What you should see: A handler of about ten lines.

  6. Step 6: Run it end to end

    Test each scenario with a real Request, against a throwaway database. Compare the statuses with the contract.

    What you should see: One test per status code in the contract.

One request, three layers
  1. Request

    From any caller

  2. Validate

    400 if malformed

  3. Service rules

    404, 422

  4. SQL statement

    409 on a clash

  5. Response

    Success or problem

Each layer does one job, and a failure at any layer becomes a problem response.

Working with an assistant on endpoints

TaskAssistant's partYour part
Plan the endpointLists files, rules and tests from the contract.Cut steps that no requirement asks for.
Write validationDrafts the checks and some test inputs.Check each limit against the contract and add bad inputs.
Write SQLDrafts the statements with parameters.Read every query. Check ownership, parameters and the unique rule.
Write testsProposes cases for each status.Make sure each test can fail, and map each to a scenario.
Decide rulesNothing. It guesses.Confirm the notice period and the meaning of 404 with the owner.

Conclusion and your next step

A good endpoint is small. The handler validates and answers, the service holds the rules and the SQL does one safe, all-or-nothing write. The server checks every input, whatever the browser did, and every status code in the contract has a test that produces it.

Your next step: build one write endpoint for your capstone in three layers, with a test for each status code in its contract. Then continue to Error Handling and Backend Review, where you make failures predictable and review the code against your criteria.

For more on checking code from an assistant, read AI Code Review: Catching Bugs Before They Ship or use the AI-Generated Code Review Checklist.

Reusable prompt

Endpoint implementation plan

Asks for a plan for one endpoint, with files, validation, statuses and tests mapped to scenarios, before any code is written.

You are helping me plan one API endpoint. Do not write code yet. Do not add behaviour that is not in the requirements or the contract.

Fictional clinic: Tidewell Physiotherapy. Stack: TypeScript, Next.js App Router, PostgreSQL with plain SQL. Database access goes through a small interface with a query method and parameters ($1, $2). Never join user input into SQL.

Endpoint: POST /api/bookings/{bookingId}/cancel (FR-02). Success: 200 with the booking and status "cancelled".
Rules (confirmed by the practice manager): a patient may cancel online only if the appointment starts at least 24 hours from now. Exactly 24 hours is allowed. A patient must not learn whether another patient's booking exists. Every change records who and when (FR-05).
Errors use problem details: 400 invalid-request, 404 not-found, 422 notice-period, 500 internal-error.

Scenarios:
FR-02.1 Cancel outside the notice period: booking cancelled, slot free.
FR-02.2 Cancel inside the notice period: booking unchanged, patient told to phone the clinic.
FR-02.3 Cancel someone else's booking: unchanged, existence not revealed.

Tasks:
1. Plan the layers: route handler, validation, service, SQL. Say what each one does.
2. List the validation rules and the status code for each failure.
3. Describe the SQL in words: the ownership check and how the change and its history row are written together.
4. List one test for each scenario and status code, with the expected result.
5. List anything you would add that is not in the requirements, under "Not requested".
Show the reusable template

Replace each {{placeholder}} with your own details.

You are helping me plan one API endpoint. Do not write code yet. Do not add behaviour that is not in the requirements or the contract.

Context: {{organisation_and_stack}}. Database access goes through a small interface with a query method and parameters ($1, $2). Never join user input into SQL.

Endpoint: {{method_and_path}} ({{requirement_id}}). Success: {{success_response}}.
Rules (confirmed): {{confirmed_rules}}
Errors use {{error_format}}: {{error_codes}}.

Scenarios:
{{acceptance_scenarios}}

Tasks:
1. Plan the layers: route handler, validation, service, SQL. Say what each one does.
2. List the validation rules and the status code for each failure.
3. Describe the SQL in words: the ownership check and how the change and its history row are written together.
4. List one test for each scenario and status code, with the expected result.
5. List anything you would add that is not in the requirements, under "Not requested".

Expected output and limitations

A short plan in five parts: the job of each layer, validation rules with statuses, the SQL described in words, one test per scenario and status, and a separate 'Not requested' list.

Sample responseIllustrative — your output will differ
1. Layers
   Handler: read bookingId from the address, validate, call the service, return 200 or a problem.
   Service: look up the booking for this patient, apply the notice rule, write the change.
   SQL: one lookup with patient_id in the WHERE clause; one statement for update plus history.

2. Validation
   bookingId must be digits, one to nine of them. Otherwise 400 invalid-request with field bookingId.

4. Tests
   FR-02.1: booking 25 hours away -> 200, status cancelled, one new history row.
   FR-02.2: booking 23 hours away -> 422, unchanged, no history row.
   FR-02.3: another patient's booking -> 404, unchanged.

5. Not requested
   A bulk-cancel endpoint. An email to the patient (comes in Module 6).

Limitations to keep in mind

  • A plan reads well even when it is wrong. Check each line against your contract and scenarios.
  • It may invent business rules, such as a cancellation fee. Anything not in your notes belongs under 'Not requested'.
  • It cannot run anything. Only your tests show whether the finished code behaves as the plan says.

Common errors and how to fix them

The server trusts the browser's checks.

Why it happens: The form already refuses bad input, so a server check seemed redundant.

Fix: Validate every field on the server, using the contract as the list. Treat all input as untrusted.

Someone else's booking gives a different answer from a missing one.

Why it happens: The lookup used only the booking id, and a separate permission check followed.

Fix: Put the patient id in the lookup, so both cases return the same 404.

A booking is saved but its history row is missing.

Why it happens: Two separate statements, and the second one failed or never ran.

Fix: Write both in one WITH ... RETURNING statement, or wrap them in one transaction.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Validate a Ferngate parts-used request

Write the validation for a Ferngate endpoint that records a part taken for a job: the body has partId and quantity, and the job id is in the address. Write the plain TypeScript check, list the cases and the status each one gives, and test it with at least five inputs.

You will need

  • Body: { partId, quantity }. Address: /api/jobs/{jobId}/parts-used.
  • Note: quantity is a whole number above zero. The owner has not set a maximum.
  • Note: the out-of-stock question is still undecided. Validation must not try to answer it.

Acceptance criteria

Your work is done when every one of these is true.

Hints (2)
  • Test the quantity 0 and the quantity 1.5 separately. They fail for different reasons.
  • A jobId in the address is text. Check it before you turn it into a number.
Show a model answer

A strong answer mirrors parseCreateBooking: an object check, then one check per field using a helper such as isPositiveInteger, then a clean value. Tests include a good body, a missing partId, partId as text, quantity 0, quantity 2.5 and a jobId such as 'abc'. Each bad one gives 400 and names the field. The maximum quantity stays as a recorded open decision, because inventing 100 would quietly turn a guess into a rule. Whether the part is in stock is not validation at all, since it depends on data and on an owner's decision. It belongs in the service, after the request is known to be well formed.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.The booking form already checks that a slot is chosen. Does the server still need to validate slotId?
    Show the answer and explanation

    Answer: B. Requests can come from any program, and the form is only one of them. The browser check is tempting to rely on because it works for ordinary users, but it protects nobody from a request that skips the page.

  2. 2.Why does Tidewell write the booking and its change row in one SQL statement?
    Show the answer and explanation

    Answer: B. A single statement is all-or-nothing, so no booking can exist without its history row. Speed is a tempting benefit, but it is not the reason. PostgreSQL runs many statements, and a transaction is the general way to group them.

  3. 3.A booking starts exactly 24 hours from now, and the rule says at least 24 hours of notice. What happens?
    Show the answer and explanation

    Answer: B. The practice manager confirmed that exactly 24 hours is allowed, and the code compares with 'less than'. Refusing at the limit is tempting because 'limit reached' sounds like a stop sign. And the last option is the danger of leaving the boundary unstated.

Frequently asked questions

What is server-side validation?

It is checking incoming data on the server before using it. The browser can check too, but only to help people. A request can skip the browser entirely, so the server must always check for itself.

Should I use Zod, or write validation by hand?

Both work. Hand-written checks need no extra package and are easy to read for a few fields. A schema library such as Zod is helpful once you have many fields, because it gives you the checks and the TypeScript type from one description.

How do I stop SQL injection?

Pass user input as parameters, written as $1, $2 and so on, and never join it into the SQL text. The database then treats the values as plain data and never as commands. This is the main defence, and it costs nothing.

Do I always need a transaction when I save two things?

You need some way to make both writes succeed or fail together. A transaction is the general tool. When both writes can be one statement, such as a WITH ... RETURNING query in PostgreSQL, that single statement does the job on its own.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.