<coded>


PHP REST API Example with JSON

September 18, 2022

Want to build a simple PHP REST API that returns JSON responses?
This step-by-step guide will show you exactly how to create a lightweight REST API using pure PHP — no frameworks required.


🚀 What We’ll Build

A minimal REST API with PHP that:


🛠️ Step 1: Database Setup

Create a table named users with some sample data.

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL
);

INSERT INTO users (name, email) VALUES
('Alice Johnson', 'alice@example.com'),
('Bob Smith', 'bob@example.com'),
('Charlie Brown', 'charlie@example.com');

🛠️ Step 2: API Structure

We’ll use a single file api.php that handles different HTTP methods:


🛠️ Step 3: PHP REST API Script (api.php)

<?php
header("Content-Type: application/json; charset=UTF-8");

// Database connection
$host = "localhost";
$db   = "test_db";
$user = "root";
$pass = "";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}

// Helper: parse input JSON
function get_input() {
    return json_decode(file_get_contents("php://input"), true);
}

$method = $_SERVER["REQUEST_METHOD"] ?? "GET";

switch($method) {
    // GET /api.php
    case "GET":
        $stmt = $pdo->query("SELECT * FROM users");
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($users);
        break;

    // POST /api.php
    case "POST":
        $data = get_input();
        if(!isset($data["name"], $data["email"])) {
            http_response_code(400);
            echo json_encode(["error" => "Missing name or email"]);
            exit;
        }
        $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->execute([$data["name"], $data["email"]]);
        echo json_encode(["message" => "User created", "id" => $pdo->lastInsertId()]);
        break;

    // PUT /api.php?id=1
    case "PUT":
        $id = $_GET["id"] ?? null;
        $data = get_input();
        if(!$id || !isset($data["name"], $data["email"])) {
            http_response_code(400);
            echo json_encode(["error" => "Missing id, name or email"]);
            exit;
        }
        $stmt = $pdo->prepare("UPDATE users SET name=?, email=? WHERE id=?");
        $stmt->execute([$data["name"], $data["email"], $id]);
        echo json_encode(["message" => "User updated"]);
        break;

    // DELETE /api.php?id=1
    case "DELETE":
        $id = $_GET["id"] ?? null;
        if(!$id) {
            http_response_code(400);
            echo json_encode(["error" => "Missing id"]);
            exit;
        }
        $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
        $stmt->execute([$id]);
        echo json_encode(["message" => "User deleted"]);
        break;

    default:
        http_response_code(405);
        echo json_encode(["error" => "Method not allowed"]);
        break;
}
?>

🛠️ Step 4: Testing the API

Use cURL or Postman to test each route.

Get all users:

curl http://localhost/api.php

Add new user:

curl -X POST -H "Content-Type: application/json" \
-d '{"name":"David Miller","email":"david@example.com"}' \
http://localhost/api.php

Update a user:

curl -X PUT -H "Content-Type: application/json" \
-d '{"name":"David M.","email":"david.m@example.com"}' \
"http://localhost/api.php?id=4"

Delete a user:

curl -X DELETE http://localhost/api.php?id=4

🎯 How It Works

  1. The script reads the HTTP method (GET, POST, PUT, DELETE).
  2. Depending on the method, it runs the correct SQL query.
  3. All responses are returned as JSON.

📈 SEO Optimization Tips


✅ Final Thoughts

This tutorial showed you how to create a minimal REST API in PHP that returns JSON. From here, you can extend it with:

Did you find this useful? Please rate this post: