PHP JSON Response API Basics
Ringkasan
Untuk API, PHP mengembalikan JSON: set header Content-Type: application/json, encode array via json_encode, dan atur status code.
Konsep Dasar
header('Content-Type: application/json').echo json_encode($data, JSON_UNESCAPED_UNICODE).http_response_code(201)untuk Created,400bad request, dll.- Baca body request:
json_decode(file_get_contents('php://input'), true).
Cara Kerja / Struktur
header('Content-Type: application/json');
$data = ['id' => 1, 'nama' => 'Budi'];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
// request
$input = json_decode(file_get_contents('php://input'), true);Catatan Implementasi
JSON_UNESCAPED_UNICODEagar UTF-8 tidak di-escape.- Kirim
exit/returnsetelah echo JSON biar tidak ada output tambahan. - API lengkap (routing, auth) dibahas terpisah.
Kesalahan Umum
- Output lain (spasi/HTML) sebelum
json_encode→ JSON rusak. - Lupa
truedijson_decode→ returns stdClass.
Glosarium
- php://input: stream raw request body.
- HTTP status: kode hasil respon (200, 201, 400, 500).