引言
在现代Web开发中,构建高性能的RESTful API是后端开发者的核心技能之一。FastAPI作为近年来崛起的Python Web框架,以其出色的性能、优雅的API设计和强大的开发体验,正在改变Python Web开发的格局。
为什么选择FastAPI?
FastAPI由Sebastián Ramírez于2018年创建,是一个现代、快速(高性能)的Web框架,用于基于标准Python类型提示构建API。它的主要特点包括:
• 高性能 :与NodeJS和Go相当的性能,得益于Starlette和Pydantic的底 层支持
• 快速开发 :开发效率提高约200-300%,代码量减少35-40%
• 减少错误 :减少了约40%的人为(开发者)错误
• 直观简洁 :代码易于阅读和理解,支持IDE的自动补全
• 标准化 :完全兼容OpenAPI和JSON Schema规范
• 自动文档 :自动生成交互式API文档(Swagger UI和ReDoc)
应用场景
FastAPI特别适合以下场景:
• RESTful API开发
• 微服务架构
• 实时数据处理应用
• 高并发的Web服务
• 需要快速迭代的项目原型
环境搭建
Python环境要求
FastAPI支持Python 3.7及以上版本。建议使用Python 3.8+以获得最佳体验。
安装FastAPI
使用pip安装FastAPI和ASGI服务器Uvicorn:
bash
# 基础安装
pip install fastapi uvicorn
# 可选:安装所有依赖(包括标准依赖和可选依赖)
pip install fastapi[all] uvicorn[standard]
依赖说明:
• fastapi:核心框架包
• uvicorn:ASGI服务器,用于运行FastAPI应用
• fastapi[all]:包含所有可选依赖,如python-multipart、 itsdangerous等
验证安装
python
# 测试安装是否成功
import fastapi
print(f"FastAPI版本: {fastapi.__version__}")
Hello World示例
让我们从最简单的FastAPI应用开始:
创建第一个应用
新建文件main.py,写入以下代码:
python
from fastapi import FastAPI
# 创建FastAPI应用实例
app = FastAPI(title="FastAPI入门示例", version="1.0.0")
# 定义根路由
@app.get("/")
def read_root():
return {"message": "Hello World", "status": "success"}
# 健康检查端点
@app.get("/health")
def health_check():
return {"status": "healthy"}
运行应用
在终端中执行以下命令启动服务器:
python
# 开发模式运行(支持热重载)
uvicorn main:app --reload
# 生产模式运行
uvicorn main:app --host 0.0.0.0 --port 8000
参数说明:
• main:app:main是文件名,app是FastAPI实例
• --reload:代码修改后自动重启服务器(开发环境推荐)
• --host 0.0.0.0:监听所有网络接口
• --port 8000:指定端口号
测试API
方式一:浏览器访问
打开浏览器,访问:
• http://127.0.0.1:8000/ - 根路径
• http://127.0.0.1:8000/health - 健康检查
方式二:使用curl命令
bash
# 测试根路径
curl http://127.0.0.1:8000/
# 测试健康检查
curl http://127.0.0.1:8000/health
方式三:访问自动文档
• Swagger UI:http://127.0.0.1:8000/docs
• ReDoc:http://127.0.0.1:8000/redoc
核心功能讲解
路由与HTTP方法
FastAPI支持所有HTTP方法,使用装饰器定义路由:
python
from fastapi import FastAPI, HTTPException
app = FastAPI()
# GET请求
@app.get("/items")
def read_items():
return {"items": ["item1", "item2"]}
# POST请求
@app.post("/items")
def create_item(item_name: str):
return {"item_name": item_name, "status": "created"}
# PUT请求
@app.put("/items/{item_id}")
def update_item(item_id: int, item_name: str):
return {"item_id": item_id, "item_name": item_name, "status": "updated"}
# DELETE请求
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
return {"item_id": item_id, "status": "deleted"}
请求参数
1. 路径参数
路径参数是URL路径的一部分,自动进行类型转换和验证:
python
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
"""
item_id 自动转换为int类型
访问: /items/5
"""
return {"item_id": item_id}
# 带验证的路径参数
@app.get("/items/{item_id}")
def read_item_with_validation(
item_id: int = Path(..., gt=0, le=100, description="商品ID必须在1-100之间")
):
"""
gt: greater than (大于)
le: less than or equal (小于等于)
"""
return {"item_id": item_id}
2. 查询参数
查询参数位于URL的?后面:
python
from fastapi import FastAPI, Query
from typing import Optional
app = FastAPI()
@app.get("/items/")
def read_items(
skip: int = 0,
limit: int = 10,
q: Optional[str] = None,
category: str = Query(..., min_length=2, max_length=20)
):
"""
skip和limit有默认值
q是可选参数(Optional)
category是必填参数(Query(...))
访问: /items/?skip=5&limit=20&q=python&category=tech
"""
return {
"skip": skip,
"limit": limit,
"q": q,
"category": category
}
3. 请求体(Request Body)
请求体用于发送复杂的数据结构,通常使用POST、PUT等方法:
python
from fastapi import FastAPI
from pydantic import BaseModel, Field
from typing import Optional
app = FastAPI()
class Item(BaseModel):
name: str = Field(..., min_length=1, max_length=50)
description: Optional[str] = None
price: float = Field(..., gt=0)
tax: Optional[float] = None
class Config:
schema_extra = {
"example": {
"name": "商品名称",
"description": "商品描述",
"price": 99.99,
"tax": 9.99
}
}
@app.post("/items/")
def create_item(item: Item):
"""
创建新商品
请求体示例:
{
"name": "笔记本电脑",
"description": "高性能办公电脑",
"price": 5999.00,
"tax": 500.00
}
"""
return {
"item": item,
"total_price": item.price + (item.tax if item.tax else 0)
}
# 同时使用路径参数、查询参数和请求体
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item, q: Optional[str] = None):
return {
"item_id": item_id,
"item": item,
"q": q
}
响应处理与状态码
设置响应状态码
python
from fastapi import FastAPI, status
app = FastAPI()
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item(item_name: str):
"""
返回201状态码表示资源创建成功
"""
return {"item_name": item_name}
# 使用HTTP异常
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id < 1:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="商品不存在"
)
return {"item_id": item_id}
自定义响应
python
from fastapi import FastAPI
from fastapi.responses import JSONResponse, HTMLResponse
app = FastAPI()
@app.get("/json")
def get_json_response():
return JSONResponse(
content={"message": "自定义JSON响应"},
status_code=200
)
@app.get("/html")
def get_html_response():
content = """
<html>
<body>
<h1>FastAPI HTML响应</h1>
</body>
</html>
"""
return HTMLResponse(content=content)
自动生成的API文档
FastAPI基于OpenAPI规范自动生成交互式文档:
Swagger UI
特点:
• 可视化展示所有API端点
• 支持在线测试API
• 自动生成请求/响应示例
• 查看数据模型定义
ReDoc
访问:http://127.0.0.1:8000/redoc
特点:
• 更美观的文档展示
• 适合作为正式API文档
• 更好的移动端体验
自定义文档信息:
python
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
app = FastAPI(
title="FastAPI商城API",
description="这是一个基于FastAPI的商城API示例",
version="2.0.0",
docs_url="/docs", # 自定义Swagger UI路径
redoc_url="/redoc" # 自定义ReDoc路径
)
# 自定义OpenAPI schema
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="FastAPI商城API",
version="2.0.0",
description="这是一个基于FastAPI的商城API示例",
routes=app.routes,
)
openapi_schema["info"]["x-logo"] = {
"url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
}
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
上篇总结
通过本篇学习,我们掌握了FastAPI的核心基础:
✅ 环境搭建 :安装FastAPI和Uvicorn服务器
✅ Hello World :创建并运行第一个FastAPI应用
✅ 路由系统 :支持GET、POST、PUT、DELETE等HTTP方法
✅ 参数处理 :路径参数、查询参数、请求体的使用
✅ 响应处理 :自定义状态码和响应格式
✅ 自动文档 :Swagger UI和ReDoc的使用
这些基础知识为深入学习FastAPI打下了坚实基础。在下篇 中,我们将学习依赖注入、异步支持、数据验证等高级特性,并通过一个完整的图书管理API实战案例,展示FastAPI在实际项目中的应用。
敬请期待《FastAPI入门(下篇):高级特性与实战应用》!