PHP API Development
In this page:
switch ($_SERVER["REQUEST_METHOD"]) {
case "GET": // read
break;
case "POST": // create
break;
case "PUT": // update
break;
case "DELETE": // remove
break;
}
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
// Set `$_SERVER['REQUEST_METHOD']` to 'GET'
$_SERVER['REQUEST_METHOD'] = 'GET';
// Print "GET /users -- read\n" to the output
echo "GET /users -- read\n";
// Print "POST /users -- create\n" to the output
echo "POST /users -- create\n";
// Print "PUT /users/1 -- update\n" to the output
echo "PUT /users/1 -- update\n";
// Print "DELETE /users/1 -- remove" to the output
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
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Call `http_response_code(200)`
http_response_code(200);
// Print `json_encode(["status" => "ok", "data" => ["id" => 1]])` to the output
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
// Set `$_SERVER['REQUEST_METHOD']` to 'PUT'
$_SERVER['REQUEST_METHOD'] = 'PUT';
// Switch on `$_SERVER['REQUEST_METHOD']` and branch by matching case
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
// Call `http_response_code(404)`
http_response_code(404);
// Print `json_encode(["error" => "Resource not found"])` to the output
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
// Declare `$validToken`, set to "secret-token"
$validToken = "secret-token";
// Declare `$authHeader`, set to "Bearer wrong-token"
$authHeader = "Bearer wrong-token";
// Check whether `$authHeader !== "Bearer $validToken"`
if ($authHeader !== "Bearer $validToken") {
// Call `http_response_code(401)`
http_response_code(401);
// Print `json_encode(["error" => "Unauthorized"])` to the output
echo json_encode(["error" => "Unauthorized"]);
}
?>
Login to try C/C++/Java/PHP code in the editor
- Returning HTML errors instead of JSON error responses from an API.
- Ignoring the request method, so a GET and a POST are treated the same.
- Always returning status 200 even when the request failed.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: