PHP REST API Basics
In this page:
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
// 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"]);
?>
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
// 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);
?>
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
// Call `header("Content-Type: application/json")`
header("Content-Type: application/json");
// Print `json_encode(["status" => "ok"])` to the output
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
// 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;
}
?>
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
- Forgetting to set
Content-Type: application/jsonbefore sending JSON output. - Ignoring
$_SERVER[REQUEST_METHOD], so a GET and a POST are handled the same way. - Always returning status 200 even for errors, instead of codes like 404 or 400.
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