Building a REST API
Serve JSON instead of HTML so front-ends and mobile apps can talk to your PHP — HTTP methods, status codes, JSON encoding and a working endpoint.
What you will learn
- Explain what a REST API and JSON are
- Read the request method and send JSON with the right status code
- Build a small JSON endpoint with PDO
What is a REST API?
Until now your PHP has produced HTML pages for humans. But modern front-ends (React, Angular, mobile apps) do not want HTML — they want raw data they can render themselves. A REST API is a PHP back-end that, instead of pages, returns JSON (a simple text format for data) at predictable URLs. This is one of the most in-demand back-end skills, because nearly every app today is a front-end talking to an API.
Two terms. JSON (JavaScript Object Notation) is a lightweight way to write data as text — it looks just like a PHP associative array. REST is a set of conventions: use the right HTTP method for the right action, and the right status code to report the result.
| HTTP method | Means | Example |
|---|---|---|
GET | Read data | List all products |
POST | Create something new | Add a product |
PUT / PATCH | Update existing | Edit a product |
DELETE | Remove something | Delete a product |
And a few common status codes — the number the server sends to say how it went:
| Code | Means |
|---|---|
200 | OK — success |
201 | Created — a new record was made |
404 | Not found |
400 | Bad request — the client sent invalid data |
500 | Server error |
Sending JSON
Two steps turn PHP data into a JSON response: set a header telling the browser "this is JSON", then echo json_encode(...) to convert a PHP array into JSON text.
<?php
header("Content-Type: application/json");
$product = [
"id" => 1,
"name" => "Keyboard",
"price" => 1299.00
];
echo json_encode($product);
?>header("Content-Type: application/json") tells whoever called the API to expect JSON, not HTML. json_encode($product) then takes the PHP associative array and turns it into a JSON string. That string is the entire response — no HTML at all.
Note: Output (what the client receives):
{"id":1,"name":"Keyboard","price":1299}
The associative array became JSON text. A React or mobile app reads this, picks out name and price, and displays them however it likes. Notice it is the same shape as the PHP array — JSON and PHP arrays map almost one-to-one.
Reading the method and routing the request
A real endpoint behaves differently depending on the HTTP method. $_SERVER["REQUEST_METHOD"] tells you which method was used, and http_response_code() sets the status the client receives.
<?php
header("Content-Type: application/json");
$method = $_SERVER["REQUEST_METHOD"];
if ($method === "GET") {
$stmt = $pdo->query("SELECT * FROM products");
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
} elseif ($method === "POST") {
$data = json_decode(file_get_contents("php://input"), true);
$stmt = $pdo->prepare("INSERT INTO products (name, price) VALUES (?, ?)");
$stmt->execute([$data["name"], $data["price"]]);
http_response_code(201); // Created
echo json_encode(["message" => "Product created"]);
} else {
http_response_code(405); // Method Not Allowed
echo json_encode(["error" => "Method not supported"]);
}
?>Walk through it. We read the method into $method. On a GET, we fetch all products and json_encode the array — a JSON list comes back. On a POST, the incoming JSON body arrives as raw text from php://input, so json_decode(..., true) turns it back into a PHP array; we insert it with a prepared statement (still essential against SQL injection), set status 201 "Created", and confirm with JSON. Any other method gets a 405 error. The true in json_decode means "give me an associative array".
Note: Output for a GET request: [{"id":1,"name":"Keyboard","price":1299},{"id":2,"name":"Mouse","price":499}] Output for a POST (with a 201 status): {"message":"Product created"} The same URL serves different actions based on the HTTP method, each with the correct status code. That is REST: methods describe the action, status codes describe the result, JSON carries the data.
Watch out: Even in an API, always use prepared statements for any value from the client, and validate the incoming JSON before using it. An API is just as exposed to SQL injection and bad input as a form.
Tip: Test an API without a front-end using a tool like Postman, or the curl command in your terminal — they let you send GET/POST/DELETE requests and see the JSON that comes back.
Q. What does json_encode() do in a PHP API?
✍️ Practice
- Return a single product as JSON with the correct Content-Type header.
- Add GET (list) and POST (create) handling to one endpoint based on the request method.
🏠 Homework
- Build a JSON API for a
taskstable supporting GET (list) and POST (create) with proper status codes and prepared statements.