SyntaxStudy
Sign Up
PHP Building JSON API Responses
PHP Intermediate 4 min read

Building JSON API Responses

JSON API Responses

Return consistent JSON from PHP APIs by setting the Content-Type header and encoding an array structure.

Example
<?php
function jsonResponse(mixed $data, int $status = 200): void {
    http_response_code($status);
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode([
        "data"    => $data,
        "status"  => $status,
        "success" => $status < 400,
    ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
    exit;
}

function errorResponse(string $message, int $status = 400): void {
    http_response_code($status);
    header("Content-Type: application/json");
    echo json_encode(["error" => $message, "status" => $status]);
    exit;
}

// Usage
jsonResponse(["users" => $users]);
errorResponse("User not found", 404);
Pro Tip

Exit immediately after outputting JSON in procedural PHP — any whitespace or output after will corrupt the response.