架构 / 闯关模式

后端系统分层架构

理解 API、Schema、Service、Repository、Model、Core 各层的职责。

一句话:分层架构就是把接请求、做业务、查数据库、定义数据格式这些事情分开放,避免项目越写越乱。

本篇学完你会什么:知道 API 层、Service 层、Repository 层、Model 层、Schema 层分别负责什么。

1. 为什么要分层

小项目可以一个文件写完。

但项目一大,容易变成:

接口里既校验参数
又写业务规则
又拼 SQL
又处理权限
又写日志

最后谁都不敢改。

分层的目标是:每层只管自己的事情。

后端系统分层架构图

2. 一个请求怎么流转

前端请求
  ↓
API 层接住请求
  ↓
Schema 校验输入
  ↓
Service 处理业务规则
  ↓
Repository 读写数据库
  ↓
Model 映射数据库表
  ↓
Schema 整理响应
  ↓
返回前端

记住这条线,后端架构就不玄了。

3. API 层

API 层负责接请求和返回响应。

@router.post("/articles", response_model=ArticleResponse)
async def create_article(
    payload: ArticleCreate,
    current_user: User = Depends(get_current_user),
    service: ArticleService = Depends(get_article_service),
):
    return await service.create_article(payload, current_user)

API 层应该少写业务细节。

它主要管:

  • 路由路径
  • 请求方法
  • 参数入口
  • 鉴权依赖
  • response_model

4. Schema 层

Schema 层负责数据形状。

class ArticleCreate(BaseModel):
    title: str = Field(min_length=1, max_length=100)
    content: str

class ArticleResponse(BaseModel):
    id: int
    title: str
    content: str

请求模型和响应模型要分开,避免把密码、内部字段返回给前端。

5. Service 层

Service 层负责业务规则。

class ArticleService:
    def __init__(self, repo: ArticleRepository):
        self.repo = repo

    async def create_article(self, payload: ArticleCreate, user: User):
        if not user.is_active:
            raise HTTPException(status_code=403, detail="用户已禁用")

        return await self.repo.create(
            title=payload.title,
            content=payload.content,
            author_id=user.id,
        )

大白话:Service 是真正办事的人。

6. Repository 层

Repository 层负责数据库读写。

class ArticleRepository:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def get_by_id(self, article_id: int):
        return await self.db.get(Article, article_id)

    async def create(self, title: str, content: str, author_id: int):
        article = Article(title=title, content=content, author_id=author_id)
        self.db.add(article)
        await self.db.commit()
        await self.db.refresh(article)
        return article

不要把复杂业务判断写在 Repository 里。

7. Model 层

Model 层负责数据库表结构。

class Article(Base):
    __tablename__ = "articles"

    id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
    content = Column(Text, nullable=False)

Model 不是给前端看的,它是给 ORM 和数据库看的。

8. Core 层

Core 放全局基础能力:

core/
  config.py
  database.py
  redis.py
  security.py
  logging.py

大白话:Core 是项目的水电煤。

9. 从单体到模块化单体

初学阶段不建议一上来微服务。

推荐先做模块化单体:

app/
  modules/
    users/
      api.py
      schemas.py
      models.py
      service.py
      repository.py
    articles/
      api.py
      schemas.py
      models.py
      service.py
      repository.py

好处:

  • 部署简单
  • 代码边界清楚
  • 以后真要拆服务,也有基础

10. 常见错误

问题原因解决
接口函数特别长API 层写了太多业务抽到 Service
Service 直接写 SQL层职责混乱数据库操作放 Repository
Model 直接返回前端内部字段泄露用 Response Schema
一开始就微服务复杂度太早先模块化单体
目录很多但没边界只是搬文件明确每层职责

11. 检查清单

[ ] API 层是否只接请求
[ ] Schema 是否负责输入输出格式
[ ] Service 是否承载业务规则
[ ] Repository 是否只做数据库读写
[ ] Model 是否只映射数据库表
[ ] Core 是否放通用基础能力
[ ] 模块之间是否尽量少互相乱调

总结表

大白话
API接待窗口
Schema表格模板
Service办业务的人
Repository查档案的人
Model数据库表设计图
Core水电煤
模块化单体一个应用里分清多个业务房间

下一篇建议:大白话讲解——Docker Compose 跑完整后端服务