JSON decoding can fail because a request is malformed, and encoding can fail because a value cannot be represented as valid JSON. If a program ignores the result, those failures may surface later as confusing “empty response” behavior.
Decode with an explicit error path
try {
$payload = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
http_response_code(400);
exit('Invalid JSON request');
}
Check the runtime's PHP version and the function signature before using flags. JSON_THROW_ON_ERROR was introduced in PHP 7.3. The PHP JSON constants reference documents the flag and exception behavior.
In a real endpoint, log a diagnostic identifier and the exception details to a protected log. Do not echo raw request data or internal parser details to a public client. Decide whether the top-level value must be an object or array; valid JSON such as null or a string may still be invalid for your API contract.
Encode responses deliberately
Use the same explicit error strategy when calling json_encode(). A returned JSON string can be empty on failure when exceptions are not enabled; with the flag, handle JsonException and decide how the application should respond. Set the response content type to application/json; charset=utf-8.
Do not turn on every encoding option without understanding its effect. Preserve numeric and string types in the API contract, and avoid silently substituting invalid data unless that fallback is part of the documented behavior.
Test the boundary cases
Try a valid object, malformed JSON, an empty body and valid JSON of the wrong top-level type. For encoding, include values that may contain invalid text or unsupported resources. These cases make the error behavior predictable before clients depend on it.
Related Articles