Lesson 10 / 10

Building a Simple REST API

A minimal JSON endpoint

<?phpnheader("Content-Type: application/json");nn$courses = [n    ["id" => 1, "title" => "PHP"],n    ["id" => 2, "title" => "Python"],n];nnecho json_encode($courses);

header("Content-Type: application/json") tells the client’s browser or app exactly what kind of data is coming back, so it can parse the response correctly rather than treating it as plain text or HTML. json_encode() converts a PHP array directly into a JSON string, the near-universal format for API responses across the web today.

Reading the request method

$method = $_SERVER["REQUEST_METHOD"];nnif ($method === "GET") {n    // return datan} elseif ($method === "POST") {n    $input = json_decode(file_get_contents("php://input"), true);n    // handle the submitted datan}

file_get_contents("php://input") reads the raw request body — this is how you receive JSON data sent by a client, since $_POST only populates automatically for traditional HTML form submissions, not for JSON request bodies.

Status codes matter

http_response_code(404);necho json_encode(["error" => "Course not found"]);

Set an accurate HTTP status code on every response — 200 for success, 404 for a missing resource, 400 for bad input the client sent, 401/403 for authentication or permission issues, 500 for a genuine server-side error. A REST client relies on the status code, not just the response body, to correctly determine what happened — returning 200 alongside an error message in the body is a common and genuinely confusing mistake.

You have completed the course

From your first script to namespaces, traits, and a working API endpoint — you now have a professional-level PHP foundation, the same one WordPress itself is built on. Take the certification assessment next, or apply to the WordPress & PHP Development Internship to build something real.