Lesson 3 of 7
JSON Request Validation & Response Envelope
API validation differs from form validation - errors must be machine-readable JSON, not HTML. The ApiResponse class enforces a consistent envelope so clients always know where to find data and errors. Consistent response structure is the most important API design decision.
ApiResponse Class & Validation Pipeline
<?php
declare(strict_types=1);
class ApiResponse {
private function __construct(
private readonly mixed $payload,
private readonly int $status,
private readonly array $headers = [],
) {}
public static function success(mixed $data, int $status = 200, array $meta = []): static {
$body = ["success" => true, "data" => $data];
if (!empty($meta)) $body["meta"] = $meta;
return new static($body, $status);
}
public static function created(mixed $data): static {
return static::success($data, 201);
}
public static function noContent(): static {
return new static(null, 204);
}
public static function error(array $errors, int $status = 400, string $code = ""): static {
$errorCodes = [
400 => "BAD_REQUEST", 401 => "UNAUTHORIZED",
403 => "FORBIDDEN", 404 => "NOT_FOUND",
405 => "METHOD_NOT_ALLOWED", 409 => "CONFLICT",
422 => "VALIDATION_ERROR", 429 => "RATE_LIMITED",
500 => "INTERNAL_ERROR",
];
return new static([
"success" => false,
"error" => [
"code" => $code ?: ($errorCodes[$status] ?? "ERROR"),
"message" => isset($errors["message"]) ? $errors["message"] : "Request failed.",
"details" => isset($errors["message"]) ? [] : $errors,
],
], $status);
}
public function send(): never {
http_response_code($this->status);
header("Content-Type: application/json; charset=UTF-8");
foreach ($this->headers as $name => $value) header("$name: $value");
if ($this->payload !== null) {
echo json_encode($this->payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
exit;
}
}
// ── API Validator - machine-readable errors ────────────────────
class ApiValidator {
private array $errors = [];
public function required(string $field, mixed $value, string $message = ""): static {
if ($value === null || $value === "" || $value === []) {
$this->errors[$field] = $message ?: ucfirst($field) . " is required.";
}
return $this;
}
public function string(string $field, mixed $value, int $min = 1, int $max = 255): static {
if (isset($this->errors[$field])) return $this;
if (!is_string($value)) { $this->errors[$field] = ucfirst($field) . " must be a string."; return $this; }
$len = mb_strlen(trim($value));
if ($len < $min) $this->errors[$field] = ucfirst($field) . " must be at least $min characters.";
elseif ($len > $max) $this->errors[$field] = ucfirst($field) . " must be $max characters or fewer.";
return $this;
}
public function email(string $field, mixed $value): static {
if (isset($this->errors[$field])) return $this;
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) $this->errors[$field] = "Invalid email address.";
return $this;
}
public function inList(string $field, mixed $value, array $allowed): static {
if (!in_array($value, $allowed, true)) {
$this->errors[$field] = ucfirst($field) . " must be one of: " . implode(", ", $allowed) . ".";
}
return $this;
}
public function passes(): bool { return empty($this->errors); }
public function throw(): void {
if (!empty($this->errors)) throw new ValidationException($this->errors);
}
}
// ── Controller example ─────────────────────────────────────────
class PostApiController {
public function __construct(
private readonly PostService $service,
private readonly ApiAuthMiddleware $auth,
) {}
public function index(ApiRequest $req): ApiResponse {
$page = max(1, (int) $req->query("page", 1));
$perPage = min(50, max(1, (int) $req->query("per_page", 10)));
$search = trim($req->query("search", ""));
$result = $this->service->listPublished($page, $perPage, $search);
return ApiResponse::success(
array_map(fn($p) => $p->toArray(), $result["items"]),
meta: ["total" => $result["total"], "page" => $page, "per_page" => $perPage, "last_page" => $result["last_page"]]
);
}
public function store(ApiRequest $req): ApiResponse {
$user = $this->auth->requireAuth($req);
$v = new ApiValidator();
$v->required("title", $req->body("title"))
->string("title", $req->body("title", ""), 3, 200)
->required("body", $req->body("body"))
->string("body", $req->body("body", ""), 10, 50000)
->inList("status", $req->body("status", "draft"), ["draft", "published"]);
$v->throw();
$post = $this->service->create([
"title" => trim($req->body("title")),
"body" => trim($req->body("body")),
"status" => $req->body("status", "draft"),
"author_id" => $user["id"],
]);
return ApiResponse::created($post->toArray());
}
}Quick Quiz
Tip
Tip
Practice JSON Request Validation Response Envelope in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for JSON Request Validation & Response Envelope
Practice Task
Note
Practice Task - (1) Write a working example of JSON Request Validation Response Envelope from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with JSON Request Validation Response Envelope is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?