Skip to main content

Input Validation

Input validation is the process of verifying that incoming request data:

  • Exists when required
  • Has the correct data type
  • Falls within allowed ranges or formats
  • Follows business rules
  • Is safe to process (prevents injection and misuse)

In REST APIs, validation occurs before business logic executes, and invalid input should result in client error responses (4xx).

Why Input Validation Is Critical

  • Security: Prevents SQL injection, XSS, header injection, and malformed requests
  • Data Integrity: Ensures only valid data enters your system
  • Predictable API Behavior: Clients get consistent, meaningful errors
  • Easier Debugging: Clear feedback helps consumers fix requests quickly
  • Performance: Rejects bad requests early without costly processing

Types of Input Validation in REST APIs

REST APIs typically validate three major request parts:

  1. Request Body – JSON/XML payload
  2. Query Parameters – URL parameters
  3. Headers – Metadata and authorization info

Request Body Validation

What Is Validated?

  • Required fields
  • Data types
  • Length constraints
  • Formats (email, UUID, date)
  • Nested object structure
  • Business rules

Example API

Create User

POST /users
Content-Type: application/json

Request Body

{
"username": "john_doe",
"email": "john@example.com",
"age": 25
}

Validation Rules

FieldRule
usernameRequired, string, min 3 chars
emailRequired, valid email format
ageOptional, integer ≥ 18

Invalid Request Example

{
"username": "jo",
"email": "invalid-email",
"age": 15
}

Error Response

HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Validation failed",
"details": [
{ "field": "username", "message": "Must be at least 3 characters long" },
{ "field": "email", "message": "Invalid email format" },
{ "field": "age", "message": "Must be 18 or older" }
]
}

Explanation

  • 400 Bad Request → client sent invalid data
  • Error message is descriptive but safe
  • Each field error is returned separately
  • Helps client correct the request easily

Query Parameter Validation

What Is Validated?

  • Presence of required query params
  • Allowed values
  • Data types
  • Range limits
  • Default values

Example API

Get Users with Pagination

GET /users?page=1&limit=20

Validation Rules

ParameterRule
pageOptional, integer ≥ 1 (default = 1)
limitOptional, integer 1–100 (default = 10)

Invalid Request Example

GET /users?page=-2&limit=500

Error Response

HTTP/1.1 400 Bad Request
{
"error": "Invalid query parameters",
"details": [
{ "parameter": "page", "message": "Must be a positive integer" },
{ "parameter": "limit", "message": "Must be between 1 and 100" }
]
}

Explanation

  • Query params are validated before fetching data
  • Prevents expensive or abusive requests
  • Default values help keep API flexible

Header Validation

What Is Validated?

  • Presence of required headers
  • Header format
  • Allowed values
  • Authorization tokens
  • Content-Type and Accept headers

Common Headers to Validate

  • Authorization
  • Content-Type
  • Accept
  • Custom headers (e.g., X-Request-Id)

Example API

POST /orders

Required Headers

HeaderRule
AuthorizationRequired, Bearer token
Content-TypeMust be application/json

Invalid Request Example

POST /orders
Content-Type: text/plain

Error Response

HTTP/1.1 415 Unsupported Media Type
{
"error": "Unsupported Content-Type",
"message": "Expected application/json"
}

Authorization Header Example

Authorization: Bearer abc123

If missing:

HTTP/1.1 401 Unauthorized
{
"error": "Unauthorized",
"message": "Missing or invalid Authorization header"
}

Explanation

  • 415 → wrong content format
  • 401 → authentication problem
  • Headers are validated before parsing body

Validation Order (Best Practice)

  1. Validate headers
  2. Validate query parameters
  3. Validate request body
  4. Apply business rules
  5. Execute core logic

This avoids unnecessary processing and improves performance.

Best Practices for Input Validation

  1. Fail Fast: Reject invalid requests immediately.

  2. Use Standard HTTP Status Codes

    ScenarioStatus
    Invalid input400
    Missing auth401
    Forbidden403
    Unsupported media type415
    Unprocessable entity (semantic error)422
  3. Return Consistent Error Format

    {
    "error": "Validation failed",
    "details": [...]
    }
  4. Don’t Leak Internal Details

    • ❌ Avoid: "SQL syntax error near column age"
    • ✅ Use: "Invalid age value"

Use Schema-Based Validation

  • JSON Schema
  • OpenAPI (Swagger)
  • Framework validators (Spring Validation, Joi, Yup, etc.)

Summary

AreaWhat to ValidateWhy
BodyStructure, types, formatsData integrity
QueryRange, type, allowed valuesPrevent abuse
HeadersAuth, content typeSecurity & correctness

Input validation is the first line of defense in REST API design and is tightly coupled with clear, consistent error handling.

Golden rule

Validation happens at the boundary. Business logic assumes clean data.