ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PHP Tutorial• 8 min read

Building RESTful Web APIs with PHP

Routing HTTP methods, handling JSON payloads, and setting headers

PHP is ideal for building lightweight, high-performance microservices and RESTful API endpoints that consume and return JSON data to mobile apps and frontend frameworks.

Architecting a Clean REST Endpoint

Set header("Content-Type: application/json; charset=UTF-8"); before any output.

Use $_SERVER["REQUEST_METHOD"] to route incoming GET, POST, PUT, and DELETE operations.

Read raw JSON request bodies via file_get_contents("php://input") followed by json_decode().

Emit standard HTTP status codes using http_response_code(200 | 201 | 400 | 404 | 500).

Pure PHP REST API Endpoint (api/users.php)
<?php
  header("Content-Type: application/json; charset=UTF-8");
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

  $method = $_SERVER['REQUEST_METHOD'];

  switch ($method) {
    case 'GET':
      $data = [
        "status" => "success",
        "data" => [
          ["id" => 1, "name" => "Alice Cooper", "role" => "Instructor"],
          ["id" => 2, "name" => "Bob Sterling", "role" => "Student"]
        ]
      ];
      http_response_code(200);
      echo json_encode($data);
      break;

    case 'POST':
      $rawBody = file_get_contents("php://input");
      $input = json_decode($rawBody, true);

      if (empty($input['name'])) {
        http_response_code(422);
        echo json_encode(["error" => "The 'name' field is required."]);
        exit;
      }

      http_response_code(201);
      echo json_encode(["status" => "created", "id" => rand(100, 999), "name" => $input['name']]);
      break;

    default:
      http_response_code(405);
      echo json_encode(["error" => "Method not allowed"]);
      break;
  }
?>
json_encode converts native PHP arrays and objects into compliant JSON strings.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which PHP stream wrapper reads the raw, unparsed request payload for incoming JSON POST requests?