FastAPI实战案例:用50行代码构建简单博客API

FastAPI是一个现代、高性能的Python API框架,它基于标准Python类型提示,支持异步操作,并能自动生成交互式API文档。对于初学者来说,FastAPI的简洁语法和强大功能使其成为快速构建API的理想选择。

今天我们将用50行代码实现一个简单的博客API,包含最基础的文章管理功能:创建、查询、更新和删除文章。

一、准备工作

首先确保安装了必要的库:

pip install fastapi uvicorn

二、代码实现

1. 导入依赖

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

2. 创建FastAPI应用实例

app = FastAPI(title="简单博客API")

3. 定义数据模型(Pydantic)

使用Pydantic定义文章的数据结构,确保数据验证和类型检查:

class PostCreate(BaseModel):
    """创建文章的请求数据模型"""
    title: str
    content: str

class PostResponse(BaseModel):
    """文章响应数据模型"""
    id: int
    title: str
    content: str

4. 模拟数据库(内存存储)

用列表模拟数据库存储文章数据:

posts = [
    {"id": 1, "title": "FastAPI基础", "content": "FastAPI是一个高性能Python框架..."},
    {"id": 2, "title": "Python异步编程", "content": "异步编程可以提高API并发处理能力..."},
]

5. 实现API端点

获取所有文章

@app.get("/posts", response_model=list[PostResponse])
def get_all_posts():
    """获取所有文章列表"""
    return posts

获取单篇文章

@app.get("/posts/{post_id}", response_model=PostResponse)
def get_single_post(post_id: int):
    """根据ID获取单篇文章"""
    for post in posts:
        if post["id"] == post_id:
            return post
    raise HTTPException(status_code=404, detail="文章不存在")

创建文章

@app.post("/posts", response_model=PostResponse, status_code=201)
def create_post(new_post: PostCreate):
    """创建新文章"""
    new_id = len(posts) + 1
    created_post = {
        "id": new_id,
        "title": new_post.title,
        "content": new_post.content
    }
    posts.append(created_post)
    return created_post

更新文章

@app.put("/posts/{post_id}", response_model=PostResponse)
def update_post(post_id: int, updated_post: PostCreate):
    """更新文章内容"""
    for post in posts:
        if post["id"] == post_id:
            post["title"] = updated_post.title
            post["content"] = updated_post.content
            return post
    raise HTTPException(status_code=404, detail="文章不存在")

删除文章

@app.delete("/posts/{post_id}", status_code=204)
def delete_post(post_id: int):
    """删除文章"""
    global posts
    for i, post in enumerate(posts):
        if post["id"] == post_id:
            del posts[i]
            return  # 204状态码不需要返回内容
    raise HTTPException(status_code=404, detail="文章不存在")

三、运行与测试

将上述代码保存为main.py,然后运行:

uvicorn main:app --reload

访问自动生成的API文档:http://localhost:8000/docs,即可在浏览器中测试所有API端点。

四、核心知识点总结

  1. 路由定义:使用@app.get()/@app.post()等装饰器定义API端点
  2. 参数验证:FastAPI自动根据函数参数类型验证输入数据
  3. 数据模型:通过Pydantic的BaseModel定义请求/响应结构,实现数据校验
  4. 状态码:使用status_code参数指定HTTP响应状态码(如201创建成功、404不存在)
  5. 自动文档:FastAPI自动生成Swagger UI和ReDoc文档,方便测试和调试

五、扩展方向

  • 添加数据库(如SQLite/PostgreSQL)持久化数据
  • 实现用户认证(JWT或OAuth2)
  • 添加分页、排序功能
  • 增加文章分类和标签

这个简单的博客API仅用50行代码就实现了完整的文章管理功能,展示了FastAPI的核心优势。通过这个案例,你可以快速上手FastAPI的基础使用,并逐步扩展更复杂的功能。

小夜