#API Architecture Style คืออะไร

API Architecture Style คือรูปแบบการกำหนดวิธีที่ระบบสื่อสารกันผ่าน API ครอบคลุมโครงสร้างทรัพยากร รูปแบบข้อความ โปรโตคอล การจัดการสถานะ และรูปแบบการโต้ตอบระหว่างผู้ให้บริการและผู้เรียกใช้งาน การเลือกสไตล์ส่งผลต่อประสิทธิภาพ ความยืดหยุ่น การบำรุงรักษา และความสามารถในการขยายระบบ

หมายเหตุ: REST เป็น architectural style; GraphQL เป็น query language และ runtime สำหรับ API; gRPC เป็น RPC framework; SOAP เป็น messaging protocol; WebSocket เป็น communication protocol และ event-driven เป็น interaction pattern จึงไม่ใช่สิ่งที่อยู่ในหมวดอนุกรมวิธานเดียวกันทั้งหมด แต่สามารถเปรียบเทียบเป็นแนวทางการออกแบบ API ในทางปฏิบัติได้

#1. REST (Representational State Transfer)

REST ใช้ resource เป็นศูนย์กลาง ระบุผ่าน URI และใช้ HTTP methods เช่น GET, POST, PUT, PATCH และ DELETE โดยทั่วไปสื่อสารด้วย JSON

GET /api/products/42 HTTP/1.1
Accept: application/json
{"id":42,"name":"Keyboard","price":1290}

จุดเด่น: เข้าใจง่าย ใช้ HTTP ecosystem ได้ดี รองรับ caching และเหมาะกับ CRUD API

ข้อควรระวัง: บางกรณีต้องเรียกหลาย endpoint หรือรับข้อมูลเกินความจำเป็น ควรออกแบบ pagination, filtering, versioning และ error responses ให้ชัดเจน

#2. GraphQL

GraphQL ให้ client ระบุฟิลด์ที่ต้องการได้ใน query เดียว และมี schema แบบ strongly typed

query {
  product(id: "42") {
    name
    price
  }
}

จุดเด่น: ลด over-fetching สำหรับหน้าจอที่ต้องใช้ข้อมูลเฉพาะชุด รวมข้อมูลจากหลายแหล่งผ่าน schema เดียว

ข้อควรระวัง: ต้องจัดการ query complexity, N+1 queries, authorization รายฟิลด์ และ caching ให้เหมาะสม

#3. gRPC (Remote Procedure Call)

gRPC นิยมใช้ Protocol Buffers นิยาม service และ message และมักใช้ HTTP/2 เป็น transport

syntax = "proto3";

service ProductService {
  rpc GetProduct (ProductRequest) returns (ProductReply);
}

message ProductRequest { int64 id = 1; }
message ProductReply {
  int64 id = 1;
  string name = 2;
  double price = 3;
}

จุดเด่น: สัญญา API ชัดเจน รองรับ code generation และ streaming เหมาะกับ service-to-service communication

ข้อควรระวัง: การเรียกโดยตรงจากเว็บเบราว์เซอร์มักต้องใช้ gRPC-Web หรือ gateway และต้องดูแลความเข้ากันได้ของ schema

#4. SOAP (Simple Object Access Protocol)

SOAP เป็น protocol สำหรับแลกเปลี่ยนข้อความ XML และมักใช้ WSDL นิยามสัญญาบริการ เหมาะกับระบบองค์กรที่ต้องการมาตรฐาน WS-* บางประเภท

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetProduct xmlns="urn:example:products">
      <id>42</id>
    </GetProduct>
  </soap:Body>
</soap:Envelope>

จุดเด่น: สัญญาการสื่อสารและมาตรฐาน enterprise ที่มีอยู่แล้ว

ข้อควรระวัง: ข้อความ XML และชุดมาตรฐานอาจเพิ่มความซับซ้อน

#5. WebSocket

WebSocket ให้ client และ server ส่งข้อความสองทางผ่าน connection ที่คงอยู่ เหมาะกับ chat, live dashboard และ collaborative editing

const socket = new WebSocket('wss://example.com/live');
socket.addEventListener('message', event => {
  console.log(JSON.parse(event.data));
});

จุดเด่น: ส่งข้อมูลแบบ real-time สองทางได้โดยไม่ต้อง polling ตลอดเวลา

ข้อควรระวัง: ต้องจัดการ reconnect, heartbeat, authentication, backpressure และการ scale connections

#6. Event-Driven APIs และ Webhooks

