การสร้าง API Endpoint สำหรับ CRUD (Create, Read, Update, Delete)
ในบทเรียนก่อนหน้านี้ เราได้เรียนรู้พื้นฐานเกี่ยวกับการสร้าง API ด้วย PHP ตั้งแต่การรับส่ง Parameter, การใช้งาน JSON, การจัดการ Error และ HTTP Status Codes ในบทนี้ เราจะมาต่อยอดความรู้โดยการสร้าง API Endpoint ที่สามารถจัดการข้อมูลพื้นฐานได้ นั่นคือการทำ CRUD (Create, Read, Update, Delete)
CRUD เป็นคำย่อที่ใช้เรียกการดำเนินการพื้นฐานที่เกี่ยวข้องกับการจัดการข้อมูล ซึ่งประกอบไปด้วย:
- Create: สร้างข้อมูลใหม่
- Read: อ่านข้อมูลที่มีอยู่
- Update: แก้ไขข้อมูลที่มีอยู่
- Delete: ลบข้อมูลที่มีอยู่
การสร้าง API Endpoint สำหรับ CRUD จะช่วยให้เราสามารถจัดการข้อมูลได้อย่างมีประสิทธิภาพและเป็นระบบ โดยแต่ละ Operation จะถูก Mapping กับ HTTP Method ที่เหมาะสม
HTTP Methods กับ CRUD
HTTP Methods ที่เราจะใช้สำหรับ CRUD คือ:
- GET: ใช้สำหรับ Read (ดึงข้อมูล)
- POST: ใช้สำหรับ Create (สร้างข้อมูลใหม่)
- PUT: ใช้สำหรับ Update (แก้ไขข้อมูลทั้งหมดของ Resource)
- DELETE: ใช้สำหรับ Delete (ลบข้อมูล)
สำคัญ: การเลือกใช้ HTTP Method ที่ถูกต้องมีความสำคัญต่อการออกแบบ API ที่ดีและเป็นไปตามมาตรฐาน
ตัวอย่าง: สร้าง API Endpoint สำหรับจัดการ "สินค้า" (Products)
สมมติว่าเราต้องการสร้าง API สำหรับจัดการข้อมูลสินค้า เราจะกำหนด Endpoint และ HTTP Method ดังนี้:
- GET /products: ดึงข้อมูลสินค้าทั้งหมด
- GET /products/{id}: ดึงข้อมูลสินค้าตาม ID
- POST /products: สร้างสินค้าใหม่
- PUT /products/{id}: แก้ไขข้อมูลสินค้าตาม ID (แก้ไขทั้งหมด)
- DELETE /products/{id}: ลบสินค้าตาม ID
โดยที่ {id} คือ Parameter ที่ใช้ระบุ ID ของสินค้า
ตัวอย่างโค้ด PHP (อย่างง่าย)
ข้อควรจำ: โค้ดตัวอย่างนี้เป็นเพียงตัวอย่างพื้นฐานเพื่อแสดงแนวคิด CRUD เท่านั้น ในบทต่อๆ ไป เราจะเรียนรู้วิธีการเชื่อมต่อกับฐานข้อมูลและการจัดการข้อมูลที่ซับซ้อนยิ่งขึ้น
สมมติว่าเรามี Array ที่เก็บข้อมูลสินค้า:
<?php
$products = [
1 => ['id' => 1, 'name' => 'Product A', 'price' => 100],
2 => ['id' => 2, 'name' => 'Product B', 'price' => 200],
];
header('Content-Type: application/json');
// กำหนด HTTP Method จาก Request
$method = $_SERVER['REQUEST_METHOD'];
// แยก URL เพื่อหา Endpoint และ ID (ถ้ามี)
$uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$endpoint = $uri[0]; // เช่น 'products'
$id = isset($uri[1]) ? (int)$uri[1] : null; // เช่น 1 หรือ null
// Router
if ($endpoint == 'products') {
switch ($method) {
case 'GET':
if ($id) {
// GET /products/{id}
if (isset($products[$id])) {
echo json_encode($products[$id]);
} else {
http_response_code(404); // Not Found
echo json_encode(['message' => 'Product not found']);
}
} else {
// GET /products
echo json_encode(array_values($products)); // แปลง Index Array เป็น Sequential Array
}
break;
case 'POST':
// POST /products
// (ตัวอย่างง่ายๆ ยังไม่มีการตรวจสอบข้อมูล)
$name = $_POST['name'] ?? null;
$price = $_POST['price'] ?? null;
if($name && $price){
$newId = max(array_keys($products)) + 1;
$products[$newId] = ['id' => $newId, 'name' => $name, 'price' => (int)$price];
http_response_code(201); // Created
echo json_encode($products[$newId]);
} else {
http_response_code(400); // Bad Request
echo json_encode(['message' => 'Missing name or price']);
}
break;
case 'PUT':
// PUT /products/{id}
if ($id && isset($products[$id])) {
// (ตัวอย่างง่ายๆ ยังไม่มีการตรวจสอบข้อมูล)
parse_str(file_get_contents("php://input"), $_PUT); // อ่านข้อมูลจาก Request Body
$name = $_PUT['name'] ?? null;
$price = $_PUT['price'] ?? null;
if($name && $price){
$products[$id] = ['id' => $id, 'name' => $name, 'price' => (int)$price];
echo json_encode($products[$id]);
} else {
http_response_code(400); // Bad Request
echo json_encode(['message' => 'Missing name or price']);
}
} else {
http_response_code(404); // Not Found
echo json_encode(['message' => 'Product not found']);
}
break;
case 'DELETE':
// DELETE /products/{id}
if ($id && isset($products[$id])) {
unset($products[$id]);
http_response_code(204); // No Content (สำเร็จ แต่ไม่มีข้อมูลส่งกลับ)
} else {
http_response_code(404); // Not Found
echo json_encode(['message' => 'Product not found']);
}
break;
default:
http_response_code(405); // Method Not Allowed
echo json_encode(['message' => 'Method Not Allowed']);
break;
}
} else {
http_response_code(404); // Not Found
echo json_encode(['message' => 'Endpoint not found']);
}
?>
คำอธิบายโค้ด:
$products: Array ที่เก็บข้อมูลสินค้า (ในความเป็นจริง ข้อมูลควรอยู่ในฐานข้อมูล)header('Content-Type: application/json');: กำหนด Content Type เป็น JSON$_SERVER['REQUEST_METHOD']: ตัวแปรที่เก็บ HTTP Method ที่ใช้ในการ Request$_SERVER['REQUEST_URI']: ตัวแปรที่เก็บ URI ของ Requestexplode('/', trim($_SERVER['REQUEST_URI'], '/')): แยก URI ออกเป็นส่วนๆ เพื่อหา Endpoint และ IDjson_encode(): ฟังก์ชันสำหรับแปลงข้อมูล PHP เป็น JSON Stringhttp_response_code(): ฟังก์ชันสำหรับกำหนด HTTP Status Code$_POST: Array ที่เก็บข้อมูลที่ส่งมาทาง POST Requestfile_get_contents("php://input")และparse_str(): ใช้สำหรับอ่านข้อมูลที่ส่งมาทาง PUT Request (ซึ่งไม่ได้อยู่ใน$_POST)
การทดสอบ API Endpoint
เราสามารถทดสอบ API Endpoint ได้โดยใช้เครื่องมือต่างๆ เช่น Postman หรือ cURL
ตัวอย่างการใช้ cURL:
- GET /products:
curl http://localhost/products - GET /products/1:
curl http://localhost/products/1 - POST /products:
curl -X POST -d "name=Product C&price=300" http://localhost/products - PUT /products/1:
curl -X PUT -d "name=Product A Updated&price=150" http://localhost/products/1 - DELETE /products/1:
curl -X DELETE http://localhost/products/1
สรุป
ในบทนี้ เราได้เรียนรู้วิธีการสร้าง API Endpoint สำหรับ CRUD โดยใช้ HTTP Methods ที่เหมาะสม และได้เห็นตัวอย่างโค้ด PHP อย่างง่ายสำหรับการจัดการข้อมูลสินค้า ในบทต่อไป เราจะมาเรียนรู้วิธีการเชื่อมต่อกับฐานข้อมูล MySQL เพื่อให้ API ของเราสามารถจัดการข้อมูลได้อย่างมีประสิทธิภาพและเป็นระบบมากยิ่งขึ้น