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的基礎使用,並逐步擴展更復雜的功能。

小夜