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

PHP API Development

Building an API is like designing a menu for other programs, deciding which addresses and requests are allowed. It lets apps and websites swap data with yours in an orderly way.
Syntax
php
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
<?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";
?>

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
// 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]]);
?>

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
// 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;
}
?>

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
// 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"]);
?>

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
// 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"]);
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Returning HTML errors instead of JSON error responses from an API.
  2. Ignoring the request method, so a GET and a POST are treated the same.
  3. Always returning status 200 even when the request failed.

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.