How to read JSON from the request body
Short answer
Data sent as JSON does not get into $_POST. Read the request body from php://input:
<?php
// api.php
$data = json_decode(file_get_contents('php://input'), true);
echo $data['name'] ?? 'no name';With validation
Invalid JSON should produce a 400 response:
<?php
// api.php
header('Content-Type: application/json');
try {
$data = json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
http_response_code(400);
exit(json_encode(['error' => 'Invalid JSON']));
}
echo json_encode(['received' => $data]);Functions used in this recipe
- json_decode — Parses a JSON string.
- file_get_contents — Reads a whole file into a string.
- http_response_code — Sets or returns the response status code.