Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

APIs · Lesson 5

Request Validation

Why Validate Requests

Request validation checks that incoming data is complete, correctly shaped, and allowed by business rules. Validation at the API boundary prevents invalid state from reaching services or databases. It also gives clients clear feedback they can act on.

Validating a Command

A validation object can report field-level problems before any write occurs. The example keeps validation deterministic and independent of a web framework.

import java.util.ArrayList;
import java.util.List;

public record CourseRequest(String title, int lessonCount) {
    public List<String> validate() {
        List<String> errors = new ArrayList<>();
        if (title == null || title.isBlank()) errors.add("title is required");
        if (lessonCount < 1 || lessonCount > 100) errors.add("lessonCount must be between 1 and 100");
        return errors;
    }

    public static void main(String[] arguments) {
        System.out.println(new CourseRequest("", 0).validate());
    }
}

Validation Layers

LayerChecksExample
SyntaxShape and typeInteger parses correctly
FieldLocal constraintsTitle is not blank
DomainBusiness rulesCourse limit is valid
PersistenceDatabase constraintsUnique slug

Common Mistake and Practices

Common Mistake: Relying only on client-side validation. A caller can bypass a browser entirely, so the server must validate every request independently.

  • Return all actionable field errors together.
  • Normalize values before validation where appropriate.
  • Avoid leaking database implementation details.
  • Validate authorization as well as shape.
  • Test boundary values and malformed payloads.

Real-World Use Case

A course creation endpoint rejects blank titles and unrealistic lesson counts with a structured 400 response. The UI can highlight both fields in one interaction instead of discovering errors one at a time.

Quiz Check

Quick Knowledge Test

Loading quiz questions...