REST API Development in PHP: Design, Build and Secure
What is REST API development?
REST API development is building a web service that exposes data as resources at URLs, such as /api/v1/products/5, and lets clients act on them with standard HTTP methods like GET, POST, PUT, PATCH and DELETE. The server replies with a status code and, usually, a JSON body. PHP can build REST APIs with or without a framework.
Resources, methods and the vocabulary of REST
A resource is a thing your API exposes, named with a plural noun: /products is a collection and /products/5 is one item. The HTTP method says what to do with it. If APIs are new to you, read the introduction to APIs first.
| Method | Example | Action | Idempotent? |
|---|---|---|---|
| GET | /products | List or read; never changes data | Yes |
| POST | /products | Create a new item | No |
| PUT | /products/5 | Replace the whole item | Yes |
| PATCH | /products/5 | Change some fields | Not necessarily |
| DELETE | /products/5 | Remove the item | Yes |
Idempotent means repeating the same request has the same effect as sending it once, which lets clients retry safely. Stateless means every request carries everything needed to process it, including authentication.
Status codes that clients rely on
| Code | Meaning | Use when |
|---|---|---|
| 200 OK | Success with a body | Returning a resource or list |
| 201 Created | New resource created | After POST, with a Location header |
| 204 No Content | Success, no body | After DELETE |
| 400 Bad Request | Malformed request | Invalid JSON |
| 401 Unauthorized | Not authenticated | Missing or invalid token |
| 403 Forbidden | Authenticated but not allowed | Editing someone else's data |
| 404 Not Found | No such resource | Unknown ID or URL |
| 422 Unprocessable Content | Valid JSON, invalid data | Validation errors |
| 429 Too Many Requests | Rate limit reached | Throttling clients |
Return errors in a consistent shape. RFC 9457, Problem Details for HTTP APIs, defines a standard JSON format with type, title and status fields and the application/problem+json media type.
Designing response bodies, filtering and pagination
Decide on one response shape and use it everywhere, so client developers never have to guess. A common pattern wraps results in a data key and puts paging details in a separate meta key:
GET /api/v1/products?category=stationery&sort=-price_paise&page=2&per_page=20
{
"data": [
{ "id": 41, "name": "Fountain pen", "price_paise": 45000 },
{ "id": 17, "name": "Gel pen", "price_paise": 2000 }
],
"meta": { "page": 2, "per_page": 20, "total": 57 }
}- Use query parameters for filtering, sorting and paging, never for the resource identity.
- Check sort fields against an allow-list, because column names cannot be bound as SQL parameters.
- Cap
per_pageat a sensible maximum so one request cannot ask for every row. - Use consistent field names, such as snake_case, and send dates in ISO 8601 format with a time zone.
- Store money as integers in the smallest unit, such as paise, to avoid rounding errors.
Only return the fields a client needs. Never send password hashes, internal flags or other users' personal data just because they are in the database row.
JSON responses and routing in plain PHP
One front controller receives every request, sends JSON with the right status and routes by method and path. Data is encoded as JSON with JSON_THROW_ON_ERROR so encoding problems are never silent.
<?php
// public/index.php
declare(strict_types=1);
function json(mixed $data, int $status = 200, array $headers = []): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
foreach ($headers as $name => $value) {
header($name . ': ' . $value);
}
if ($status !== 204) {
echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
exit;
}
function problem(int $status, string $title, array $extra = [], array $headers = []): never
{
json(['type' => 'about:blank', 'title' => $title, 'status' => $status] + $extra,
$status, ['Content-Type' => 'application/problem+json'] + $headers);
}
$pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', 'shop_app', getenv('DB_PASSWORD') ?: '', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$method = $_SERVER['REQUEST_METHOD'];
$path = rtrim((string) parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
if ($path === '/api/v1/products') {
match ($method) {
'GET' => json(['data' => $pdo->query('SELECT id, name, price_paise FROM products ORDER BY id LIMIT 50')->fetchAll()]),
'POST' => createProduct($pdo, authenticate($pdo)),
default => problem(405, 'Method not allowed', [], ['Allow' => 'GET, POST']),
};
}
if (preg_match('#^/api/v1/products/(\d+)$#', $path, $m) && $method === 'GET') {
$stmt = $pdo->prepare('SELECT id, name, price_paise FROM products WHERE id = ?');
$stmt->execute([(int) $m[1]]);
$product = $stmt->fetch();
$product ? json(['data' => $product]) : problem(404, 'Product not found');
}
problem(404, 'Not found');The functions createProduct() and authenticate() follow in the next two sections; place them above the routing code. Run the API with php -S localhost:8000 -t public public/index.php.
Reading and validating JSON input
PHP does not fill $_POST for JSON bodies, so read the raw body from php://input. Validate types strictly and return every error at once with status 422.
<?php
function readJson(): array
{
try {
$data = json_decode((string) file_get_contents('php://input'), true, 32, JSON_THROW_ON_ERROR);
} catch (JsonException) {
problem(400, 'Request body must be valid JSON');
}
return is_array($data) ? $data : problem(400, 'Request body must be a JSON object');
}
function createProduct(PDO $pdo, int $userId): never
{
$in = readJson();
$errors = [];
$name = is_string($in['name'] ?? null) ? trim($in['name']) : '';
if ($name === '' || mb_strlen($name) > 120) {
$errors['name'] = 'Name is required, up to 120 characters.';
}
$price = $in['price_paise'] ?? null;
if (!is_int($price) || $price < 1) {
$errors['price_paise'] = 'Price must be a positive whole number of paise.';
}
if ($errors) {
problem(422, 'Validation failed', ['errors' => $errors]);
}
$pdo->prepare('INSERT INTO products (name, price_paise, created_by) VALUES (?, ?, ?)')
->execute([$name, $price, $userId]);
$id = (int) $pdo->lastInsertId();
json(['data' => ['id' => $id, 'name' => $name, 'price_paise' => $price]], 201,
['Location' => '/api/v1/products/' . $id]);
}Unexpected failures, such as a lost database connection, must still produce JSON. Register an exception handler near the top of the front controller, log the details privately and send a generic 500 response. With display_errors switched off in production, clients never see stack traces or file paths.
<?php
set_exception_handler(function (Throwable $e): void {
error_log((string) $e);
problem(500, 'Internal server error');
}); Token authentication and versioning
APIs usually authenticate with a bearer token in the Authorization header instead of a session cookie. Generate tokens with bin2hex(random_bytes(32)), show each one to the user once and store only its SHA-256 hash, so a database leak does not expose working tokens.
<?php
function authenticate(PDO $pdo): int
{
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/^Bearer ([a-f0-9]{64})$/', $header, $m)) {
problem(401, 'Missing or malformed token', [], ['WWW-Authenticate' => 'Bearer']);
}
$stmt = $pdo->prepare('SELECT user_id FROM api_tokens WHERE token_hash = ? AND revoked_at IS NULL');
$stmt->execute([hash('sha256', $m[1])]);
$userId = $stmt->fetchColumn();
if ($userId === false) {
problem(401, 'Invalid token', [], ['WWW-Authenticate' => 'Bearer']);
}
return (int) $userId;
}- Some Apache and FastCGI setups do not pass the
Authorizationheader to PHP by default; check your server configuration if it is always empty. - Put the major version in the path, such as
/api/v1/, and add/api/v2/only for breaking changes. Adding new optional fields is not a breaking change. - Serve APIs only over HTTPS, apply rate limits and check per-record ownership on every request.
- Allow cross-origin browser requests only from front ends you trust, using CORS headers.
Password-based login for the people who create tokens is covered in the PHP authentication guide.
Practical exercise: build and test a products API
Assemble the code above into one project on your machine, create the products and api_tokens tables and insert one hashed test token. Then test it from the terminal:
curl -i http://localhost:8000/api/v1/products
curl -i -X POST http://localhost:8000/api/v1/products \
-H "Authorization: Bearer YOUR_64_CHARACTER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"Gel pen","price_paise":2000}'- Add
PATCHandDELETEfor/api/v1/products/{id}, returning 200 and 204. - Add
?page=pagination with a maximum page size. - Call the API from a web page with the Fetch API.
You are done when a POST without a token returns 401, a negative price returns 422 with a field error, a valid POST returns 201 with a Location header and an unknown ID returns 404. API work is a major part of the advanced PHP course.
Common mistakes
- Returning status 200 with an error message in the body, so clients cannot detect failures.
- Using verbs in URLs such as
/getProductsinstead of methods on resource nouns. - Changing data on a GET request, which caches, crawlers and prefetching may trigger.
- Storing API tokens in plain text in the database.
- Echoing PHP warnings or stack traces into JSON responses, which breaks clients and leaks details.
- Making breaking changes to an existing version instead of releasing a new one.
Frequently asked questions
Should I use PUT or PATCH for updates?
Use PUT when the client sends the complete resource to replace it, and PATCH when it sends only the fields that change. Many APIs offer PATCH alone because clients rarely want to resend everything.
Do I need a framework to build a REST API in PHP?
No, as this guide shows. A framework such as Laravel adds routing, validation and authentication packages that save time on larger APIs.
What is the difference between REST and GraphQL?
REST exposes many URLs, one per resource. GraphQL usually exposes one endpoint where the client describes exactly which fields it wants in a query.
How should I document my API?
The OpenAPI Specification is a widely used format for describing endpoints, parameters and responses, and many tools generate interactive documentation from it.