REST API with PHP
7 min read Quiz at the end
A REST API serves data over HTTP using GET, POST, PUT, and DELETE. Return JSON responses with proper status codes like 200, 201, and 404. Validate all input and use PDO for safe database access.
Building a REST API // Simple router
$method = $_SERVER["REQUEST_METHOD"];
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
header("Content-Type: application/json");
function jsonResponse(mixed $data, int $code = 200): void {
http_response_code($code);
echo json_encode($data);
exit;
}
// Route handling
match(true) {
$method === "GET" && $path === "/api/users"
=> jsonResponse($userModel->all()),
$method === "POST" && $path === "/api/users"
=> jsonResponse($userModel->create(json_decode(file_get_contents("php://input"), true)), 201),
$method === "GET" && preg_match("#^/api/users/(\d+)$#", $path, $m)
=> jsonResponse($userModel->find((int)$m[1])),
$method === "DELETE" && preg_match("#^/api/users/(\d+)$#", $path, $m)
=> jsonResponse($userModel->delete((int)$m[1])),
default
=> jsonResponse(["error" => "Not Found"], 404)
};
Topic Quiz · 5 questions
Test your understanding before moving on
1. Which HTTP method creates a new resource?
A. GET
B. PUT
C. POST
D. DELETE
💡 POST is used to create new resources in REST APIs.
2. Which HTTP method retrieves a resource?
A. POST
B. GET
C. PUT
D. PATCH
💡 GET retrieves resources — it should be read-only with no side effects.
3. What status code means "Created"?
A. 200
B. 201
C. 204
D. 202
💡 HTTP 201 Created is returned when a POST request successfully creates a resource.
4. What Content-Type should a JSON API return?
A. text/html
B. text/json
C. application/json
D. application/xml
💡 REST APIs returning JSON should set Content-Type: application/json.
5. What does HTTP 404 mean?
A. Server error
B. Forbidden
C. Not Found
D. Redirect
💡 HTTP 404 Not Found means the requested resource does not exist.
Submit answers