REST APIs
suggest changeRepresentational State Transfer (REST) is an architectural style for networked systems. In PHP, building RESTful APIs involves routing incoming HTTP requests to resources, reading and validating JSON request bodies, dispatching by HTTP verb, and returning structured JSON payloads with appropriate HTTP status codes.
1. REST Architecture and HTTP Verbs
REST APIs map operations onto standard HTTP verbs:
| HTTP Verb | Path Example | Action | Expected Status Code |
|---|---|---|---|
GET |
/api/v1/products |
Retrieve list of products | 200 OK |
GET |
/api/v1/products/42 |
Retrieve single product | 200 OK or 404 Not Found |
POST |
/api/v1/products |
Create a new product | 201 Created or 422 Unprocessable |
PUT |
/api/v1/products/42 |
Replace an existing product | 200 OK or 204 No Content |
PATCH |
/api/v1/products/42 |
Partially update product attributes | 200 OK or 204 No Content |
DELETE |
/api/v1/products/42 |
Delete a product | 204 No Content or 200 OK |
2. Reading JSON Request Bodies (php://input)
When a client sends a JSON payload with Content-Type: application/json, PHP does not populate the $_POST superglobal (which is only populated for application/x-www-form-urlencoded or multipart/form-data). Furthermore, PHP does not populate superglobals for PUT, PATCH, or DELETE requests.
To read the raw request body, read from the read-only stream php://input:
<?php
function getJsonInput(): array
{
// Verify client Content-Type
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (stripos($contentType, 'application/json') === false) {
http_response_code(415); // Unsupported Media Type
echo json_encode(['error' => 'Content-Type must be application/json']);
exit;
}
$rawBody = file_get_contents('php://input');
if ($rawBody === false || trim($rawBody) === '') {
return [];
}
try {
return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
http_response_code(400); // Bad Request
echo json_encode(['error' => 'Malformed JSON: ' . $e->getMessage()]);
exit;
}
}
3. Sending Standard JSON Responses
A clean helper standardizes response headers and formatting across all endpoints:
<?php
function sendJsonResponse(mixed $data, int $statusCode = 200): void
{
// Set HTTP response status code
http_response_code($statusCode);
// Set headers
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
if ($statusCode === 204) {
// No Content responses must not send a body
return;
}
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
4. Complete RESTful API Endpoint Example
The following script implements a complete CRUD resource endpoint for /api/books:
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
// Simple in-memory mock datastore
$database = [
1 => ['id' => 1, 'title' => 'Clean Code', 'author' => 'Robert C. Martin'],
2 => ['id' => 2, 'title' => 'Design Patterns', 'author' => 'Gang of Four'],
];
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
// Parse resource ID from URL: e.g. /api/books or /api/books/1
$pathSegments = explode('/', trim($uri, '/'));
$resourceId = isset($pathSegments[2]) && is_numeric($pathSegments[2])
? (int) $pathSegments[2]
: null;
switch ($method) {
case 'GET':
if ($resourceId !== null) {
// Retrieve single book
if (!isset($database[$resourceId])) {
sendJsonResponse(['error' => 'Resource not found'], 404);
}
sendJsonResponse($database[$resourceId], 200);
} else {
// List all books
sendJsonResponse(array_values($database), 200);
}
break;
case 'POST':
$body = getJsonInput();
// Validate required fields
if (empty($body['title']) || empty($body['author'])) {
sendJsonResponse([
'error' => 'Validation error',
'details' => ['title and author are required fields']
], 422); // Unprocessable Entity
}
$newId = count($database) + 1;
$newBook = [
'id' => $newId,
'title' => htmlspecialchars($body['title'], ENT_QUOTES, 'UTF-8'),
'author' => htmlspecialchars($body['author'], ENT_QUOTES, 'UTF-8'),
];
$database[$newId] = $newBook;
header('Location: /api/books/' . $newId);
sendJsonResponse($newBook, 201); // Created
break;
case 'PUT':
case 'PATCH':
if ($resourceId === null || !isset($database[$resourceId])) {
sendJsonResponse(['error' => 'Resource not found'], 404);
}
$body = getJsonInput();
if (isset($body['title'])) {
$database[$resourceId]['title'] = $body['title'];
}
if (isset($body['author'])) {
$database[$resourceId]['author'] = $body['author'];
}
sendJsonResponse($database[$resourceId], 200);
break;
case 'DELETE':
if ($resourceId === null || !isset($database[$resourceId])) {
sendJsonResponse(['error' => 'Resource not found'], 404);
}
unset($database[$resourceId]);
sendJsonResponse(null, 204); // No Content
break;
default:
header('Allow: GET, POST, PUT, PATCH, DELETE');
sendJsonResponse(['error' => 'Method not allowed'], 405);
break;
}
5. Security and API Best Practices
- Strict Input Validation and Sanitization: Never trust incoming parameters directly. Validate types, lengths, and constraints before passing data to storage.
- CORS Handling: Handle
OPTIONSpreflight requests when the API is consumed by browser applications on separate domains. - Consistent Error Payload Format: Return errors using a uniform schema (such as RFC 7807 Problem Details):
{ "type": "https://example.com/errors/validation", "title": "Validation Failed", "status": 422, "detail": "The 'email' field must be a valid email address." } - Use Proper Status Codes: Do not return HTTP
200 OKwith an error message in the payload body (e.g.{"status": "error"}); use standard HTTP status codes (400,401,403,404,422,500).