FastAPI实战:用GET和POST方法构建RESTful API

为什么选择FastAPI?

在当今的Web开发中,构建高效、易用的API变得越来越重要。FastAPI是一个基于Python的现代Web框架,它有几个突出的优势:

  • 高性能:基于Starlette和Pydantic构建,性能接近Node.js和Go
  • 自动生成API文档:无需额外工具,自带Swagger UI和ReDoc
  • 类型提示支持:利用Python的类型注解自动生成接口规范和数据验证
  • 易用性:代码简洁,学习曲线平缓,适合初学者快速上手

环境准备

首先,安装FastAPI和运行服务器:

pip install fastapi uvicorn

uvicorn是FastAPI推荐的ASGI服务器,用于运行我们的API应用。

快速入门:第一个API

让我们从最简单的例子开始,创建一个返回欢迎信息的接口:

from fastapi import FastAPI

# 创建FastAPI应用实例
app = FastAPI(title="FastAPI示例")

# 定义一个GET请求接口,路径为"/"
@app.get("/")
async def root():
    return {"message": "欢迎使用FastAPI!访问/docs查看API文档"}

运行方式:在终端执行以下命令,服务器将在http://localhost:8000启动:

uvicorn main:app --reload

main是当前Python文件名,app是我们创建的FastAPI实例,--reload表示开发模式下自动重启服务器

GET方法实战:获取数据

假设我们要构建一个用户管理系统,首先实现”获取用户信息”的功能。

1. 获取指定ID的用户(路径参数)

from fastapi import FastAPI

app = FastAPI()

# 模拟数据库:用户列表
fake_users_db = [
    {"id": 1, "name": "张三", "age": 25},
    {"id": 2, "name": "李四", "age": 30},
    {"id": 3, "name": "王五", "age": 28}
]

# 定义GET请求,路径为"/users/{user_id}"
@app.get("/users/{user_id}")
async def get_user(user_id: int):  # user_id是路径参数,类型为整数
    """获取指定ID的用户信息"""
    # 在模拟数据库中查找用户
    for user in fake_users_db:
        if user["id"] == user_id:
            return user
    return {"error": "用户不存在"}

关键点
- 路径参数用{user_id}声明,函数参数直接写user_id: int(FastAPI会自动验证类型)
- 函数返回字典会被FastAPI自动序列化为JSON
- 路径参数类型验证:如果传入非整数,会自动返回422错误

2. 带查询参数的用户过滤

有时我们需要根据条件过滤用户,比如按姓名搜索:

@app.get("/users/filter")
async def filter_users(name: str = None, age: int = None):
    """过滤用户:按姓名和年龄筛选"""
    result = []
    for user in fake_users_db:
        if (name is None or user["name"] == name) and (age is None or user["age"] == age):
            result.append(user)
    return result

测试方式:访问http://localhost:8000/users/filter?name=张三,会返回所有姓名为”张三”的用户

POST方法实战:提交数据

使用POST方法创建新用户,需要接收JSON格式的用户数据。

1. 定义数据模型

FastAPI推荐使用Pydantic模型定义请求数据结构:

from pydantic import BaseModel

# 定义用户创建数据的模型
class UserCreate(BaseModel):
    name: str
    age: int
    email: str = None  # 可选字段

2. 实现创建用户接口

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.post("/users")
async def create_user(user: UserCreate):
    """创建新用户"""
    # 模拟用户ID生成(实际应用中可使用数据库自增ID)
    new_id = max([u["id"] for u in fake_users_db], default=0) + 1
    new_user = {
        "id": new_id,
        "name": user.name,
        "age": user.age,
        "email": user.email
    }
    fake_users_db.append(new_user)
    return {"message": "用户创建成功", "user": new_user}

关键点
- 使用@app.post装饰器定义POST接口
- 通过user: UserCreate接收JSON数据,FastAPI会自动验证数据格式
- Pydantic模型提供了强大的数据验证能力(如类型检查、必填字段验证)

自动API文档

FastAPI最贴心的功能之一是自动生成API文档,启动服务器后:

  • 访问http://localhost:8000/docs查看Swagger UI(交互式文档)
  • 访问http://localhost:8000/redoc查看ReDoc文档

在Swagger UI中,你可以直接输入参数、点击”Try it out”测试接口,非常适合开发和调试。

完整代码示例

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

# 创建应用实例
app = FastAPI(title="用户管理API")

# 模拟数据库
fake_users_db = [
    {"id": 1, "name": "张三", "age": 25, "email": "zhangsan@example.com"},
    {"id": 2, "name": "李四", "age": 30, "email": "lisi@example.com"}
]

# 定义用户创建数据模型
class UserCreate(BaseModel):
    name: str
    age: int
    email: str = None

# 根路径接口
@app.get("/")
async def root():
    return {"message": "欢迎使用用户管理API!访问/docs查看文档"}

# 获取用户接口
@app.get("/users/{user_id}")
async def get_user(user_id: int):
    """获取指定ID的用户信息"""
    for user in fake_users_db:
        if user["id"] == user_id:
            return user
    raise HTTPException(status_code=404, detail="用户不存在")

# 过滤用户接口
@app.get("/users/filter")
async def filter_users(name: str = None, age: int = None):
    """过滤用户:按姓名和年龄筛选"""
    result = []
    for user in fake_users_db:
        if (name is None or user["name"] == name) and (age is None or user["age"] == age):
            result.append(user)
    return result

# 创建用户接口
@app.post("/users")
async def create_user(user: UserCreate):
    """创建新用户"""
    new_id = max([u["id"] for u in fake_users_db], default=0) + 1
    new_user = {
        "id": new_id,
        "name": user.name,
        "age": user.age,
        "email": user.email
    }
    fake_users_db.append(new_user)
    return {"message": "用户创建成功", "user": new_user}

总结

通过这篇文章,我们学习了:

  1. FastAPI的基本安装和启动
  2. 使用GET方法处理路径参数和查询参数
  3. 使用POST方法处理JSON数据(Pydantic模型)
  4. 利用自动生成的API文档进行接口测试

FastAPI的核心优势在于:类型提示、自动数据验证、交互式文档,以及优秀的性能。对于初学者来说,它提供了”即学即用”的开发体验,让你能快速构建可靠的RESTful API。

现在,你可以尝试扩展这个示例:添加PUT(更新用户)和DELETE(删除用户)接口,或者连接到真实的数据库,体验完整的API开发流程!

小夜