Skip to content
OurLogicLearn • Grow • Lead
Home Blog Interview Notes Videos News Discussions Polls & voting Pro Pass
Trending topics

Build your first REST API in plain PHP

Rohan Gupta 12 Sep 2026 1 min read 542 4 (2)

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.

2 Share:

Feedback & comments (2)

Rohan Gupta 18 h ago

Helpful, thanks. Please write a follow-up on the advanced topics.

Priya Nair 16 h ago

Great summary. It would be nice to add one more example with real data.

Rate this post:
Comments are moderated before they appear.