APIs with Express · Chapter 13 of 29

Validation

By the end of this chapter you can check every request body against a schema, tidy it first, and answer one 400 that lists every problem. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The Tapri API
  • 5 tasks
  • Express
  • In the all labs plan

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.

Why you need this

The new orders API went live on Monday. By Wednesday Ravi had a printout of strange orders: one for -3 cutting chais, one for a size called venti, one with qty: "two", and one from a partner whose app sent price: 1 along with ten large chais. The server had saved every one.

With what you know, each route would start with its own wall of if statements, each answering only the first problem it finds. And a route that saves { ...req.body } saves whatever a stranger put in it, a price included.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    findProblems: missing fields and wrong types

    Export findProblems(schema, body), which returns an array of every problem as { field, message }, in the schema's order, and [] when there are none. It walks the fields of the schema, not the body. A body of undefined (no JSON sent) counts as {}.

    A field whose value is undefined, null or '' is missing: a required one gives '<field> is required' (for orderSchema and {} that is customer, size and qty, in that order), and a missing optional field, such as note, gives nothing.

    A field that is there must have its rule's type, else '<field> must be <type>': 'a string' for string, 'a whole number' for integer (so '2' and 2.5 fail), 'a number' for number, and 'true or false' for boolean. Each field gives at most one problem.

  2. Task 2

    findProblems: ranges, lengths and allowed values

    Extend findProblems. A field with the right type is then checked against its other rules, in this order, and only the first one it breaks is reported:

    min gives '<field> must be at least <min>' (qty 0: 'qty must be at least 1'), max gives '<field> must be at most <max>' (qty 21: 'qty must be at most 20'), maxLength gives '<field> must be at most <maxLength> characters' (a 61-character note: 'note must be at most 60 characters'), and oneOf gives '<field> must be one of ' followed by the allowed values joined with a comma and a space ('size must be one of cutting, regular, large').

    The edges are allowed: qty 1 and 20, a 40-character customer and a 60-character note are fine. Every field is checked, so one body can give several problems. The check also uses its own schema with rating (integer, required, 1 to 5), comment (string, at most 10 characters) and anonymous (boolean).

  3. Task 3

    sanitize: tidy the input and drop unknown fields

    Export sanitize(schema, body), which returns a new object and leaves body unchanged. It holds only the fields that the schema names and that the body really has as its own properties: price, status, isAdmin and any other field are dropped. Every string value is trimmed, and a field whose rule has lowercase: true is lowercased as well (in orderSchema only size, so 'Blue Tokai' keeps its capitals). Numbers and booleans are copied as they are, and a body of undefined gives {}.

    sanitize(orderSchema, { customer: ' Ravi ', size: ' LARGE ', qty: 2, note: ' extra hot ', price: 0 }) returns { customer: 'Ravi', size: 'large', qty: 2, note: 'extra hot' }.

  4. Task 4

    validate: one middleware for any schema

    Export validate(schema), which returns a middleware. It sanitizes req.body with schema (task 3), then runs findProblems (tasks 1 and 2) on the clean object, so a value of only spaces counts as missing.

    With problems it answers 400 with { error: 'Invalid request', problems } and the handler after it does not run. A request with no body at all gets the 400 too, listing the required fields, for example [{ field: 'rating', message: 'rating is required' }].

    Without problems it replaces req.body with the clean object (trimmed, unknown fields gone) and passes the request on.

  5. Task 5

    POST /orders: only valid orders, at the server's price

    In createApp, put validate(orderSchema) in front of POST /orders. A valid order answers 201 with { id, customer, size, qty, note, price, status: 'placed' }: the clean fields (note only when it was sent), ids 1, 2, 3 in the order orders are saved (a rejected order takes no id), price worked out by the server as prices[size] times qty, and status always placed, whatever the client sent.

    So { customer: ' Anjali ', size: 'Large', qty: 3, price: 1, status: 'delivered' } answers { id: 1, customer: 'Anjali', size: 'large', qty: 3, price: 180, status: 'placed' }. An invalid order answers 400 with { error: 'Invalid request', problems }.

    A body that is not valid JSON answers 400 with { error: 'Body is not valid JSON' }, not Express's HTML page.

What you will learn

  • Types in JavaScript: which checks really tell a whole number from text.
  • A schema: the rules as data, and every problem listed in one 400.
  • Sanitising: trimming, lowercasing and dropping unknown fields before checking.
  • A validation middleware: one guard for any route, plus a 400 for broken JSON.

More in The Tapri API

Build "Validation" yourself

Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.