Mon. Jun 2nd, 2025
RESTful API คืออะไร? พร้อมตัวอย่างโค้ดด้วย Node.js และ PHPRESTful API คืออะไร? พร้อมตัวอย่างโค้ดด้วย Node.js และ PHP
Spread the love

ในยุคที่ระบบซอฟต์แวร์มักต้องเชื่อมต่อกันผ่านอินเทอร์เน็ต ไม่ว่าจะเป็นเว็บแอปพลิเคชัน แอปมือถือ หรือระบบหลังบ้าน (backend) การใช้ API (Application Programming Interface) จึงเป็นสิ่งสำคัญมาก โดยเฉพาะ RESTful API ที่เป็นมาตรฐานในการออกแบบ API ซึ่งได้รับความนิยมสูงสุดในปัจจุบัน


✅ RESTful API คืออะไร?

REST (Representational State Transfer) เป็นรูปแบบของการออกแบบ API โดยใช้หลักการของ HTTP ที่เราคุ้นเคยกัน เช่น GET, POST, PUT, DELETE เพื่อสื่อสารและจัดการกับข้อมูลในรูปแบบที่เป็นมาตรฐาน

ตัวอย่างเช่น:

Methodความหมายตัวอย่าง URLใช้ทำอะไร
GETอ่านข้อมูล/usersดึงรายชื่อผู้ใช้ทั้งหมด
GETอ่านข้อมูล/users/1ดึงข้อมูลผู้ใช้ ID = 1
POSTเพิ่มข้อมูล/usersเพิ่มผู้ใช้ใหม่
PUTแก้ไขข้อมูล/users/1แก้ไขข้อมูลผู้ใช้ ID = 1
DELETEลบข้อมูล/users/1ลบผู้ใช้ ID = 1

🔧 ตัวอย่างโค้ด RESTful API ด้วย Node.js (Express.js)

ติดตั้ง Express ก่อน:

npm init -y
npm install express

สร้างไฟล์ app.js:

const express = require('express');
const app = express();
app.use(express.json());

let users = [
  { id: 1, name: "John Doe" },
  { id: 2, name: "Jane Smith" }
];

// GET - ดึงผู้ใช้ทั้งหมด
app.get('/users', (req, res) => {
  res.json(users);
});

// GET - ดึงผู้ใช้ตาม ID
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id == req.params.id);
  if (user) res.json(user);
  else res.status(404).send("User not found");
});

// POST - เพิ่มผู้ใช้
app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT - แก้ไขผู้ใช้
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id == req.params.id);
  if (user) {
    user.name = req.body.name;
    res.json(user);
  } else {
    res.status(404).send("User not found");
  }
});

// DELETE - ลบผู้ใช้
app.delete('/users/:id', (req, res) => {
  users = users.filter(u => u.id != req.params.id);
  res.status(204).send();
});

app.listen(3000, () => console.log('Server started on port 3000'));

รันเซิร์ฟเวอร์:

node app.js

🧰 ตัวอย่างโค้ด RESTful API ด้วย PHP (Vanilla PHP)

สร้างไฟล์ api.php:

<?php
header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));

$users = [
    1 => ['id' => 1, 'name' => 'John Doe'],
    2 => ['id' => 2, 'name' => 'Jane Smith']
];

switch ($method) {
    case 'GET':
        if (isset($uri[1]) && is_numeric($uri[1])) {
            $id = (int)$uri[1];
            if (isset($users[$id])) {
                echo json_encode($users[$id]);
            } else {
                http_response_code(404);
                echo json_encode(["error" => "User not found"]);
            }
        } else {
            echo json_encode(array_values($users));
        }
        break;

    case 'POST':
        $data = json_decode(file_get_contents("php://input"), true);
        $id = count($users) + 1;
        $users[$id] = ['id' => $id, 'name' => $data['name']];
        http_response_code(201);
        echo json_encode($users[$id]);
        break;

    case 'PUT':
        $id = (int)$uri[1];
        if (isset($users[$id])) {
            $data = json_decode(file_get_contents("php://input"), true);
            $users[$id]['name'] = $data['name'];
            echo json_encode($users[$id]);
        } else {
            http_response_code(404);
            echo json_encode(["error" => "User not found"]);
        }
        break;

    case 'DELETE':
        $id = (int)$uri[1];
        if (isset($users[$id])) {
            unset($users[$id]);
            http_response_code(204);
        } else {
            http_response_code(404);
            echo json_encode(["error" => "User not found"]);
        }
        break;

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

✅ แนะนำให้รันในเซิร์ฟเวอร์ท้องถิ่น เช่น XAMPP, Laragon หรือ PHP built-in server

php -S localhost:8000

จากนั้นเข้าผ่าน http://localhost:8000/api.php/users

🌐 RESTful API ใช้ในสถานการณ์ใดบ้าง?

  • แอปพลิเคชันมือถือ ต้องดึงข้อมูลจากเซิร์ฟเวอร์
  • Frontend SPA (React, Vue) ต้องคุยกับ backend
  • ระบบ IoT ที่ต้องเชื่อมต่อกับ backend
  • เว็บแอปแบบ microservices แบ่งบริการย่อยคุยกันด้วย REST

🎯 ข้อดีของ RESTful API

  • ใช้งานง่าย เข้าใจไม่ยาก (ใช้ HTTP มาตรฐาน)
  • รองรับได้ทุกภาษาและแพลตฟอร์ม
  • ใช้กับ Cloud, IoT, Mobile, Web ได้สบาย

🚨 ข้อควรระวัง

  • ต้องใส่ใจเรื่อง ความปลอดภัย เช่นการยืนยันตัวตน (Auth), การจำกัดสิทธิ์ (Role)
  • หากข้อมูลมีความซับซ้อนมาก บางครั้งอาจเหมาะกับ GraphQL มากกว่า REST
  • ต้องออกแบบ API route ให้มีมาตรฐาน สื่อความหมายได้ดี

สรุป

RESTful API เป็นเทคนิคสำคัญในการสื่อสารระหว่างระบบดิจิทัลต่าง ๆ ในโลกยุคใหม่ โดยอิงหลักการ HTTP ที่เข้าใจง่ายและนำไปใช้ได้อย่างยืดหยุ่น ตัวอย่างโค้ดทั้ง Node.js และ PHP ที่แสดงในบทความนี้สามารถนำไปปรับใช้ได้ทันทีหากคุณกำลังพัฒนาเว็บแอปหรือแอปมือถือ

Loading

By tikky

Leave a Reply

Your email address will not be published. Required fields are marked *