An API receives structured input, but JSON syntax does not make that input trustworthy. A valid JSON document may contain unexpected fields, huge arrays, deeply nested objects, invalid identifiers or values that violate business rules. Validation should happen at the boundary before data is passed into domain operations.
Validate structure and meaning
Check required fields, types, lengths, numeric ranges, formats and allowed enum values. Then apply domain validation such as whether a transition is permitted or whether the referenced object belongs to the current tenant. Keep these two concerns distinct: a syntactically valid value may still be invalid for the current business state.
Limit resource consumption
Set maximum request body size at the web server and application layers. Bound array lengths, string lengths, nesting depth, page size and expensive filter combinations. Reject unsupported content types. Do not assume PHP's decoded JSON structure is small simply because the request was accepted by the server.
Prevent mass assignment
Map only explicitly allowed fields into update commands. Do not pass arbitrary decoded JSON directly into a model or SQL update. Validate sort columns and directions against fixed allow-lists; SQL parameters cannot safely substitute identifiers.
Return actionable errors
Use a consistent error format with stable field names and machine-readable codes. Avoid echoing the submitted secret or raw invalid payload. Ensure validation responses do not disclose whether a sensitive account exists unless that disclosure is intended.
Further reading
- OWASP Input Validation Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
- PHP JSON functions — https://www.php.net/manual/en/ref.json.php