FastAPI + MySQL + Docker Workshop Template เรียนรู้การสร้าง REST API พร้อม Database และ Frontend Integration
Workshop นี้ออกแบบมาเพื่อสอนนักศึกษาสร้างแอปพลิเคชันฝึกภาษาอังกฤษแบบ Full-Stack โดยใช้เทคโนโลยีที่ทันสมัย เหมาะสำหรับนักศึกษาที่กำลังทำ Term Project เกี่ยวกับ Vocabulary Learning, Language Practice:
- ✅ REST API Backend
- ✅ Database Integration (MySQL)
- ✅ Frontend-Backend Connection
- ✅ AI/Mock Validation System
- FastAPI: สร้าง RESTful API ที่เร็วและมี auto-documentation
- MySQL + Docker: จัดการ database ด้วย Docker Compose
- SQLAlchemy ORM: เชื่อมต่อและจัดการข้อมูลแบบ Object-Oriented
- API Integration: เชื่อมต่อ Frontend-Backend อย่างถูกต้อง
- Mock AI System: เตรียมพร้อมสำหรับ real AI integration (n8n/OpenAI)
ก่อนเริ่ม Workshop ต้องติดตั้งโปรแกรมเหล่านี้:
- Docker Desktop (รวม Docker Compose)
- Node.js version 18 หรือสูงกว่า
- Git
- Code Editor (แนะนำ VS Code)
1. Clone Repository
git clone {your fork repository URL}
cd daily-vocab-api2. เริ่ม Backend + Database
docker-compose up -dรอ Docker ทำงาน:
- 🗄️ สร้าง MySQL container
- 📋 Run
init.sqlสร้างตารางและข้อมูลตัวอย่าง - 🚀 Start FastAPI server
3. ตรวจสอบ API
เปิด browser ไปที่ http://localhost:8000/docs
คุณจะเห็น Swagger UI สำหรับทดสอบ API ทันที!
| Method | Endpoint | Description | Response |
|---|---|---|---|
GET |
/ |
API information | JSON with endpoints list |
GET |
/api/word |
สุ่มคำศัพท์ 1 คำ | Word object |
POST |
/api/validate-sentence |
ตรวจประโยค + ให้คะแนน | Validation result |
GET |
/api/summary |
สถิติการฝึกทั้งหมด | Summary statistics |
GET |
/api/history |
ประวัติการฝึก | Array of practice sessions |
GET |
/health |
Health check | Status object |
Request:
curl http://localhost:8000/api/wordResponse:
{
"id": 1,
"word": "apple",
"definition": "A round fruit with red, green, or yellow skin",
"difficulty_level": "Beginner"
}Request:
curl -X POST http://localhost:8000/api/validate-sentence \
-H "Content-Type: application/json" \
-d '{
"word_id": 1,
"sentence": "I eat an apple every morning for breakfast"
}'Response:
{
"score": 8.5,
"level": "Beginner",
"suggestion": "Excellent! Your sentence is well-structured and descriptive.",
"corrected_sentence": "I eat an apple every morning for breakfast"
}Request:
curl http://localhost:8000/api/summaryResponse:
{
"total_practices": 15,
"average_score": 7.8,
"total_words_practiced": 5,
"level_distribution": {
"Beginner": 8,
"Intermediate": 5,
"Advanced": 2
}
}เก็บคำศัพท์ทั้งหมดในระบบ
| Column | Type | Constraints | Description |
|---|---|---|---|
id |
INT | PRIMARY KEY, AUTO_INCREMENT | รหัสคำศัพท์ |
word |
VARCHAR(100) | UNIQUE, NOT NULL | คำศัพท์ภาษาอังกฤษ |
definition |
TEXT | ความหมาย/คำจำกัดความ | |
difficulty_level |
ENUM | 'Beginner', 'Intermediate', 'Advanced' | ระดับความยาก |
created_at |
TIMESTAMP | DEFAULT CURRENT_TIMESTAMP | วันที่เพิ่มคำศัพท์ |
เก็บประวัติการฝึกของผู้ใช้
| Column | Type | Constraints | Description |
|---|---|---|---|
id |
INT | PRIMARY KEY, AUTO_INCREMENT | รหัสการฝึก |
word_id |
INT | FOREIGN KEY → words(id) | คำศัพท์ที่ฝึก |
user_sentence |
TEXT | NOT NULL | ประโยคที่ผู้ใช้แต่ง |
score |
DECIMAL(3,1) | คะแนน (0.0-10.0) | |
feedback |
TEXT | คำแนะนำจาก AI | |
corrected_sentence |
TEXT | ประโยคที่แก้ไขแล้ว | |
practiced_at |
TIMESTAMP | DEFAULT CURRENT_TIMESTAMP | วันเวลาที่ฝึก |
┌─────────────┐ ┌───────────────────┐
│ words │ │ practice_sessions │
├─────────────┤ ├───────────────────┤
│ id (PK) │◄────────│ id (PK) │
│ word │ 1:N │ word_id (FK) │
│ definition │ │ user_sentence │
│ difficulty │ │ score │
│ created_at │ │ feedback │
└─────────────┘ │ corrected_sentence│
│ practiced_at │
└───────────────────┘
ดูสถานะ containers:
docker psRestart services:
# Restart ทั้งหมด
docker-compose restart
# Restart เฉพาะ FastAPI
docker-compose restart vocabapi
# Restart เฉพาะ MySQL
docker-compose restart mysqlดู logs:
# Logs ทั้งหมด
docker-compose logs -f
# Logs เฉพาะ service
docker-compose logs -f vocabapi
docker-compose logs -f mysqlหยุด containers:
docker-compose downลบข้อมูลและเริ่มใหม่:
docker-compose down -v # ลบ volumes (ข้อมูลใน database จะหายด้วย)
docker-compose up -dเข้าใช้งาน MySQL CLI:
docker exec -it vocab_mysql mysql -u vocabuser -pvocabpass123 vocabulary_dbเพิ่มคำศัพท์ใหม่:
INSERT INTO words (word, definition, difficulty_level) VALUES
('courage', 'The ability to do something frightening', 'Intermediate'),
('serendipity', 'Finding something good without looking for it', 'Advanced');ดูข้อมูลทั้งหมด:
-- ดูคำศัพท์ทั้งหมด
SELECT * FROM words;
-- ดูประวัติการฝึก 10 รายการล่าสุด
SELECT * FROM practice_sessions ORDER BY practiced_at DESC LIMIT 10;
-- ดูสถิติ
SELECT
difficulty_level,
COUNT(*) as total_practices,
AVG(score) as avg_score
FROM practice_sessions ps
JOIN words w ON ps.word_id = w.id
GROUP BY difficulty_level;Export ข้อมูล:
docker exec vocab_mysql mysqldump -u vocabuser -pvocabpass123 vocabulary_db > backup.sqlImport ข้อมูล:
docker exec -i vocab_mysql mysql -u vocabuser -pvocabpass123 vocabulary_db < backup.sqlแทนที่ mock_ai_validation():
import requests
def ai_validation_with_n8n(sentence: str, word: str, level: str):
"""เรียก n8n webhook ที่เชื่อม OpenAI"""
response = requests.post(
"https://your-n8n-instance.com/webhook/validate",
json={
"sentence": sentence,
"target_word": word,
"difficulty": level
},
timeout=10
)
return response.json()n8n Workflow แนะนำ:
- Webhook Trigger
- OpenAI Node (GPT-4)
- Prompt: "Evaluate this English sentence..."
- Return JSON response
Streak System:
# เพิ่ม table
CREATE TABLE user_streaks (
user_id INT,
current_streak INT DEFAULT 0,
longest_streak INT DEFAULT 0,
last_practice_date DATE
);Achievement System:
achievements = {
"first_practice": "แต่งประโยคครั้งแรก",
"score_perfect": "คะแนนเต็ม 10/10",
"streak_7": "ฝึกติดต่อกัน 7 วัน",
"words_50": "ฝึก 50 คำศัพท์แล้ว"
}Image Integration (Unsplash API):
@app.get("/api/word/{word_id}/image")
def get_word_image(word_id: int):
word = db.query(Word).filter(Word.id == word_id).first()
response = requests.get(
f"https://api.unsplash.com/search/photos?query={word.word}",
headers={"Authorization": f"Client-ID {UNSPLASH_KEY}"}
)
return response.json()Export Progress (PDF):
from reportlab.pdfgen import canvas
@app.get("/api/export/pdf")
def export_progress_pdf(user_id: int):
# สร้าง PDF report ของผู้ใช้
pass- 📘 FastAPI Documentation - Complete guide
- 📘 SQLAlchemy 2.0 Tutorial
- 📘 Docker Compose Reference
- 📘 Next.js App Router
- speechful - Achieve your target IELTS score with Speechful
- Duolingo - Language learning gamification
- Anki - Spaced repetition flashcards
- Quizlet - Study tools and flashcards
Made with ❤️ and ☕️ for Learner ⬆ กลับไปด้านบน