PHP REST API Basics
In this page:
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
header("Content-Type: application/json");
echo json_encode(["message" => "REST API responds over plain HTTP"]);
?>
Login to try C/C++/Java/PHP code in the editor
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
$users = [["id" => 1, "name" => "Alice"]];
echo json_encode($users);
?>
Login to try C/C++/Java/PHP code in the editor
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
header("Content-Type: application/json");
echo json_encode(["status" => "ok"]);
?>
Login to try C/C++/Java/PHP code in the editor
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
$_SERVER['REQUEST_METHOD'] = 'DELETE';
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
echo "Reading data";
break;
case 'DELETE':
echo "Deleting resource";
break;
}
?>
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser