← Back to PHP Course | Chapter 15: Web Development | Lesson 5 of 12

PHP API Development

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
<?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";
?>

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
<?php
header("Content-Type: application/json");
http_response_code(200);
echo json_encode(["status" => "ok", "data" => ["id" => 1]]);
?>

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
<?php
$_SERVER['REQUEST_METHOD'] = 'PUT';
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET': echo "Reading"; break;
    case 'PUT': echo "Updating"; break;
    case 'DELETE': echo "Deleting"; break;
}
?>

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
<?php
http_response_code(404);
echo json_encode(["error" => "Resource not found"]);
?>

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
<?php
$validToken = "secret-token";
$authHeader = "Bearer wrong-token";
if ($authHeader !== "Bearer $validToken") {
    http_response_code(401);
    echo json_encode(["error" => "Unauthorized"]);
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.