โครงสร้างโปรเจกต์
เปรียบเทียบ file tree
หัวข้อที่มีชื่อว่า “เปรียบเทียบ file tree”โปรเจกต์ NestJS หรือ Express มี convention ของตัวเอง FastAPI ไม่ได้บังคับโครงสร้าง แต่ community ได้ลงตัวกับรูปแบบที่ดูคุ้นเคย
# โปรเจกต์ Express / NestJSmy-api/├── src/│ ├── main.ts # bootstrap│ ├── app.module.ts # root module (NestJS)│ ├── items/│ │ ├── items.controller.ts│ │ ├── items.service.ts│ │ └── items.dto.ts│ └── database/│ └── database.module.ts├── test/├── package.json└── tsconfig.json# โปรเจกต์ FastAPImy-api/├── app/│ ├── main.py # FastAPI() instance + startup│ ├── routers/│ │ └── items.py # APIRouter — เหมือน controller│ ├── models/│ │ └── item.py # SQLAlchemy ORM models│ ├── schemas/│ │ └── item.py # Pydantic schemas (DTOs)│ ├── dependencies.py # shared Depends() factories│ └── database.py # engine + Session├── tests/├── pyproject.toml # เหมือน package.json└── .envการ mapping แทบจะ 1:1:
controller→routers/(ใช้APIRouter)service→ เพิ่มservices/layer ได้ แต่ FastAPI ไม่บังคับdto→schemas/(Pydantic models)entity→models/(SQLAlchemy models)app.module.ts→main.py
main.py — entry point
หัวข้อที่มีชื่อว่า “main.py — entry point”// Express src/main.tsimport express from 'express';import { itemsRouter } from './items/items.router';
const app = express();app.use(express.json());app.use('/items', itemsRouter);
app.listen(3000, () => console.log('listening on 3000'));# app/main.pyfrom contextlib import asynccontextmanager
from fastapi import FastAPIfrom app.routers import items
# Startup/shutdown via lifespan: code before yield runs at startup,# code after yield runs at shutdown (e.g. open/close a DB pool).@asynccontextmanagerasync def lifespan(app: FastAPI): print("Server is starting up") yield print("Server is shutting down")
app = FastAPI(title="Items API", version="1.0.0", lifespan=lifespan)
app.include_router(items.router, prefix="/items", tags=["items"])
# รัน: uvicorn app.main:app --reloadpyproject.toml — เทียบเท่า package.json
หัวข้อที่มีชื่อว่า “pyproject.toml — เทียบเท่า package.json”// package.json{ "name": "my-api", "version": "1.0.0", "scripts": { "start": "node dist/main.js", "dev": "ts-node-dev src/main.ts", "build": "tsc" }, "dependencies": { "express": "^4.18.0", "zod": "^3.22.0" }, "devDependencies": { "typescript": "^5.0.0", "@types/express": "^4.17.0" }}# pyproject.toml (PEP 517/518 — ใช้กับ pip / poetry / uv)[project]name = "my-api"version = "1.0.0"requires-python = ">=3.11"dependencies = [ "fastapi>=0.115", "uvicorn[standard]>=0.29", "pydantic>=2.0", "sqlalchemy>=2.0",]
[project.optional-dependencies]dev = ["pytest", "httpx", "mypy"]
[tool.uvicorn]# เริ่ม: uvicorn app.main:app --reload# หรือ: python -m uvicorn app.main:app --reloadรันที่เครื่องตัวเอง — ต้องการ FastAPI + server สร้างโครงสร้างด้านบน, ติดตั้ง dependencies ด้วย
pip install -e ".[dev]"หรือuv syncแล้วรันuvicorn app.main:app --reload