← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 6 of 24

PHP REST API Basics

What is a REST API?

A REST API exposes your application's data over plain HTTP, letting other programs (a mobile app, a JavaScript frontend, another server) read and modify resources using standard verbs like GET and POST instead of a custom protocol.

Example: What is a REST API?

php
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "REST API responds over plain HTTP"]);
?>

Creating a GET Endpoint

A minimal GET endpoint reads whatever data was requested, encodes it with json_encode(), and prints it -- the client on the other end simply parses that JSON response.

Example: Creating a GET Endpoint

php
<?php
$users = [["id" => 1, "name" => "Alice"]];
echo json_encode($users);
?>

Setting HTTP Response Headers

Every JSON API response should set its Content-Type header to application/json via header(), so consuming code knows to parse the body as JSON rather than guessing from the content itself.

Example: Setting HTTP Response Headers

php
<?php
header("Content-Type: application/json");
echo json_encode(["status" => "ok"]);
?>

Reading Request Methods

Checking $_SERVER[REQUEST_METHOD] tells your script whether the incoming call is a GET, POST, PUT, or DELETE, which is how a single endpoint script can branch to handle several different operations on the same resource.

Example: Reading Request Methods

php
<?php
$_SERVER['REQUEST_METHOD'] = 'DELETE';
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        echo "Reading data";
        break;
    case 'DELETE':
        echo "Deleting resource";
        break;
}
?>

Reading Request Payloads

For POST and PUT requests, the submitted data usually isn't in $_POST at all if it was sent as raw JSON -- you read it directly from the request body with file_get_contents('php://input') and decode it yourself.

Example: Reading Request Payloads

php
<?php
file_put_contents("php_input_sim.json", '{"name": "Alice"}');
$raw = file_get_contents("php_input_sim.json"); // stands in for php://input
$data = json_decode($raw, true);
echo $data['name'];
?>

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.