Build a Simple REST API in PHP (GET + POST)
Create a basic REST-style API endpoint with routing, JSON responses, and validation.
Megan Parker
October 30, 2025
5.5k221
Let’s build a small API endpoint in PHP that returns and creates posts.
Goal endpoints
- GET /api/posts
- POST /api/posts
Step 1: Simple router using REQUEST_METHOD
File: api.php
<?php
require_once "config.php";
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
$rows = $pdo->query("SELECT id, title, body FROM posts ORDER BY id DESC")->fetchAll();
echo json_encode($rows);
exit;
}
if ($method === 'POST') {
$input = json_decode(file_get_contents("php://input"), true);
$title = trim($input['title'] ?? '');
$body = trim($input['body'] ?? '');
if ($title === '' || $body === '') {
http_response_code(400);
echo json_encode(["error" => "title and body are required"]);
exit;
}
$stmt = $pdo->prepare("INSERT INTO posts (title, body) VALUES (:title, :body)");
$stmt->execute(["title" => $title, "body" => $body]);
echo json_encode(["status" => "created"]);
exit;
}
http_response_code(405);
echo json_encode(["error" => "Method not allowed"]);
?>
Why we used php://input
When clients send JSON, it does not appear in $_POST. You read raw body and decode it.
Next: Security basics, XSS and CSRF protection in PHP forms.
#PHP#API#Intermediate