FastAPI 零基础入门指南:10 分钟搭建高性能 API

一、为什么选择 FastAPI?

想象一下,用 Python 写 API 可以像搭积木一样简单,同时还能拥有媲美 Go 语言的性能,这个框架凭借三大核心优势迅速风靡全球:

  • 开发效率提升 3 倍:类型注解 + 自动文档,代码即文档
  • 性能碾压传统框架:异步架构 + UJSON 序列化,QPS 轻松破万
  • 零配置自动化:Swagger UI/ReDoc 文档、数据验证、依赖注入开箱即用

二、5 分钟快速上手

1. 环境准备

bash 复制代码
# 安装核心库
pip install fastapi uvicorn pydantic

2. 第一个 API

python 复制代码
# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

3. 启动服务

bash 复制代码
uvicorn main:app --reload

4. 访问 API

打开浏览器访问 http://localhost:8000/,你会看到:

打开浏览器访问 http://localhost:8000/docs,你会看到交互式 API 文档:

三、核心功能详解

1. 路由系统

路径参数
python 复制代码
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
查询参数
python 复制代码
@app.get("/users")
async def read_users(skip: int = 0, limit: int = 10):
    return {"users": fake_users_db[skip : skip + limit]}
响应模型
python 复制代码
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str

@app.get("/user/{user_id}", response_model=User)
async def get_user(user_id: int):
    return User(id=user_id, name="Alice")

2. 数据验证

python 复制代码
class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

@app.post("/items/")
async def create_item(item: Item):
    return {"item_name": item.name, "item_price": item.price}

3. 异步支持

python 复制代码
import asyncio

@app.get("/async-task")
async def async_task():
    await asyncio.sleep(1)  # 模拟耗时操作
    return {"result": "Done"}

四、生产级功能

1. 自动文档

  • Swagger UI :访问 /docs 进行交互式测试
  • ReDoc :访问 /redoc 获取简洁文档
  • OpenAPI 规范:自动生成标准接口契约

2. 依赖注入

python 复制代码
def get_db():
    db = Database()
    try:
        yield db
    finally:
        db.close()

@app.get("/items/")
async def read_items(db: Database = Depends(get_db)):
    return db.query("SELECT * FROM items")

3. 中间件

python 复制代码
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

五、进阶技巧

1. 代码结构优化

plaintext 复制代码
myapi/
├── main.py
├── routers/
│   ├── items.py
│   └── users.py
├── models.py
└── schemas.py

2. 性能优化

python 复制代码
# 使用orjson加速序列化
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse

app = FastAPI(default_response_class=ORJSONResponse)

3. 测试方案

python 复制代码
from fastapi.testclient import TestClient

client = TestClient(app)

def test_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}

六、生态工具链

工具类型 推荐工具 核心功能
代码生成 fastapi-code-generator 从 OpenAPI 生成项目骨架
调试工具 httpie 命令行 API 测试
监控 Prometheus + Grafana 性能指标可视化
部署 Docker + Kubernetes 云原生部署

七、真实案例

某电商平台使用 FastAPI 重构商品推荐接口后:

  • 日均请求量从 200 万增至 800 万
  • 响应时间中位数从 420ms 降至 110ms
  • 接口联调周期缩短 60%

八、常见问题

  1. 如何处理跨域请求?
python 复制代码
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
  1. 如何自定义异常响应?
python 复制代码
@app.exception_handler(ValueError)
async def value_error_handler(request, exc):
    return JSONResponse(
        status_code=400,
        content={"message": f"Invalid value: {exc}"},
    )

九、学习资源

相关推荐
Hgfdsaqwr4 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
开发者小天4 小时前
python中For Loop的用法
java·服务器·python
布局呆星4 小时前
FastAPI:高性能Python Web框架
fastapi
老百姓懂点AI5 小时前
[RAG实战] 向量数据库选型与优化:智能体来了(西南总部)AI agent指挥官的长短期记忆架构设计
python
喵手7 小时前
Python爬虫零基础入门【第九章:实战项目教学·第15节】搜索页采集:关键词队列 + 结果去重 + 反爬友好策略!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·搜索页采集·关键词队列
Suchadar7 小时前
if判断语句——Python
开发语言·python
ʚB҉L҉A҉C҉K҉.҉基҉德҉^҉大7 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
喵手7 小时前
Python爬虫零基础入门【第九章:实战项目教学·第14节】表格型页面采集:多列、多行、跨页(通用表格解析)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·表格型页面采集·通用表格解析
毕设源码-钟学长7 小时前
【开题答辩全过程】以 基于SpringBoot的智能书城推荐系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
0思必得08 小时前
[Web自动化] 爬虫之API请求
前端·爬虫·python·selenium·自动化