CodeBlanks Logo Icon CodeBlanks

JSON response format

PHP course · Advanced · Lesson 58/92

Write a consistent JSON format for success and error responses.

The JsonResponse class

A REST API needs a consistent response format. The JsonResponse class provides it: it holds a status code (200, 201, 400, 404) and a body array. The send() method does three things: it sets the status code with http_response_code(), the content type with header(), and returns the body as structured data through json_encode().

Every handler then produces the same shape, so the client can parse it without trouble.

Status codes

HTTP status codes carry the meaning of a response. 200 means success, 201 created, 400 bad request and 404 not found. The JsonResponse constructor takes this code as its first parameter.

A successful read returns 200, creating a new record returns 201. Missing or broken requests answer with 400, a non-existent resource with 404. The client reads the outcome from the code alone.

Exercise Define the JsonResponse class

Define a class named JsonResponse. Add two properties: public int $status; and public array $body;. Add a __construct(int $status, array $body) that assigns them. Write a send() method that calls http_response_code($this->status) and header("Content-Type: application/json"), then returns return json_encode($this->body, JSON_UNESCAPED_UNICODE);. The demo creates an instance and prints the send() output.

Show example solution
application/json"); return json_encode($this->body, JSON_UNESCAPED_UNICODE);
Example solution:
<?php
// REST API project: Router + addRoute + dispatch + JsonResponse

class Router {
    public array $routes = [];
    public function addRoute(string $method, string $path, $handler): void {
    $this->routes[] = ["method" => $method, "path" => $path, "handler" => $handler];
}
    public function dispatch(string $method, string $path) {
    foreach ($this->routes as $route) {
        if ($route["method"] === $method && $route["path"] === $path) {
            return ($route["handler"])();
        }
    }
    return "404 Not Found";
}
}

class JsonResponse {
    public int $status;
    public array $body;
    public function __construct(int $status, array $body) {
        $this->status = $status;
        $this->body = $body;
    }
    public function send(): string {
        http_response_code($this->status);
        header("Content-Type: application/json");
        return json_encode($this->body, JSON_UNESCAPED_UNICODE);
    }
}

// Demo:
$resp = new JsonResponse(200, ["message" => "OK"]);
echo $resp->send();

Test yourself

  1. Which three tools does JsonResponse::send() use, in order?

    • echo, print and var_dump
    • count, sort and array_map
    • fopen, fwrite and fclose
    • http_response_code, header and json_encode
    Show answer

    http_response_code, header and json_encode — Correct. send() sets the status code, then the header, then encodes the body as structured data.

  2. Match the status codes

    200
    Success
    201
    Created
    400
    Bad request
    404
    Not found
  3. Complete the content type header

    header("____");
    Show answer
    header("Content-Type: application/json");

All lessons in Advanced