JavaScript · Advanced level

Advanced level · Module 2: Node.js for Tools and Servers · Lesson 4 of 4

Validating and Testing the API

Validate every input on the server, return useful errors and test the API automatically.

In this lesson you will

  • Validate request data on the server
  • Write integration tests that start the server and send requests

Key concepts

server-side validationerror response formatintegration testtest server on a random port

The lesson

The server must validate every input, even if the browser already did: required fields, types, ranges and lengths. Reject invalid data with 400 and a JSON body listing the problems.

Use one consistent error format, for example { "error": "validation", "details": [{ "field": "amount", "message": "must be positive" }] }, so clients can show messages next to fields.

Integration tests start the server on a random free port, send real HTTP requests with fetch and assert the status and body. Close the server after the tests.

Step by step

  1. Write a validation function for payment input.
  2. Return 400 with the error format for invalid data.
  3. Write integration tests for valid and invalid requests.
  4. Run all tests with npm test.

Practice activity

Add validation and integration tests to the payments API.

Expected result: Invalid requests return 400 with details, and the integration tests pass.

Check your understanding

  1. Why validate on the server if the browser already validates?

    Show answer

    Anyone can send requests directly to the server, bypassing the browser.

  2. Why start the test server on a random port?

    Show answer

    To avoid conflicts with other running servers or tests.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.