প্রথম REST API তৈরি

লেসন ৩৬ / ৩৯

Setup Folder

api/
├── config/db.php
├── products.php
└── .htaccess

config/db.php

<?php
class DB {
    private static $conn = null;
    public static function get(): mysqli {
        if (self::$conn === null) {
            self::$conn = new mysqli("localhost", "root", "", "shop_db");
            if (self::$conn->connect_error) {
                http_response_code(500);
                exit(json_encode(["error" => "DB সংযোগ ব্যর্থ"]));
            }
            self::$conn->set_charset("utf8mb4");
        }
        return self::$conn;
    }
}
?>

products.php — প্রথম API

<?php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");

require_once "config/db.php";
$conn = DB::get();

$result = $conn->query("SELECT id, name, price, stock FROM products ORDER BY id DESC");

if (!$result) {
    http_response_code(500);
    echo json_encode(["success" => false, "error" => "Query ব্যর্থ"]);
    exit;
}

$products = $result->fetch_all(MYSQLI_ASSOC);

http_response_code(200);
echo json_encode([
    "success" => true,
    "data" => $products,
    "count" => count($products)
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
?>

Test

# Browser
http://localhost/api/products.php

# curl
curl http://localhost/api/products.php

# Response
{
    "success": true,
    "data": [
        {"id":1, "name":"ল্যাপটপ", "price":"75000.00", "stock":10},
        {"id":2, "name":"মাউস", "price":"500.00", "stock":50}
    ],
    "count": 2
}

Query Parameter

<?php
// ?search=ল্যাপটপ&limit=10
$search = $_GET["search"] ?? "";
$limit = min(100, max(1, (int)($_GET["limit"] ?? 10)));

if ($search) {
    $like = "%{$search}%";
    $stmt = $conn->prepare("SELECT * FROM products WHERE name LIKE ? LIMIT ?");
    $stmt->bind_param("si", $like, $limit);
} else {
    $stmt = $conn->prepare("SELECT * FROM products LIMIT ?");
    $stmt->bind_param("i", $limit);
}

$stmt->execute();
$products = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

echo json_encode(["success" => true, "data" => $products], JSON_UNESCAPED_UNICODE);
?>

একটি Product (by ID)

<?php
$id = (int)($_GET["id"] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    exit(json_encode(["error" => "Valid ID দিন"]));
}

$stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$product = $stmt->get_result()->fetch_assoc();

if (!$product) {
    http_response_code(404);
    exit(json_encode(["error" => "পাওয়া যায়নি"]));
}

echo json_encode(["success" => true, "data" => $product], JSON_UNESCAPED_UNICODE);
?>

মূল Concepts

  • Content-Type header
  • CORS header
  • HTTP status code (200, 400, 404, 500)
  • JSON_UNESCAPED_UNICODE (বাংলা)
  • Prepared statement
  • Input validation