Skip to article content
FrontendXLesson 05 / 24

JSON APIs, validation and error handling

Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.

intermediate · about 50 minutes · 2 exercises

  • Predict
  • Debug

What you will be able to do

#
  • Validate request bodies at the boundary before touching business logic.
  • Return a consistent error envelope without leaking internals.
  • Distinguish validation errors from unexpected server faults.

Overview

#

An API is a contract. Validate every input at the edge, reject invalid data with a precise status code, and shape errors so clients can react without parsing prose.

Validate at the boundary

snippet.js
function parseCreateArticle(body) {
  const errors = [];
  if (typeof body.title !== 'string' || body.title.trim().length < 3) {
    errors.push({ field: 'title', message: 'must be at least 3 characters' });
  }
  if (typeof body.body !== 'string' || body.body.length === 0) {
    errors.push({ field: 'body', message: 'is required' });
  }
  return { errors, value: { title: body.title?.trim(), body: body.body } };
}

A consistent error envelope

snippet.json
{ "error": { "code": "validation_error", "message": "Invalid request", "details": [ { "field": "title", "message": "must be at least 3 characters" } ] } }

Use 400 for malformed JSON and 422 for well-formed JSON that fails validation. Reserve 500 for faults you did not anticipate, and log the stack trace server-side instead of returning it.

Central error handling

Wrap handlers so thrown errors become responses in one place. Unknown errors become a generic 500 with a request id the client can quote to support.

Common pitfalls

  • Trusting req.body shape and reading body.title.length on undefined.
  • Echoing the raw database error to the client, which leaks schema details.
  • Returning 200 with { success: false } instead of an error status.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Debug

    This endpoint crashes with a TypeError on some requests. Explain why and fix it.

    starter.javascript
    app.post('/articles', (req, res) => {
      const title = req.body.title.trim();
      res.status(201).json({ title });
    });

    Reveal the reference answer
    reference.javascript
    app.post('/articles', (req, res) => {
      const title = typeof req.body?.title === 'string' ? req.body.title.trim() : '';
      if (title.length < 3) {
        return res.status(422).json({ error: { code: 'validation_error', message: 'Invalid request' } });
      }
      res.status(201).json({ title });
    });

    Authored expected output: Missing or non-string title returns 422 instead of throwing; valid title returns 201.

    Reading .trim() on undefined throws. Guard the type before calling string methods and return a validation error.

  2. Exercise 2Predict

    The client sends well-formed JSON with a numeric title. Which status code should the API return?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.http
    POST /articles
    { "title": 123, "body": "hello" }
    Choose the best answer

Common misconceptions

#
  • Validation belongs in the database: the database is the last line of defense, but the API should reject bad input first with a clear message.
  • A 500 is fine for bad input: bad input is a client error and belongs in the 4xx range.

Follow-up practice

#
  • backend-databases-routing-middleware

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.