Sublimity Dev Blog

Articles and Tips in Web Development , Programming , SEO and Linux

Recent Posts

Published On

Learn How to Build a Simple RESTful API With PHP

Creating a REST API with PHP is a foundational skill for modern web development. REST (Representational State Transfer) is a widely-used architecture that allows different systems to communicate over HTTP. In this tutorial, you'll learn how to build a simple and clean PHP RESTful API from scratch using native PHP — no frameworks required.

What Is a REST API?

A REST API allows your backend to expose resources (like users, posts, or products) via standard HTTP methods:

  • GET – Retrieve data
  • POST – Create data
  • PUT – Update data
  • DELETE – Remove data

Basic Project Structure

Let’s create a structure like this:

/api
  ├── config/
  │   └── database.php
  ├── objects/
  │   └── Product.php
  ├── product/
  │   ├── read.php
  │   ├── create.php
  │   └── delete.php
  └── index.php

Connecting to the Database

<?php
// /api/config/database.php
class Database {
    private $host = "localhost";
    private $db_name = "myapi";
    private $username = "root";
    private $password = "";
    public $conn;

    public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . 
                $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        } catch(PDOException $exception) {
            echo "Connection error: " . $exception->getMessage();
        }
        return $this->conn;
    }
}
?>

Creating a Simple Read Endpoint

<?php
// /api/product/read.php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include_once '../config/database.php';

$database = new Database();
$db = $database->getConnection();

$query = "SELECT id, name, price FROM products";
$stmt = $db->prepare($query);
$stmt->execute();

$products = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    $products[] = [
        "id" => $id,
        "name" => $name,
        "price" => $price
    ];
}

echo json_encode($products);
?>

This endpoint returns all products in JSON format. You can test it using Postman or directly in the browser.

Testing the API

Use the command below in your terminal to test the endpoint:

curl http://localhost/api/product/read.php

If configured correctly, you’ll receive a JSON response like:

[
  {
    "id": 1,
    "name": "Book",
    "price": 15.99
  },
  {
    "id": 2,
    "name": "Pen",
    "price": 1.25
  }
]

Conclusion

Building a RESTful API using PHP is a practical way to learn both backend logic and web standards. While this tutorial used raw PHP for clarity, you can easily apply the same concepts using frameworks like Laravel or Slim for more complex projects.

You now have a working understanding of REST principles, how to structure your API, and how to build and test basic endpoints. Keep going by adding authentication, input validation, and full CRUD support.