关注【索引目录】服务号,更多精彩内容等你来探索!
在现代 Web 开发领域,速度至关重要。无论您是开发单页应用,还是向移动客户端传递数据,强大的后端 API 都至关重要。对于需要高性能、可扩展且设置简单的 API 的 Python 开发者来说, FastAPI已迅速成为他们的首选解决方案。
在本指南中,我们将介绍如何使用 FastAPI 构建和测试超快的 REST API,以及如何使用 fetch/AJAX 将其连接到前端。
为什么选择 FastAPI?
FastAPI 是一个现代化的、异步优先的 Python Web 框架,专为构建 API 而设计。以下是开发者喜爱它的原因:
默认异步:原生支持 async/await。
类型提示 = 自动验证:使用 Python 类型提示自动生成文档并验证输入。
交互式 API 文档:开箱即用,配备 Swagger 和 Redoc 接口。
速度极快:性能与 NodeJS 和 Go 相当。
️ 一步步构建简单的 API
让我们创建一个最小的后端来管理任务列表——非常适合像 React、Vue 甚至 vanilla JS 这样的简单前端。
1. 安装 FastAPI 和 Uvicorn
pip install fastapi uvicorn
2. 项目结构
project/
├── main.py
3. API 代码(main.py)
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Task(BaseModel):
id: int
title: str
completed: bool = False
tasks: List[Task] = []
@app.get("/tasks", response_model=List[Task])
def get_tasks():
return tasks
@app.post("/tasks", response_model=Task)
def create_task(task: Task):
tasks.append(task)
return task
@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, updated_task: Task):
for i, t in enumerate(tasks):
if t.id == task_id:
tasks[i] = updated_task
return updated_task
raise HTTPException(status_code=404, detail="Task not found")
@app.delete("/tasks/{task_id}")
def delete_task(task_id: int):
global tasks
tasks = [t for t in tasks if t.id != task_id]
return {"message": "Task deleted"}
▶️4.运行 API 服务器
uvicorn main:app --reload
访问地址:http://127.0.0.1: 8000/docs
️ 前端:通过 JavaScript 连接
让我们使用基本fetch()调用与 FastAPI 后端进行交互。
<script>
async function addTask() {
await fetch("http://localhost:8000/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: Date.now(), title: "Learn FastAPI", completed: false }),
});
loadTasks();
}
async function loadTasks() {
const res = await fetch("http://localhost:8000/tasks");
const data = await res.json();
console.log(data);
}
addTask();
</script>
这足以将您的 FastAPI 后端连接到React、Vue,甚至是基本的静态 HTML 页面。
内置测试和文档
FastAPI 自动生成:
Swagger 用户界面:http://localhost:8000/docs
Redoc 用户界面:http://localhost:8000/redoc
两者都使 API 测试变得简单且直观。
福利:为前端集成添加 CORS
如果您从另一个端口(例如,端口 3000 上的 React dev 服务器)为前端提供服务,则需要添加 CORS 支持:
pip install fastapi[all]
然后更新您的main.py:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace with your frontend URL in production
allow_methods=["*"],
allow_headers=["*"],
)
值得尝试的高级想法
掌握基础知识后,请尝试:
JWT 身份验证
SQLModel 或 SQLAlchemy ORM
异步数据库(如 Tortoise ORM)
使用 Celery 或 FastAPI 的后台任务
BackgroundTasks用于实时更新的 WebSocket
有用的资源
FastAPI 官方文档
使用 FastAPI 进行测试驱动开发
全栈 FastAPI + React 模板
在 Render 或 Fly.io 上部署 FastAPI
✅ 总结
FastAPI 是所有 Python Web 开发者工具包的强大补充。它拥有异步速度、直观的语法和自动文档,能够显著减少样板代码并提高生产力。
如果您正在构建现代 Web 应用程序(尤其是 SPA 或移动应用程序),那么 FastAPI 应该在您的候选名单上。
构建更智能,交付更快,并且不再需要与后端斗争。
关注【索引目录】服务号,更多精彩内容等你来探索!

