PHPPHP17 min read

Standard API Responses (Consistent Success and Errors)

Make your API predictable by always returning consistent JSON structure and proper HTTP status codes.

Megan Fisher
September 6, 2025
9.8k477

A professional API does not return random shapes. It follows consistent patterns.

Example standard

Success:

{ "success": true, "data": {...} }

Error:

{ "success": false, "error": { "code": "VALIDATION_ERROR", "message": "..." } }

Helper functions

function json_ok($data, int $code = 200) {
  http_response_code($code);
  header("Content-Type: application/json");
  echo json_encode(["success" => true, "data" => $data]);
  exit;
}

function json_error(string $codeName, string $message, int $code = 400) {
  http_response_code($code);
  header("Content-Type: application/json");
  echo json_encode(["success" => false, "error" => ["code" => $codeName, "message" => $message]]);
  exit;
}

Why this helps

Frontends can handle responses reliably, and debugging is easier.

Next: Validation strategy, centralize validation instead of repeating everywhere.

#PHP#API#Advanced