今天我们要开发一个简单的 AI 应用后端:

今天先把 API 服务框架和路由搭起来,暂时不接真实大模型。
FastAPI 是一个基于 Python 的 Web API 框架。
可以这样理解:
| 技术 | 你熟悉的作用 | Python 对应 |
|---|---|---|
| Spring Boot | Java Web 框架 | FastAPI |
| Spring MVC Controller | 接收 HTTP 请求 | APIRouter |
@GetMapping |
GET 路由 | @router.get() |
@PostMapping |
POST 路由 | @router.post() |
| DTO | 请求和响应对象 | Pydantic Model |
| Swagger | API 文档 | FastAPI 自动生成 |
FastAPI 的优势:
原生支持异步接口。
自动生成 Swagger API 文档。
使用类型提示进行请求参数校验。
适合开发大模型、RAG、Agent 等 AI 服务。
进入第一课创建的项目:
|
1 2 3 |
cd ai-app-platform source .venv/bin/activate |
安装依赖:
|
1 |
pip install "fastapi[standard]" |
检查安装:
|
1 |
pip show fastapi |
再将依赖保存下来:
|
1 |
pip freeze > requirements.txt |
打开项目中的:
app/main.py
把原来的代码替换为:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from fastapi import FastAPI # 创建 FastAPI 应用 app = FastAPI( title="AI 应用平台", description="AI 应用工程师学习项目", version="1.0.0" ) # 第一个接口 @app.get("/") async def root(): return { "code": 200, "message": "AI 应用平台启动成功" } # 健康检查接口 @app.get("/health") async def health(): return { "status": "ok", "service": "ai-app-platform" } |
启动服务:
|
1 |
fastapi dev app/main.py |
看到类似下面的信息,说明启动成功:
|
1 |
Uvicorn running on http://127.0.0.1:8000 |
打开浏览器访问:
第三个地址就是自动生成的 Swagger 文档。
这意味着你不需要单独搭建 Swagger,就可以拥有可交互的 API 文档。
在 Spring Boot 中,你熟悉这样的写法:
|
1 2 3 4 |
@GetMapping("/users/{userId}") public User getUser(@PathVariable Long userId) { // ... } |
FastAPI 的写法非常接近。
在 app/main.py 中增加:
|
1 2 3 4 5 6 |
@app.get("/api/users/{user_id}") async def get_user(user_id: int): return { "user_id": user_id, "name": "张三" } |
访问:
|
1 |
http://127.0.0.1:8000/api/users/1001 |
返回:
|
1 2 3 4 |
{ "user_id": 1001, "name": "张三" } |
这里的 user_id: int 很重要。
如果访问:
|
1 |
/api/users/abc |
FastAPI 会自动进行参数类型校验,并返回 422 错误,而不是让你自己手动转换。
例如,我们需要分页查询用户:
|
1 2 3 4 5 6 7 8 9 10 |
@app.get("/api/users") async def get_users( page: int = 1, page_size: int = 10 ): return { "page": page, "page_size": page_size, "data": ["张三", "李四"] } |
访问:
|
1 |
http://127.0.0.1:8000/api/users?page=2&page_size=20 |
FastAPI 会自动把查询字符串转换成对应类型。
对照 Java:
| FastAPI | Spring MVC |
|---|---|
/users/{id} |
@PathVariable |
page: int = 1 |
@RequestParam(defaultValue="1") |
@app.get() |
@GetMapping |
@app.post() |
@PostMapping |
现在模拟用户向 AI 系统提问。
增加下面的代码:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from pydantic import BaseModel class ChatRequest(BaseModel): user_id: int question: str @app.post("/api/ai/chat") async def chat(request: ChatRequest): return { "user_id": request.user_id, "question": request.question, "answer": f"收到你的问题:{request.question}" } |
这段代码中:
ChatRequest:请求 DTO。
BaseModel:Pydantic 提供的数据模型基类。
request:经过解析和校验的请求对象。
这与 Java 中使用 DTO 接收 JSON 请求体的思路非常相似。
打开 Swagger:
|
1 |
http://127.0.0.1:8000/docs |
找到 POST /api/ai/chat,点击 Try it out,输入:
|
1 2 3 4 |
{ "user_id": 1001, "question": "什么是 RAG?" } |
点击 Execute。
今天先了解 Pydantic 的基本用法,下一课我们会专门深入学习请求校验、字段约束和响应模型。
这一步开始引入架构设计。
如果所有接口都写在 main.py,项目越来越大后,就会变得难以维护。
你以前做 Java 项目时,应该习惯 Controller、Service、Repository 分层。Python 项目同样需要模块化。
我们把项目调整为:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
ai-app-platform/ │ ├── app/ │ ├── __init__.py │ ├── main.py │ │ │ ├── api/ │ │ ├── __init__.py │ │ ├── users.py │ │ └── ai.py │ │ │ ├── services/ │ │ └── ai_service.py │ │ │ ├── models/ │ │ └── schemas.py │ │ │ └── core/ │ └── __init__.py │ └── requirements.txt |
app/api/users.py
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from fastapi import APIRouter router = APIRouter( prefix="/api/users", tags=["用户管理"] ) @router.get("/{user_id}") async def get_user(user_id: int): return { "user_id": user_id, "name": "张三" } @router.get("/") async def list_users( page: int = 1, page_size: int = 10 ): return { "page": page, "page_size": page_size, "users": ["张三", "李四"] } |
注意:
|
1 |
prefix="/api/users" |
表示这个路由模块中的接口统一使用 /api/users 前缀。
app/api/ai.py
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from fastapi import APIRouter from pydantic import BaseModel router = APIRouter( prefix="/api/ai", tags=["AI 服务"] ) class ChatRequest(BaseModel): user_id: int question: str @router.post("/chat") async def chat(request: ChatRequest): return { "user_id": request.user_id, "answer": f"AI 回答:{request.question}" } |
app/main.py
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from fastapi import FastAPI from app.api import users, ai app = FastAPI( title="AI 应用平台", description="企业级 AI 应用后端", version="1.0.0" ) app.include_router(users.router) app.include_router(ai.router) @app.get("/health", tags=["系统管理"]) async def health(): return { "status": "ok", "service": "ai-app-platform" } |
启动:
|
1 |
fastapi dev app/main.py |
现在打开:
|
1 |
http://127.0.0.1:8000/docs |
你会看到接口自动按照模块分类:
用户管理
AI 服务
系统管理
这就是今天最重要的架构知识:通过 APIRouter 拆分业务模块,再由 main.py 统一注册。
相当于 Spring Boot 中将不同 Controller 组织成独立模块。
再进一步,我们不应该把 AI 业务逻辑全部写在路由函数里。
创建 app/services/ai_service.py:
|
1 2 3 4 5 6 7 8 |
class AIService: async def generate(self, question: str) -> str: # 后续在这里接入真正的大模型 API return f"AI 正在回答:{question}" ai_service = AIService() |
然后修改 app/api/ai.py:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
from fastapi import APIRouter from pydantic import BaseModel from app.services.ai_service import ai_service router = APIRouter( prefix="/api/ai", tags=["AI 服务"] ) class ChatRequest(BaseModel): user_id: int question: str @router.post("/chat") async def chat(request: ChatRequest): answer = await ai_service.generate(request.question) return { "user_id": request.user_id, "answer": answer } |
现在架构变成:
