JSON REST endpoint

A REST endpoint answers in data, not in pages. In PHP one file reads the request, decides what happened, and sends one JSON value together with a status code.

One file endpoint

A REST endpoint is a PHP file that speaks JSON instead of HTML. It takes a request, does one job, and answers with data plus a status code. One file is enough to learn the shape: read, decide, answer.

Declare the answer format first with a Content-Type header, then print exactly one JSON value. The background primer is REST.

The file api.php in the folder you serve with php -S 127.0.0.1:8000:

<?php header("Content-Type: application/json"); $items = ["apple", "orange", "plum"]; echo json_encode(["items" => $items]);

curl -s "http://127.0.0.1:8000/api.php"

{"items":["apple","orange","plum"]}

The answer is one JSON object with the list inside it, and the Content-Type header tells the client how to read the text. The same file answers every GET request the same way, so a client needs no HTML parser.

Read php://input

Browsers send forms, but APIs send raw JSON bodies. PHP does not fill $_POST for those - read the raw stream php://input and decode it. Always check the decode result: a client can send anything. The decode is json_decode() and the check is is_array().

The file input.php in the same folder:

<?php $raw = file_get_contents("php://input"); $data = json_decode($raw, true); if (!is_array($data)) { http_response_code(400); echo json_encode(["error" => "Bad JSON"]); exit; } header("Content-Type: application/json"); echo json_encode(["received" => $data]);

curl -s -d '{"name":"Ada"}' "http://127.0.0.1:8000/input.php"

{"received":{"name":"Ada"}}

The stream holds the body of the request, and the decoded array comes back in the answer. A broken body takes the early exit instead, without any data from it.

Emit JSON + status

The answer has two parts: the status code and the body. Set the code with http_response_code() before printing anything, then print one JSON value. Keep one envelope - data on success, an error key on failure - so clients parse every answer the same way.

The file created.php in the same folder:

<?php http_response_code(201); echo json_encode(["id" => 7, "status" => "created"]);

curl -s "http://127.0.0.1:8000/created.php"

{"id":7,"status":"created"}

The body names the new resource, and the status line of the same response is 201, checked with a client that reads it. A client that only read the body could not tell a creation from an update, so the code carries the difference.

Call it with curl

Test the endpoint from the terminal before writing client code. One command shows the raw answer with no browser in the way.

The commands under the three files above are exactly that test: a curl -s request for the list, a -d request with a JSON body for the input file, and one more request for the created answer.

Exercises

  1. Add a third item to the list in api.php and request it again.
  2. Send a broken body to input.php and read the status with curl -s -o /dev/null -w "%{http_code}".
  3. Change created.php to answer 204 with an empty body and see what curl prints.
  4. Add a method key to the answer of api.php that tells which request method arrived.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a REST endpoint answer with?

    Answer

    A JSON body together with a status code

    The client reads the status for the outcome and the JSON body for the data.

  2. How does a PHP script read a raw JSON request body?

    Answer

    With file_get_contents("php://input")

    PHP fills $_POST only for form encoded bodies, so a JSON body is read from the input stream.

  3. Why check is_array() after json_decode()?

    Answer

    Because a client can send anything, and a broken body decodes to null

    A failed decode returns null, so the check is what separates a usable body from noise.

  4. Which status code fits a newly created resource?

    Answer

    201

    201 Created says that the request made a new resource, usually named in the body.

  5. What does this program print? <?php $raw = '{"name":"Ada"}'; $data = json_decode($raw, true); echo $data["name"];

    Answer

    Ada

    The true argument gives an array, and the name key holds the string Ada.

  6. What does this program print? <?php $raw = '{broken}'; var_dump(json_decode($raw, true));

    Answer

    NULL

    A body that is not JSON decodes to null, which is why the endpoint checks the result.

  7. What does this program print? <?php echo json_encode(["id" => 7, "status" => "created"]);

    Answer

    {"id":7,"status":"created"}

    json_encode writes an object with quoted keys, numeric and string values, and no spaces.

  8. What does this program print? <?php http_response_code(400); echo http_response_code();

    Answer

    400

    The first call sets the code and the second one reads it back.

  9. Why must an endpoint print exactly one JSON value?

    Answer

    The client parses the whole body as one document

    A second value, or text before the first, makes the body invalid JSON and the client fails to parse it.

  10. What does curl -s -d '{"a":1}' URL send?

    Answer

    A POST request with the JSON body

    The -d option puts the data into the body of a POST request, which the script reads from php://input.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev