Course contentsShow
← Security
Lesson 1039 of 3,05221. Web Security - API SecurityFree lesson

Input Validation and Output Encoding

Implement comprehensive input validation, output encoding, and content-type enforcement for API requests and responses.

Input Validation and Output Encoding

You'll learn how to defend APIs against injection attacks by properly validating incoming data and safely encoding outgoing responses.

The Core Idea

Every API is a conversation between your server and the outside world. Input validation means checking that incoming data (in requests) matches your expectations before using it. Output encoding means transforming outgoing data (in responses) so it can't be misinterpreted as executable code by the receiver.

Think of it like airport security: validation checks what comes into your system (the X-ray scanner), while encoding protects what leaves it (wrapping sharp objects safely before they travel).

Why Both Matter

Input validation prevents attackers from injecting malicious payloads (SQL, scripts, commands) into your API parameters, headers, or body. You reject anything that doesn't fit expected formats, lengths, character sets, or value ranges.

Output encoding ensures that when you send data back—especially user-generated content—it can't execute as code in the client's context. For JSON APIs, this means escaping special characters and enforcing strict Content-Type headers so browsers don't misinterpret responses.

The Triple Defense

  1. Validate inputs: Use allowlists (permitted patterns), check data types, enforce length limits, and reject unexpected characters
  2. Encode outputs: Escape JSON special characters, use proper Content-Type headers (application/json), and never reflect raw user input
  3. Enforce Content-Type: Set and validate Content-Type headers on both requests and responses to prevent content sniffing attacks

For example, an API accepting a username should reject <script>alert(1)</script> at the door (validation), and if storing/returning it, should encode angle brackets as \u003c and \u003e in JSON responses (encoding).

Key Takeaway:
Input validation blocks bad data from entering your API, output encoding prevents your responses from becoming weapons, and Content-Type enforcement ensures both sides speak the same safe language.