API input needs structural validation and an authorization check for the requested resource. Correct JSON syntax alone does not make a request safe or permitted.
IN THIS ARTICLE
What you need before you begin
Define the accepted fields, data types, length limits and resource ownership rules. Decide how unknown or invalid fields are reported to the caller.
01 Validate API input before using it in a database
Parse the supported content type with a bounded request size. Validate required fields, allowed values and reasonable lengths before beginning the business operation.
Authenticate the caller and verify access to each referenced resource. A valid account token does not grant access to every record identifier.
Use parameterized database queries or the framework’s appropriate query API. Do not concatenate request values into SQL.
Allow only intended mutable fields. Avoid binding the entire request directly to a sensitive account or permission model.
Return a controlled validation response and record safe diagnostic identifiers. Test invalid, oversized and cross-account requests with harmless data.
02 Example: bind input and enforce account ownership in PHP
This read-only PDO fragment belongs inside an existing authenticated endpoint. $pdo is its configured database connection and $authenticatedAccount comes from trusted authentication middleware. Replace the illustrative table and field names with your reviewed application schema.
$orderId = filter_input(INPUT_GET, 'order_id', FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]);
if ($orderId === false || $orderId === null) {
http_response_code(400);
exit;
}
$query = $pdo->prepare(
'SELECT id, status FROM orders
WHERE id = :id AND account_id = :account_id LIMIT 1'
);
$query->execute([
'id' => $orderId,
'account_id' => (int) $authenticatedAccount->id,
]);
$order = $query->fetch(PDO::FETCH_ASSOC);
The authenticated account restriction belongs in the query alongside the validated order ID. Never obtain that account ID from an untrusted form field. Return a controlled not-found or permission response when no permitted row matches.
Expected result: A valid account can read its own test order. Changing the order ID to another account’s record returns no order, while malformed input is rejected before SQL runs.
Confirm the expected result
Confirm a valid request succeeds and another user’s record cannot be read or changed by substituting an identifier. Verify invalid fields do not partially modify data.
Troubleshoot unexpected results
If a request passes schema validation but changes the wrong account, investigate authorization and resource ownership. Input validation and access control solve different problems.
A common question
Does using an ORM remove the need for validation?
No. An ORM can help construct queries, but business rules, ownership checks, field restrictions and safe handling of raw queries still belong to the application.