JSON REST endpoint
| One file endpoint | |
| Read php://input | |
| Emit JSON + status | |
| Call it with curl |
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.
<?php header("Content-Type: application/json"); $items = ["apple", "orange", "plum"]; echo json_encode(["items" => $items]);
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.
$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; }
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.
http_response_code(201); echo json_encode(["id" => 7, "status" => "created"]);
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.
$ curl -s localhost:8000/api.php
{"items":["apple","orange","plum"]}
Next: Database with PDO
Article author: Arthur Isaev