API Fundamentals Course
API Fundamentals
/
Beginner

Input Validation

Definition

The process of verifying that the data sent by a client to an API exactly matches the expected format, type, and constraints before the API processes it.

Explain Like I'm New

Never trust the client. If your API expects an `age` parameter, and the client sends `"age": "potato"`, your database might crash. Input validation checks the data at the front door and rejects the 'potato' immediately.

Real World Example

Using libraries like Zod or Joi to ensure that an incoming POST request contains a validly formatted email address, a password longer than 8 characters, and an age greater than 18.

Common Use Cases

  • •Data integrity
  • •Preventing SQL injection
  • •Providing helpful errors

Interactive Example

// Validating an API request using the Zod library

import { z } from "zod";

// 1. Define the strict schema rules
const UserSchema = z.object({
  email: z.string().email(),
  age: z.number().min(18),
  password: z.string().min(8)
});

app.post('/api/users', (req, res) => {
  // 2. Test the incoming data against the schema
  const validation = UserSchema.safeParse(req.body);
  
  if (!validation.success) {
    // 3. Return a 400 error with the specific field errors
    return res.status(400).json({
      error: "Invalid Input",
      details: validation.error.format()
    });
  }
  
  // 4. Data is 100% safe and typed. Save to DB.
  db.users.create(validation.data);
});

Interview Questions

basic

  • If your frontend React app already validates that the password is 8 characters long, do you still need to validate it on the backend API?

intermediate

  • What HTTP Status code should an API return if input validation fails?

Flash Cards

Question

Validate on backend?

Click to reveal answer
Answer

ABSOLUTELY YES. Frontend validation is only for User Experience. Hackers can easily bypass the frontend and send raw HTTP requests directly to your API via Postman. The backend must ALWAYS validate everything independently.

Question

Which status code?

Click to reveal answer
Answer

`400 Bad Request`. It is the client's fault for sending improperly formatted data.