Build a REST API in Core PHP with PDO
Create a JSON endpoint with validation, prepared statements and consistent HTTP responses.
Keep a simple structure
api/public/index.php
src/Database.php
src/UserController.php
config/ (outside public web root)
Configure the document root to public/ where possible. Keep credentials outside public directories.
Connect with PDO
$pdo = new PDO('mysql:host=127.0.0.1;dbname=app;charset=utf8mb4',
getenv('DB_USER'),
getenv('DB_PASS'),
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
Use protected configuration or environment variables for secrets. Never commit production credentials.
Validate JSON input
$payload = json_decode(file_get_contents('php://input'), true);if (!is_array($payload)) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
$name = trim((string)($payload['name'] ?? ''));
if ($name === '') {
http_response_code(422);
echo json_encode(['error' => 'Name is required']);
exit;
}
Insert safely
$stmt = $pdo->prepare('INSERT INTO users (name) VALUES (:name)');$stmt->execute(['name' => $name]);
http_response_code(201);
header('Content-Type: application/json');
echo json_encode(['id' => (int)$pdo->lastInsertId()]);
Prepared statements separate SQL code from visitor data.
Production checklist
- Validate every field server-side.
- Restrict HTTP methods and configure CORS deliberately.
- Add authentication and authorization for private data.
- Do not expose SQL errors or stack traces.
- Use HTTPS, logging, rate limits and automated tests.
Try the concepts in a small project and verify version-specific details with official documentation.
More PHP resources