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開發流程!

小夜