Event-driven communication ให้ผู้ผลิตเหตุการณ์ส่ง event ไปยัง broker หรือ subscriber ส่วน webhook เป็น HTTP callback ที่ส่งเมื่อเกิดเหตุการณ์

{
  "event_id": "evt_001",
  "type": "order.created",
  "occurred_at": "2026-10-13T14:00:00Z",
  "data": {"order_id": 101}
}

จุดเด่น: ลด coupling เชิงเวลา รองรับงาน asynchronous และการกระจายเหตุการณ์ไปหลายระบบ

ข้อควรระวัง: ต้องออกแบบ idempotency, retries, ordering, dead-letter queue, event versioning และ observability; สำหรับ webhook ควรตรวจสอบลายเซ็นและป้องกัน replay

#7. เปรียบเทียบแนวทาง

แนวทาง รูปแบบหลัก เหมาะกับ ประเด็นที่ต้องดูแล
REST Resource + HTTP Public API, CRUD, mobile backend Endpoint design, pagination
GraphQL Client-defined queries UI ที่ต้องเลือกข้อมูลละเอียด Query cost, N+1, authorization
gRPC Typed RPC Internal microservices Browser support, schema evolution
SOAP XML messaging Legacy/enterprise integration Complexity, WS-* configuration
WebSocket Bidirectional persistent connection Chat, real-time dashboard Connection lifecycle, scaling
Event-driven / Webhook Async event notifications Orders, payment notifications, integration Delivery guarantees, retries, idempotency

#8. แนวทางเลือกใช้

  1. Public CRUD API: เริ่มจาก REST หากไม่มีข้อกำหนดพิเศษ
  2. Frontend ที่ต้องรวมข้อมูลหลายแหล่ง: พิจารณา GraphQL
  3. Internal service-to-service ที่เน้น contract และ streaming: พิจารณา gRPC
  4. เชื่อมต่อระบบองค์กรเดิมที่ใช้ WS-*: ใช้ SOAP ตามสัญญาที่ระบบกำหนด
  5. ต้องส่งข้อมูลสองทางทันที: ใช้ WebSocket
  6. ระบบที่ตอบสนองต่อเหตุการณ์และไม่ต้องรอผลทันที: ใช้ event-driven messaging หรือ webhook

ระบบจริงสามารถผสมหลายแนวทางได้ เช่น REST สำหรับ public API, gRPC สำหรับ internal services, WebSocket สำหรับ live updates และ message broker สำหรับ event processing

#9. Workshop: REST API อย่างง่ายด้วย Express.js

เตรียม Node.js แล้วสร้างโปรเจกต์:

mkdir api-style-workshop && cd api-style-workshop
npm init -y
npm install express

สร้าง server.js:

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

const products = [{ id: 1, name: 'Keyboard', price: 1290 }];

app.get('/api/products', (req, res) => res.json(products));
app.get('/api/products/:id', (req, res) => {
  const product = products.find(p => p.id === Number(req.params.id));
  if (!product) return res.status(404).json({ error: 'Product not found' });
  res.json(product);
});
app.post('/api/products', (req, res) => {
  const { name, price } = req.body;
  if (typeof name !== 'string' || !name.trim() || typeof price !== 'number' || !Number.isFinite(price) || price < 0) {
    return res.status(400).json({ error: 'Invalid product data' });
  }
  const product = { id: Math.max(0, ...products.map(p => p.id)) + 1, name: name.trim(), price };
  products.push(product);
  res.status(201).location(`/api/products/${product.id}`).json(product);
});

app.listen(3000, () => console.log('API running on port 3000'));

ทดลอง:

node server.js
curl http://localhost:3000/api/products
curl -X POST http://localhost:3000/api/products \
  -H 'Content-Type: application/json' \
  -d '{"name":"Mouse","price":590}'

ตัวอย่างนี้เก็บข้อมูลในหน่วยความจำเพื่อการเรียนรู้ ยังไม่ใช่ production-ready API; ระบบจริงควรเพิ่มฐานข้อมูล การพิสูจน์ตัวตน การกำหนดสิทธิ์ rate limiting การทดสอบ และ monitoring

#10. สรุป

ไม่มี API style ใดดีที่สุดในทุกสถานการณ์ ควรเลือกจากลักษณะการโต้ตอบ (request/response, streaming หรือ asynchronous), ประเภท client, latency, data contract, security และความพร้อมของทีม โดยสามารถออกแบบแบบ hybrid เพื่อใช้ข้อดีของแต่ละแนวทางร่วมกันได้

#แหล่งศึกษาเพิ่มเติม