PHP API Development
In this page:
Designing REST APIs
Building an API means designing which URLs represent which resources and which HTTP methods are valid on each -- GET for reading, POST for creating, PUT/PATCH for updating, DELETE for removing.
Example: Designing REST APIs
<?php
$_SERVER['REQUEST_METHOD'] = 'GET';
echo "GET /users -- read\n";
echo "POST /users -- create\n";
echo "PUT /users/1 -- update\n";
echo "DELETE /users/1 -- remove";
?>
Login to try C/C++/Java/PHP code in the editor
JSON Output Formatting
Well-formed responses go beyond just returning data: consistent status codes, a predictable JSON shape, and clear error messages all make an API easier for other developers to integrate against.
Example: JSON Output Formatting
<?php
header("Content-Type: application/json");
http_response_code(200);
echo json_encode(["status" => "ok", "data" => ["id" => 1]]);
?>
Login to try C/C++/Java/PHP code in the editor
Reading Request Methods
Branching on $_SERVER[REQUEST_METHOD] inside a single endpoint script lets one route handle GET, POST, PUT, and DELETE differently, matching how REST expects one resource URL to support multiple operations.
Example: Reading Request Methods
<?php
$_SERVER['REQUEST_METHOD'] = 'PUT';
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET': echo "Reading"; break;
case 'PUT': echo "Updating"; break;
case 'DELETE': echo "Deleting"; break;
}
?>
Login to try C/C++/Java/PHP code in the editor
Handling API Errors
Returning the right HTTP status code -- 400 for a malformed request, 401 for a missing or invalid token, 404 for a resource that doesn't exist -- lets API clients react programmatically instead of parsing error text.
Example: Handling API Errors
<?php
http_response_code(404);
echo json_encode(["error" => "Resource not found"]);
?>
Login to try C/C++/Java/PHP code in the editor
Simple Token Authentication
A simple token-authentication scheme checks for a secret value in the Authorization header on every request, rejecting calls that don't include a valid token before any protected logic runs.
Example: Simple Token Authentication
<?php
$validToken = "secret-token";
$authHeader = "Bearer wrong-token";
if ($authHeader !== "Bearer $validToken") {
http_response_code(401);
echo json_encode(["error" => "Unauthorized"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: