Quickstart guide cho fresher

Làm CRUD App với Python FastAPI và Cloudflare Free

Guide này ưu tiên các câu lệnh tạo nhanh dự án trước, sau đó hướng dẫn fresher viết backend FastAPI, website quản lý sinh viên/nhân sự và deploy miễn phí lên Cloudflare.

1. Lệnh tạo nhanh dự án

Chạy các lệnh này để tạo nhanh cấu trúc full-stack gồm frontend React trên Cloudflare Pages và backend FastAPI.

1.1 Tạo frontend React bằng Cloudflare CLI

npm create cloudflare@latest -- student-crud-app --framework=react --platform=pages
cd student-crud-app
npm run dev
Giải thích: đây là lệnh chính thức của Cloudflare Pages cho React. CLI sẽ tạo project, cài dependency, cài Wrangler và hỏi bạn có muốn deploy ngay không.

1.2 Tạo backend FastAPI nhanh bằng uv

FastAPI không có lệnh scaffold chính thức kiểu create-fastapi. Cách nhanh, rõ ràng và dễ dạy fresher là dùng uv để tạo project Python rồi thêm FastAPI.

cd ..
mkdir student-crud-api
cd student-crud-api
uv init --app
uv add "fastapi[standard]" "pydantic[email]" pytest httpx ruff
mkdir app tests

Tạo file Python nhanh:

# Windows PowerShell
New-Item app\__init__.py
New-Item app\main.py

# macOS/Linux
touch app/__init__.py app/main.py

1.3 Chạy backend local

uv run fastapi dev app/main.py

Mở http://127.0.0.1:8000/docs để test API.

1.4 Tạo project Cloudflare Python Worker cho backend deploy

uvx --from workers-py pywrangler init
uv run pywrangler dev
uv run pywrangler deploy
Note: Cloudflare Python Workers đang là beta. Khi deploy FastAPI lên Workers cần WorkerEntrypoint, asgi.fetch và flag python_workers.

2. Cài môi trường máy tính

Công cụ Dùng để làm gì Kiểm tra
Python 3.11+ Chạy FastAPI backend python --version
Node.js LTS Chạy React, Cloudflare CLI, Wrangler node --version
uv Tạo project Python, cài package, chạy pywrangler uv --version
Git Quản lý source code git --version
VS Code Editor cho fresher Cài extension Python, Ruff, ESLint
# Cài uv trên Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# Cài uv trên macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

3. Viết backend FastAPI CRUD

Tạo nội dung cho student-crud-api/app/main.py:

from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, EmailStr, Field

app = FastAPI(title="Student CRUD API")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Demo only. Production nên đổi thành URL Pages.
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class StudentCreate(BaseModel):
    full_name: str = Field(min_length=2, max_length=80)
    email: EmailStr
    department: str = Field(min_length=2, max_length=80)
    year: int = Field(ge=1, le=4)


class Student(StudentCreate):
    id: int


students: dict[int, Student] = {}
next_id = 1


@app.get("/health")
async def health():
    return {"status": "ok"}


@app.get("/students", response_model=list[Student])
async def list_students():
    return list(students.values())


@app.post("/students", response_model=Student, status_code=status.HTTP_201_CREATED)
async def create_student(payload: StudentCreate):
    global next_id
    student = Student(id=next_id, **payload.model_dump())
    students[student.id] = student
    next_id += 1
    return student


@app.put("/students/{student_id}", response_model=Student)
async def update_student(student_id: int, payload: StudentCreate):
    if student_id not in students:
        raise HTTPException(status_code=404, detail="Student not found")
    student = Student(id=student_id, **payload.model_dump())
    students[student_id] = student
    return student


@app.delete("/students/{student_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_student(student_id: int):
    if student_id not in students:
        raise HTTPException(status_code=404, detail="Student not found")
    del students[student_id]

Test API

uv run fastapi dev app/main.py

curl http://127.0.0.1:8000/health
curl http://127.0.0.1:8000/students

4. Làm website Quản Lý Đơn Giản

Với project React đã tạo bằng npm create cloudflare@latest, fresher chỉ cần làm các component cơ bản: form, table, nút sửa, nút xóa.

Luồng frontend cần có

Fetch API mẫu

const API_BASE = "http://127.0.0.1:8000";

async function loadStudents() {
  const response = await fetch(`${API_BASE}/students`);
  return response.json();
}

async function createStudent(payload) {
  const response = await fetch(`${API_BASE}/students`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });

  if (!response.ok) throw new Error("Create student failed");
  return response.json();
}

async function updateStudent(id, payload) {
  const response = await fetch(`${API_BASE}/students/${id}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });

  if (!response.ok) throw new Error("Update student failed");
  return response.json();
}

async function deleteStudent(id) {
  const response = await fetch(`${API_BASE}/students/${id}`, {
    method: "DELETE",
  });

  if (!response.ok) throw new Error("Delete student failed");
}

5. Deploy Cloudflare Free

5.1 Deploy frontend React lên Cloudflare Pages

Nếu dùng lệnh tạo nhanh ở đầu guide, CLI có thể hỏi deploy ngay. Nếu chưa deploy, chạy:

cd student-crud-app
npm run build
npx wrangler pages deploy dist

5.2 Deploy backend FastAPI lên Cloudflare Workers Python

Trong backend deploy, thêm entrypoint cho Workers:

from workers import WorkerEntrypoint
import asgi
from app.main import app


class Default(WorkerEntrypoint):
    async def fetch(self, request):
        return await asgi.fetch(app, request, self.env)

Config mẫu:

name = "student-crud-api"
main = "src/entry.py"
compatibility_date = "2026-07-09"
compatibility_flags = ["python_workers"]

Deploy:

uv run pywrangler deploy
Sau deploy: đổi API_BASE trong frontend từ http://127.0.0.1:8000 sang URL Worker, ví dụ https://student-crud-api.your-name.workers.dev, rồi deploy lại Pages.

6. Lỗi cơ bản cần note cho fresher

Lỗi Cách xử lý
Nhầm lệnh frontend với backend npm create cloudflare@latest tạo frontend React/Pages. Backend FastAPI tạo bằng Python/uv.
Quên chạy virtual environment hoặc uv run Dùng uv run fastapi dev app/main.py để chạy đúng môi trường project.
Bị CORS khi frontend gọi backend Thêm CORSMiddleware. Production nên allow đúng URL Pages.
Deploy frontend nhưng vẫn gọi localhost Đổi API_BASE sang URL Worker đã deploy.
Dùng in-memory dict làm database thật Chỉ dùng để học CRUD. Production cần D1, KV hoặc database ngoài.
Quên python_workers Thêm compatibility_flags = ["python_workers"] khi deploy Workers Python.

7. Nguồn tài liệu