การสร้าง API ด้วย FastAPI
FastAPI คืออะไร?
หัวข้อที่มีชื่อว่า “FastAPI คืออะไร?”ถ้าคุณมาจากโลก Node.js คุณน่าจะคุ้นเคยกับรูปแบบนี้แล้ว: เฟรมเวิร์กที่ map HTTP verb และ URL path ไปยัง handler function, จัดการการ parse request และส่งคืน JSON response FastAPI ทำสิ่งเดียวกันนี้สำหรับ Python แต่มีความสามารถพิเศษติดมาด้วย
FastAPI สร้างบนสองไลบรารีหลักที่คุณจะได้รู้จัก:
- Starlette — ASGI web toolkit (เทียบเท่ากับ
httpmodule ของ Node แต่รองรับ async) - Pydantic — ไลบรารีสำหรับ data validation ที่ใช้ Python type hints (คิดว่าเป็น Zod + class-transformer รวมกัน)
ผลลัพธ์คือเฟรมเวิร์กที่สร้าง OpenAPI docs อัตโนมัติ, ตรวจสอบ request body และ query parameter โดยไม่ต้องเขียน boilerplate, และรันแบบ async เต็มรูปแบบโดยค่าเริ่มต้น
FastAPI vs Express vs NestJS
หัวข้อที่มีชื่อว่า “FastAPI vs Express vs NestJS”// Express — ทำทุกอย่างเองconst express = require('express');const app = express();app.use(express.json());
app.get('/items/:id', (req, res) => { const id = Number(req.params.id); // แปลงประเภทเอง if (isNaN(id)) return res.status(422).json({ error: 'bad id' }); res.json({ id, name: 'Widget' });});
app.listen(3000);
// NestJS — decorators + DI// @Get(':id') findOne(@Param('id') id: string) { ... }# FastAPI — type hints ทำงานแทนfrom fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")async def get_item(item_id: int): # แปลง int + ส่ง 422 อัตโนมัติ return {"id": item_id, "name": "Widget"}
# รันด้วย:# uvicorn main:app --reload# Docs ที่: http://localhost:8000/docsเปรียบเทียบฟีเจอร์หลัก:
| ฟีเจอร์ | Express | NestJS | FastAPI |
|---|---|---|---|
| Type safety | Manual / TS compiler | TS + class-validator | Python type hints |
| Validation | Manual / Joi / Zod | class-validator | Pydantic (อัตโนมัติ) |
| Async model | Callbacks / Promises | Promises / Observables | async/await (ASGI) |
| OpenAPI docs | swagger-jsdoc | @nestjs/swagger | Built-in อัตโนมัติ |
| DI container | ไม่มีใน core | ใช่ (IoC) | Depends() (เบาๆ) |
| Performance | เร็ว | ปานกลาง | เร็วมาก (Starlette) |
สิ่งที่เราจะสร้าง
หัวข้อที่มีชื่อว่า “สิ่งที่เราจะสร้าง”ตลอดโมดูลนี้เราจะสร้าง Items API ขนาดเล็ก ที่เป็น CRUD service แบบที่คุณน่าจะเคยสร้างมาแล้วหลายครั้งใน Node ระหว่างนั้นเราจะครอบคลุม:
- โครงสร้างโปรเจกต์และการเริ่มต้น
- Routing, path params และ query params
- Pydantic models สำหรับ request/response schema
- Validation อัตโนมัติและข้อจำกัด
- Response models และ status codes
- Dependency injection ด้วย
Depends - Middleware และ CORS
- Error handling ด้วย
HTTPException - การเชื่อมต่อฐานข้อมูลด้วย SQLAlchemy
- Testing ด้วย
TestClient+ pytest
รันที่เครื่องตัวเอง — ต้องการ FastAPI + server ติดตั้ง:
pip install fastapi uvicorn[standard] pydantic sqlalchemy pytest httpx