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

PHP REST API Basics

A REST API is like a restaurant menu that programs can order from using simple web requests. Each address stands for something, such as users, and verbs like get or delete say what to do.
Syntax
php
header("Content-Type: application/json");
http_response_code(200);
echo json_encode($data);

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
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["message" => "REST API responds over plain HTTP"])` to the output
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
// Declare `$users` as an array: `[["id" => 1, "name" => "Alice"]]`
$users = [["id" => 1, "name" => "Alice"]];
// Print `json_encode($users)` to the output
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
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["status" => "ok"])` to the output
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
// Set `$_SERVER['REQUEST_METHOD']` to 'DELETE'
$_SERVER['REQUEST_METHOD'] = 'DELETE';
// Switch on `$_SERVER['REQUEST_METHOD']` and branch by matching case
switch ($_SERVER['REQUEST_METHOD']) {
    // Case: `'GET'`
    case 'GET':
        // Print "Reading data" to the output
        echo "Reading data";
        break;
    // Case: `'DELETE'`
    case 'DELETE':
        // Print "Deleting resource" to the output
        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'];
?>
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. Forgetting to set Content-Type: application/json before sending JSON output.
  2. Ignoring $_SERVER[REQUEST_METHOD], so a GET and a POST are handled the same way.
  3. Always returning status 200 even for errors, instead of codes like 404 or 400.

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.