Skip to content
 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

📚 Vocabulary Practice API Workshop

FastAPI + MySQL + Docker Workshop Template เรียนรู้การสร้าง REST API พร้อม Database และ Frontend Integration

FastAPI MySQL Docker Next.js TypeScript

📖 เกี่ยวกับ Workshop

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)

🚀 Quick Start

Prerequisites

ก่อนเริ่ม Workshop ต้องติดตั้งโปรแกรมเหล่านี้:

⚡ เริ่มต้นใช้งาน (5 นาที)

1. Clone Repository

git clone {your fork repository URL}
cd daily-vocab-api

2. เริ่ม 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 ทันที!


🔌 API Endpoints

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

📝 ตัวอย่างการใช้งาน

1. ดึงคำศัพท์สุ่ม

Request:

curl http://localhost:8000/api/word

Response:

{
  "id": 1,
  "word": "apple",
  "definition": "A round fruit with red, green, or yellow skin",
  "difficulty_level": "Beginner"
}

2. ส่งประโยคเพื่อตรวจสอบ

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"
}

3. ดูสถิติการฝึก

Request:

curl http://localhost:8000/api/summary

Response:

{
  "total_practices": 15,
  "average_score": 7.8,
  "total_words_practiced": 5,
  "level_distribution": {
    "Beginner": 8,
    "Intermediate": 5,
    "Advanced": 2
  }
}

🗄️ Database Schema

Table: words

เก็บคำศัพท์ทั้งหมดในระบบ

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 วันที่เพิ่มคำศัพท์

Table: practice_sessions

เก็บประวัติการฝึกของผู้ใช้

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 วันเวลาที่ฝึก

ER Diagram

┌─────────────┐         ┌───────────────────┐
│   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      │
                        └───────────────────┘

🛠️ Development Guide

การจัดการ Docker Containers

ดูสถานะ containers:

docker ps

Restart 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

การจัดการ Database

เข้าใช้งาน 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.sql

Import ข้อมูล:

docker exec -i vocab_mysql mysql -u vocabuser -pvocabpass123 vocabulary_db < backup.sql

🚀 แนะนำการพัฒนาต่อ (สำหรับ Term Project)

🤖 1. เชื่อมต่อ AI จริง (n8n + OpenAI)

แทนที่ 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 แนะนำ:

  1. Webhook Trigger
  2. OpenAI Node (GPT-4)
    • Prompt: "Evaluate this English sentence..."
  3. Return JSON response

🎮 2. Gamification Features

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 คำศัพท์แล้ว"
}

📱 3. Advanced Features

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

📚 Learning Resources

Official Documentation

Video Tutorials

Related Projects & Inspiration

  • 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 ⬆ กลับไปด้านบน

About

This workshop is designed to teach students how to build a Full-Stack English vocabulary practice application using modern technologies. It is ideal for students working on Term Projects related to Vocabulary Learning, Language Practice

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages