บทที่ 8: API & REST
“ท่อน้ำเชื่อมห้องครัวกับถังเก็บน้ำ เหมือน API เชื่อม Frontend กับ Database”
The Blueprint (พิมพ์เขียว)
Section titled “The Blueprint (พิมพ์เขียว)”เว็บไซต์ไม่ได้ทำงานโดดเดี่ยว มันต้อง:
- ดึงข้อมูลจาก Database
- ส่งข้อมูลไปบันทึก
- เรียกใช้บริการภายนอก (Payment, Email)
API = ท่อน้ำ ที่ส่งข้อมูลไปมาระหว่าง Frontend กับ Backend
The Construction Site (หน้างานก่อสร้าง)
Section titled “The Construction Site (หน้างานก่อสร้าง)”🔌 API คืออะไร?
Section titled “🔌 API คืออะไร?”API (Application Programming Interface) = ช่องทางสื่อสารมาตรฐาน
Frontend (Browser) ──── API ───── Backend (Server) │ │ │ "ขอรายการสินค้าหน่อย" │ │ ─────────────────────────────────▶ │ │ │ │ "นี่ครับ: [{...}, {...}]" │ │ ◀───────────────────────────────── │📤 HTTP Methods
Section titled “📤 HTTP Methods”| Method | หน้าที่ | ตัวอย่าง |
|---|---|---|
| GET | อ่านข้อมูล | ดูรายการสินค้า |
| POST | สร้างใหม่ | เพิ่มสินค้า |
| PUT/PATCH | แก้ไข | อัปเดตราคา |
| DELETE | ลบ | ลบสินค้า |
📊 HTTP Status Codes
Section titled “📊 HTTP Status Codes”| Code | ความหมาย | เปรียบเทียบ |
|---|---|---|
| 200 | OK | สำเร็จ ✅ |
| 201 | Created | สร้างเสร็จแล้ว |
| 400 | Bad Request | คำขอผิด |
| 401 | Unauthorized | ไม่มีสิทธิ์ |
| 404 | Not Found | หาไม่เจอ |
| 500 | Server Error | เซิร์ฟเวอร์พัง |
Material Selection (เลือกสเปกวัสดุ)
Section titled “Material Selection (เลือกสเปกวัสดุ)”🔧 Next.js API Routes
Section titled “🔧 Next.js API Routes”import { NextResponse } from 'next/server';
export async function GET() { const products = await db.product.findMany(); return NextResponse.json(products);}
export async function POST(request: Request) { const body = await request.json(); const product = await db.product.create({ data: body }); return NextResponse.json(product, { status: 201 });}📡 Fetching Data
Section titled “📡 Fetching Data”// ฝั่ง Frontendasync function getProducts() { const response = await fetch('/api/products'); if (!response.ok) throw new Error('Failed to fetch'); return response.json();}Architect’s Note (บันทึกสถาปนิก)
Section titled “Architect’s Note (บันทึกสถาปนิก)”⚠️ ข้อควรระวัง
Section titled “⚠️ ข้อควรระวัง”- Validate Input — ตรวจสอบข้อมูลก่อนประมวลผลเสมอ
- Error Handling — จัดการ Error ให้ดี ไม่ส่ง Stack Trace ให้ Client
- Rate Limiting — ป้องกัน API ถูกเรียกมากเกินไป
💡 Best Practices
Section titled “💡 Best Practices”- ใช้ RESTful conventions —
/products,/products/123 - ส่ง Status Codes ที่ถูกต้อง
- ใช้ TypeScript สำหรับ Type-safe API