Build your first REST API in plain PHP
A REST API is just a set of URLs that accept requests and return JSON. Here is the smallest useful version in PHP.
<?php
header('Content-Type: application/json');
$pdo = new PDO('mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4', 'user', 'pass');
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$st = $pdo->prepare('SELECT id, name, price FROM products WHERE id = ?');
$st->execute([(int)($_GET['id'] ?? 0)]);
echo json_encode($st->fetch(PDO::FETCH_ASSOC) ?: ['error' => 'Not found']);
}
Next steps
- Return proper status codes (404, 422, 201).
- Validate every input.
- Add authentication with API tokens.
Feedback & comments (2)
Rohan Gupta
Helpful, thanks. Please write a follow-up on the advanced topics.
Priya Nair
Great summary. It would be nice to add one more example with real data.