Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Building an API

Validation and Input Handling

Validate API input properly: type and range checks, required and unknown fields, trimming, mass assignment, size limits, 400 versus 422 and a tiny reusable schema validator.

Everything a client sends is untrusted: the body, the query string, the headers, even the URL path. Validation is the gate that decides whether input is allowed to reach your business logic and your database. Done well, it prevents bad data, security holes and confusing crashes deep in your code. Done badly, you get Cannot read properties of undefined as a 500 and corrupted records.

This lesson builds a small validator step by step so you understand what libraries (Zod, Joi, Laravel's validator, Pydantic) do for you.

What to validate

For each input field, decide:

  1. Presence: required or optional?
  2. Type: string, integer, boolean, array, object? (JSON gives you numbers, but "5" is a string.)
  3. Format: email, UUID, ISO date, URL.
  4. Range and length: 1 <= quantity <= 100, title up to 200 characters.
  5. Allowed values: an enum such as status in {open, closed}.
  6. Unknown fields: reject, ignore or strip anything not on your list.
  7. Cross-field rules: endDate must be after startDate.

Validate at the edge (as soon as the request arrives), against the contract rather than the database. A database constraint (unique index, NOT NULL) is a second line of defense, never the first.

400, 422 or 409?

As you saw in status codes:

  • 400 Bad Request: the request is malformed. Broken JSON, wrong top-level type, bad query-string syntax.
  • 422 Unprocessable Content: well-formed, but a value breaks a rule. Many APIs also use 400 for this. Pick one and stay consistent.
  • 409 Conflict: the value is valid but conflicts with existing state (duplicate email).
  • 413 for bodies over your size limit, 415 for unsupported Content-Type.

Always return all problems at once, with a path to each field, in the error format you chose.

Mass assignment

A classic vulnerability: you take the whole body and write it to the database.

JavaScript
// Dangerous: the client controls every column
db.users.update(id, request.body);

An attacker sends {"name": "Eve", "role": "admin"} and promotes themselves. Always allow-list the fields a client may set. A schema validator that strips unknown keys (and never contains role for ordinary users) solves this by construction.

A tiny schema validator

The validator below describes each field with a few properties (type, required, min, max, enum, pattern, trim) and returns { value, errors }. The cleaned value contains only allowed fields, already trimmed and typed.

Node.js A reusable schema validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the results: the first input is trimmed and gets status: "draft" by default; the second reports every problem at once; the third shows role rejected instead of silently stored; the last proves that even the shape of the body is checked.

Validating in an endpoint

The validator becomes useful when it sits in front of your handler. This server validates POST /products and answers 422 with the full error list. Broken JSON is a different failure: 400.

Node.js Validation in a POST endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Query parameters and path parameters

Path and query values are always strings. GET /tasks?limit=10 gives you "10", so convert explicitly and validate the result: Number("abc") is NaN, and Number("") is 0. IDs in paths should also be checked against their format before hitting a database, so /users/not-a-uuid yields 400 or 404 quickly and never reaches a query. The earlier filtering lesson used the same allow-list approach.

Sanitise or reject?

  • Normalise harmless differences (trim whitespace, lowercase an email, strip a trailing slash).
  • Reject anything suspicious (control characters, wrong types) instead of "fixing" it silently.
  • Never "sanitize" for security by stripping bad characters and then trusting the result. Defend at the output: parameterised SQL queries and context-aware HTML escaping. Validation reduces garbage; escaping and parameter binding stop injection.

Also set limits everywhere: body size (see the server lesson), string length, array length and nesting depth, otherwise a single request can burn CPU or memory.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client sends {"name": "Eve", "role": "admin"} to a profile update endpoint that has no role field for users. What protects you from mass assignment?

    Only fields you explicitly allow may reach your data layer.
  2. 2. Which status fits a request with broken JSON syntax?

    A syntactically invalid body is a malformed request. Many APIs reserve 422 for well-formed bodies with invalid values.
  3. 3. Why should an API report all validation errors at once?

    One response with the full list saves repeated submit-fail cycles.
  4. 4. What is the value of Number("") in JavaScript, and why does it matter for query parameters?

    Empty strings convert to 0. Validate presence and format before converting.
  5. 5. Which statement about validation and security is correct?

    Validation is one layer. Injection is prevented at the point of use with parameter binding and escaping.

Summary

  • Treat all input as untrusted and validate presence, type, format, range, enum and unknown fields at the edge.
  • Use 400 for malformed requests, 422 (or consistently 400) for rule violations, 409 for conflicts, 413/415 for size and type.
  • Allow-list fields to prevent mass assignment, and return every error with its field path.
  • Path and query values are strings: convert and validate explicitly.
  • Validation complements, but never replaces, parameterised queries and output escaping.

Next: Middleware and Error Handling