Friday, October 16, 2026 New tutorials published every day
Home
Tutorials
Core PHP PHP Course JavaScript React & Next.js Python WordPress Artificial Intelligence
Course
Lesson 1 — Start Here Course playlist Lesson notes & code
Projects
PHP Projects — all projects
More
About Contact Search Login
Core PHP

How to Build a Simple REST API in PHP from Scratch: Step-by-Step Guide

Build a simple REST API in PHP from scratch, step by step. No framework needed. Full code for GET, POST, PUT and DELETE endpoints with MySQL, JSON and testing.

How to Build a Simple REST API in PHP from Scratch: Step-by-Step Guide

To build a REST API in PHP from scratch, you create PHP files that read the request method (GET, POST, PUT or DELETE), work with a MySQL database using PDO, and return the result as JSON with the correct HTTP status code. You do not need any framework for a simple API — plain PHP, a database and clean code are enough to learn how APIs really work.

What Is a REST API, in Simple Words?

API stands for Application Programming Interface. A REST API is a way for two programs to talk to each other over the internet using simple HTTP requests. Your mobile app, your JavaScript frontend, or another website sends a request, and your PHP API answers with data, usually in JSON format.

Think of a restaurant. The customer is the app, the kitchen is your database, and the waiter is the API. The customer never enters the kitchen — the waiter takes the order and brings the food. That is what an API does between software and data.

REST APIs use the standard HTTP methods, and each method has a clear job:

MethodJobExample
GETRead dataGET /api/products — list all products
POSTCreate new dataPOST /api/products — add a product
PUTUpdate existing dataPUT /api/products/5 — update product 5
DELETERemove dataDELETE /api/products/5 — delete product 5

What You Need Before You Start

  • XAMPP, WAMP, or any server with PHP 7.4 or higher and MySQL
  • Basic PHP and PDO knowledge — if database connections are new to you, first read our guide on how to connect PHP with a MySQL database
  • Postman (free) or any tool to test API requests

Step 1: Create the Database and Table

Create a database named api_demo and a products table:

CREATE TABLE products (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  price DECIMAL(10,2) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Then add two or three sample products from the phpMyAdmin Insert tab — for example a wireless mouse, a keyboard and a USB hub — so you have data to test with.

Step 2: Create the Database Connection

Create a folder named api in your server folder, and inside it a file db.php:

<?php
$host = "localhost";
$dbname = "api_demo";
$username = "root";
$password = "";

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

Step 3: Create a Helper for JSON Responses

Every API response should be JSON, with a clear HTTP status code. Add this small helper in a file named helpers.php:

<?php
function sendJSON($data, $status = 200) {
    http_response_code($status);
    header("Content-Type: application/json");
    echo json_encode($data);
    exit;
}

Status codes matter. Use 200 for success, 201 when something new is created, 400 for bad input from the client, 404 when data is not found, and 500 for server errors. Apps that call your API depend on these codes.

Step 4: Build the Main API File

Now create index.php inside the api folder. This one file reads the method and the request, and handles all four operations:

<?php
require "db.php";
require "helpers.php";

$method = $_SERVER["REQUEST_METHOD"];
$id = $_GET["id"] ?? null;
$input = json_decode(file_get_contents("php://input"), true);

if ($method === "GET" && $id === null) {
    $products = $pdo->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
    sendJSON($products);
}

if ($method === "GET" && $id !== null) {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id = :id");
    $stmt->execute(["id" => $id]);
    $product = $stmt->fetch();
    if (!$product) sendJSON(["error" => "Product not found"], 404);
    sendJSON($product);
}

if ($method === "POST") {
    if (empty($input["name"]) || !isset($input["price"])) {
        sendJSON(["error" => "Name and price are required"], 400);
    }
    $stmt = $pdo->prepare("INSERT INTO products (name, price) VALUES (:name, :price)");
    $stmt->execute(["name" => $input["name"], "price" => $input["price"]]);
    sendJSON(["message" => "Product created", "id" => $pdo->lastInsertId()], 201);
}

if ($method === "PUT") {
    if ($id === null) sendJSON(["error" => "Product ID is required"], 400);
    $stmt = $pdo->prepare("UPDATE products SET name = :name, price = :price WHERE id = :id");
    $stmt->execute(["name" => $input["name"], "price" => $input["price"], "id" => $id]);
    sendJSON(["message" => "Product updated"]);
}

if ($method === "DELETE") {
    if ($id === null) sendJSON(["error" => "Product ID is required"], 400);
    $stmt = $pdo->prepare("DELETE FROM products WHERE id = :id");
    $stmt->execute(["id" => $id]);
    sendJSON(["message" => "Product deleted"]);
}

sendJSON(["error" => "Method not allowed"], 405);

Look at two important details. First, incoming JSON is read from the raw request body at the top of the file, because form data and JSON bodies arrive in different ways. Second, every database query uses prepared statements, so your API stays safe from SQL injection.

Step 5: Test Your API With Postman

Start your server and test each endpoint in Postman:

  • GET http://localhost/api/ — returns the full product list as JSON
  • GET http://localhost/api/?id=1 — returns one product
  • POST http://localhost/api/ with a JSON body like {"name": "Laptop Stand", "price": 1299} — creates a product
  • PUT http://localhost/api/?id=1 with a JSON body — updates product 1
  • DELETE http://localhost/api/?id=1 — deletes product 1

If each request returns the right JSON and status code, congratulations — your API works. The same API can now serve a website, an Android app, or an iPhone app, because all of them understand HTTP and JSON.

How to Make Your API Better and Safer

  • Add authentication. For private data, ask the client to send an API key or a token in the header, and check it before doing any work.
  • Validate everything: required fields, numeric prices, safe text lengths.
  • Never show raw errors. Return a simple JSON error message, and log the real error on the server.
  • Use clean URLs later. With a small .htaccess rewrite, /api/?id=1 can become /api/products/1. When your API grows, Laravel gives you routing, validation and authentication out of the box.

Frequently Asked Questions

Can I build a REST API in PHP without a framework?

Yes. Plain PHP with PDO can handle a complete REST API, as this guide shows. Frameworks like Laravel become helpful when the API grows large, but learning the raw version first teaches you how APIs truly work.

Why does my API return HTML instead of JSON?

Usually a PHP error or warning is printed before your JSON. Turn off error display on the page, log errors instead, and make sure you set the Content-Type: application/json header before any output.

What is the difference between an API and a website?

A website returns HTML pages for humans to read in a browser. An API returns raw data, usually JSON, for other programs to use. The same database can serve both.

How do I secure a PHP REST API?

Use HTTPS, prepared statements, input validation, token-based authentication for private endpoints, and a limit on requests per minute.

Conclusion

You have built a working REST API in pure PHP: a database, a PDO connection, one clean endpoint file, proper JSON and correct status codes. Practise by adding a search feature or a second table. Once this feels easy, frameworks will make much more sense — and so will full projects like our full-stack online examination system. Follow Coding Cush for one simple coding guide every day.

L
Written by

Lavkush K

Lav is a software developer with 5+ years of experience in the software industry, specialising in PHP and MySQL web development. Over the years he has built business websites, WordPress platforms and complete web applications — admin panels, login systems, dashboards and more. Through CodingCush, he turns that real project experience into simple, step-by-step tutorials with full working code, so students and beginners can learn by building real things, not just by reading theory.

0 Comments

Leave a Comment