Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท API Security

Input Validation and Mass Assignment

Validate every API request: schemas, types and limits, safe error responses, allowlists against mass assignment, and parameterized queries against injection.

Every byte that arrives in a request is controlled by the caller: the URL, the query string, headers, the JSON body. Treat all of it as hostile until proven otherwise. Most injection, crash and data-corruption bugs share one root: the server assumed the input had the shape the documentation promised.

Validation has two goals. It protects your system (no oversized bodies, no SQL in a name field, no field that should not be writable), and it helps honest clients with precise error messages. This lesson covers schema validation, mass assignment, injection and size limits, with code you can run.

Validate at the door

Shape Required fields and types.
Limits Length, range, array size.
Allowlist Accept known fields only.
Reject early 400 or 422 before any work.

Validate on the server even if the client validates too.

1 / 2

Validate with a schema

Describe what a valid request looks like and reject everything else. In production use a schema library (Zod, Joi, Ajv with JSON Schema, or your framework's validator). The principle is easy to see in a small hand-written version.

Choose status codes with care: 400 Bad Request for malformed syntax (invalid JSON), and 422 Unprocessable Content when the JSON is well-formed but the values break your rules. Return all errors at once, each with the field name, so the client can fix them in one go.

Node.js A tiny 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.

Good error responses describe what is wrong without revealing internals. Never echo stack traces, SQL or file paths. The standard format for API errors is Problem Details (application/problem+json, RFC 9457): a JSON object with type, title, status, detail and extension members such as errors.

Mass assignment

Mass assignment (also called over-posting) happens when code copies a whole request body into a database record. The client then sets fields you never meant to expose: role, isAdmin, balance, ownerId, emailVerified.

JavaScript
// DANGEROUS: whatever the client sends is saved
Object.assign(user, req.body);
await db.users.update(user);

A client who sends {"name": "Ana", "role": "admin"} just promoted themselves. The fix is an allowlist of the fields a given endpoint may write. Pick fields explicitly, instead of removing a blocklist of known-bad names (you will forget one).

Node.js Mass assignment and the allowlist fix

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.

Use separate request and response shapes (often called DTOs): one list of writable fields per endpoint, and one list of readable fields per response. The same idea protects against leaking passwordHash in responses.

Injection

Injection happens when input is pasted into a command that is then interpreted: SQL, shell, LDAP, NoSQL operators, template engines, file paths. The cure is always to keep data and code separate.

  • SQL: use parameterized queries (prepared statements). Never build SQL with string concatenation or template strings.
  • Shell: avoid shells; pass arguments as an array (execFile), not one string.
  • Paths: resolve the path and check that it stays inside the allowed directory (../../etc/passwd).
  • NoSQL: reject objects where a string is expected, otherwise {"password": {"$ne": null}} can bypass a login.

This demo uses Node's built-in SQLite. The unsafe query turns a "name" into extra SQL.

Node.js SQL injection and parameters

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.

The unsafe version returns every row because the single quote ended the string and OR '1'='1' is always true. With a placeholder, the whole text is just a name nobody has.

Limits and content checks

  • Body size: cap request bodies (for example 100 KB for JSON) and answer 413 Content Too Large.
  • Content-Type: require application/json for JSON endpoints and answer 415 Unsupported Media Type otherwise.
  • Nesting and arrays: limit array length and depth, so a payload cannot be cheap to send and expensive to process.
  • Numbers and dates: validate ranges and formats (ISO 8601). Treat IDs in paths as untrusted too.
  • Uploads: check size, real file type, and never trust the file name.
  • Query parameters: whitelist sort fields and page sizes; never insert a client-provided column name into SQL.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A JSON body parses fine but the age field is -4. Which status fits best?

    The syntax is valid but the content breaks the rules, which is 422. Invalid JSON itself would be 400.
  2. 2. What is mass assignment?

    Over-posting lets a client set role, balance or ownership fields. Use allowlists per endpoint.
  3. 3. Which is the correct defence against SQL injection?

    Parameters keep input as data, so it can never change the structure of the query.
  4. 4. Why prefer an allowlist of writable fields over a blocklist?

    New sensitive fields are protected automatically with an allowlist, while a blocklist needs updating every time.
  5. 5. Which status is right when a request body is far larger than allowed?

    413 tells the client the payload exceeds the server's limit, and you can reject it before reading it all.

Summary

  • Validate type, shape, length and range on the server for every input, and reject unknown fields.
  • Use 400 for malformed syntax, 422 for rule violations, 413 for oversized bodies and 415 for the wrong content type; report all field errors at once.
  • Stop mass assignment with a per-endpoint allowlist, and use separate request and response shapes.
  • Prevent injection by keeping data apart from code: parameterized SQL, argument arrays, path checks.
  • Never reveal stack traces or internals in error responses.

Next: Rate Limiting and Abuse Protection