API Data Handling
From request validation to data transformation, learn the patterns that make APIs secure, maintainable, and resilient.
Validations and Transformations in API Design
Building APIs that don't break when users send unexpected data isn't optional—it's foundational. Validations and transformations sit at the edge of your system, catching bad input before it corrupts your business logic or database.
This post walks through where these checks belong, why they matter, and how to implement them without overcomplicating your stack.
#The Layered Backend Architecture
Most backend systems follow a three-layer pattern. Understanding where each piece lives helps you place validations correctly.
Repository Layer
- Handles database connections and queries
- Executes inserts, updates, deletes
- Works with any persistent store: PostgreSQL, Redis, MongoDB, etc.
Service Layer
- Contains business logic
- Orchestrates repository calls, external APIs, notifications
- Should remain agnostic of HTTP concerns
Controller Layer
- Accepts HTTP requests and returns HTTP responses
- Handles status codes, headers, response formatting
- Calls service methods and maps results to HTTP responses
The separation exists so HTTP concerns don't leak into business logic. Controllers handle the wire format; services handle what the app actually does.
#Where Validations and Transformations Fit
Validations and transformations happen after route matching, before service logic.
This is the gatekeeper phase. If the input doesn't match expectations, reject it here with a 400 Bad Request. Don't let malformed data reach your service layer.
#Why Validate Early?
Imagine a client sends this payload to create a book:
{ "name": 0 }Your API expects name to be a string with length 5–100. Without validation at the entry point:
- Controller passes
0to the service layer - Service calls repository to insert a new book
- Repository executes:
INSERT INTO books (name) VALUES (0) - PostgreSQL rejects the query: column
nameisTEXT NOT NULL - Database error bubbles up as a
500 Internal Server Error
The client gets a generic server error instead of a clear message: "name must be a string between 5 and 100 characters."
Validate early. Return 400 for client mistakes. Reserve 500 for actual server failures.
#Types of Validations
| Type | Purpose | Example |
|---|---|---|
| Syntactic | Checks structure/format | Email must match user@domain.tld |
| Semantic | Checks logical meaning | Date of birth cannot be in the future |
| Type | Checks data type | age must be a number, not a string |
Syntactic Validation
Validates that a value follows a known pattern.
// Example: email format check
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(input.email)) {
return { error: "Invalid email format" };
}Applies to:
- Email addresses
- Phone numbers (with country codes)
- ISO 8601 dates (
2025-11-05T01:11:00Z)
Semantic Validation
Validates that a value makes sense in context.
// Example: age must be realistic
if (input.age < 0 || input.age > 120) {
return { error: "Age must be between 0 and 120" };
}
// Example: date of birth cannot be future-dated
if (new Date(input.dateOfBirth) > new Date()) {
return { error: "Date of birth cannot be in the future" };
}Type Validation
Ensures the data type matches expectations.
// Example: strict type checks
if (typeof input.name !== "string") {
return { error: "name must be a string" };
}
if (!Array.isArray(input.tags)) {
return { error: "tags must be an array" };
}Don't assume query params are numbers. In HTTP, all query values arrive as strings. Cast them explicitly before validation.
#Transformations: Shaping Input for Your Logic
Validation checks if data is acceptable. Transformation adjusts data to fit your internal expectations.
Common Transformation Cases
Query parameter casting
// Raw query: ?page=2&limit=20
// Received as: { page: "2", limit: "20" } (strings)
// Transform before validation
const parsed = {
page: parseInt(req.query.page, 10),
limit: parseInt(req.query.limit, 10)
};Normalizing strings
// Convert email to lowercase for consistent storage
input.email = input.email.toLowerCase().trim();
// Normalize phone: add country code prefix if missing
if (!input.phone.startsWith("+")) {
input.phone = `+1${input.phone}`;
}Date formatting
// Convert frontend date picker output to ISO string
input.createdAt = new Date(input.createdAt).toISOString();Pair transformations with validations in a single pipeline. Keep all input-handling logic co-located so it's easy to audit and test.
#Practical Validation Examples
Syntactic: Email, Phone, Date
// POST /api/valid/syntactic
{
"email": "test@gmail.com",
"phone": "+1234567890",
"date": "2025-11-05T01:11:00Z"
}Invalid attempts:
"email": "not-an-email"→400: Invalid email format"phone": 1234567890→400: phone must be a string"date": "yesterday"→400: Invalid date format
Semantic: Age and Date Logic
// POST /api/valid/semantic
{
"date_of_birth": "1995-06-12",
"age": 43
}Edge cases:
"date_of_birth": "2026-01-30"→400: Date of birth cannot be in the future"age": 430→400: Age must be ≤ 120
Complex: Conditional and Cross-Field Rules
// POST /api/valid/complex
{
"password": "securepass123",
"password_confirmation": "securepass123",
"married": true,
"partner": "Alex"
}Rules enforced:
- Passwords must match
- Password minimum length: 8 characters
- If
married: true,partnerfield becomes required
Transformation: Normalizing Input
// Client sends:
{
"email": "TeSt@Gmail.COM",
"phone": "234567890",
"date": "2025-11-05"
}
// Server transforms to:
{
"email": "test@gmail.com",
"phone": "+1234567890",
"date": "2025-11-05T00:00:00.000Z"
}The client doesn't need to know the exact format your backend expects. Transform on ingest.
Type Validation: Strict Schema Enforcement
// POST /api/valid/types
{
"string_field": "hello",
"number_field": 42,
"array_field": ["a", "b"],
"boolean_field": false
}Common mistakes:
- Sending
"42"instead of42→400: number_field must be a number - Sending
"[\"a\",\"b\"]"instead of an array →400: array_field must be an array
Validate nested structures too. If array_field contains objects, validate each object's schema.
#Frontend Validation ≠ Backend Validation
This mistake comes up constantly: teams skip backend validation because "the frontend already checks it."
Don't do that.
| Aspect | Frontend Validation | Backend Validation |
|---|---|---|
| Purpose | Improve UX, give instant feedback | Enforce security and data integrity |
| Bypassable | Yes (curl, Postman, scripts) | No (gatekeeper for all clients) |
| Error codes | Inline form messages | HTTP 4xx responses |
| Trust level | Zero trust | Single source of truth |
Your API might serve:
- A React web app with real-time validation
- A mobile app with offline queues
- A third-party integration using raw HTTP
- A cron job posting batch updates
Only backend validation applies to all of them. Frontend checks are a courtesy. Backend checks are mandatory.
#Implementation Tips
- Use a validation library – Zod, Joi, Yup, or your language's equivalent. Don't write regex for emails from scratch.
- Define schemas once – Reuse validation schemas across controllers, tests, and OpenAPI docs.
- Return structured errors – Include field names and constraints so clients can display targeted messages.
- Log validation failures – Track patterns to improve UX or catch abuse attempts.
- Test edge cases – Empty strings, nulls, extremely long inputs, unicode, SQL injection attempts.
Example with Zod:
import { z } from "zod";
const createUserSchema = z.object({
email: z.string().email(),
phone: z.string().regex(/^\+\d{10,15}$/),
age: z.number().min(0).max(120),
name: z.string().min(5).max(100)
});
// In controller
const result = createUserSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.format() });
}
// Proceed with result.data (now typed and clean)Validations and transformations aren't glamorous, but they're what keep your API from becoming a liability. Place them at the entry point. Be strict. Assume every client is either mistaken or malicious.
Frontend validation improves the experience. Backend validation protects the system. Use both, but never rely on the frontend.
When in doubt: reject early, fail loudly, and keep your business logic clean.