跳至內容

FastAPI

維基百科,自由的百科全書
FastAPI
開發者Sebastián Ramírez
首次發布2018年12月5日,​7年前​(2018-12-05)[1]
當前版本0.162.0[2]在維基數據編輯(2026年10月23日)
源代碼庫github.com/tiangolo/fastapi
編程語言Python
類型Web框架
許可協議MIT
網站fastapi.tiangolo.com

FastAPI是用Python 3.8+建造基於HTTP的服務API的Web框架[3]。它使用Pydantic和類型提示來確認、序列化和解序列化數據。FastAPI還為其建造的API自動生成OpenAPI文檔[4]。它首次發行於2018年。

構件

[編輯]

Pydantic

[編輯]

Pydantic是Python的數據確認庫。當在IDE中寫代碼的時候,Pydantic提供基於標註的類型提示[5]。FastAPI廣泛的利用Pydantic建模數據確認、序列化和自動API文檔。這些模型都使用標準的Python類型提示,它們提供了一種聲明性方式,用來規定到來請求(比如HTTP主體)和外出響應的數據的結構和類型[6]。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool | None = None

@app.post("/items/")
def create_item(item: Item):
    # The 'item' object is already validated and typed
    return {"message": "Item received", "item_name": item.name}

Starlette

[編輯]

Starlette是輕量級ASGI(英語:Asynchronous Server Gateway Interface)框架/工具箱,它支持Python中的async功能[7]。

Uvicorn

[編輯]

Uvicorn是針對async框架的小型低層服務器/應用Web服務器,它遵從ASGI規定[8]。在技術上,它實現了多進程模型,具有一個主進程,它負責管理工作進程池並將到來的HTTP請求發布給它們。工人進程的數目是預配置的,但也可以在運行時上下調整[9]。

OpenAPI集成

[編輯]

FastAPI為API自動生成OpenAPI文檔。這個文檔包括Swagger UI(英語:Swagger (software))和ReDoc二者,它們提供了交互式API文檔,人們可以實時探索並測試他們的端點。這對於同其他開發者或用戶開發、測試和共享API而言特別有用。Swagger UI可以默認訪問於/docs路由而ReDoc在/redoc路由[10]。

特徵

[編輯]

異步操作

[編輯]

FastAPI的架構固有的支持異步編程(英語:Asynchrony (computer programming))。這種設計允許用單線程的事件循環來有效處理大量的並發請求,特別是在處理I/O密集(英語:I/O bound)操作如數據庫查詢或外部API調用的時候。

依賴注入

[編輯]

FastAPI結合了依賴注入系統,用來管理並向HTTP端點提供服務。這種機制允許開發者將構件比如數據庫會話或驗證邏輯聲明為函數參數。FastAPI為每個請求自動解析這些依賴,注入所需的實例[11]。

from fastapi import Depends, HTTPException, status
from db import DbSession

# --- Dependency for Database Session ---
def get_db():
    db = DbSession()
    try:
        yield db
    finally:
        db.close()

@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item(name: str, description: str, db: DbSession = Depends(get_db)):
    new_item = Item(name=name, description=description)
    db.add(new_item)
    db.commit()
    db.refresh(new_item)
    return {"message": "Item created successfully!", "item": new_item}

@app.get("/items/{item_id}")
def read_item(item_id: int, db: DbSession = Depends(get_db)):
    item = db.query(Item).filter(Item.id == item_id).first()
    if item is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
    return item

WebSockets支持

[編輯]

WebSocket允許在客戶和服務器之間的全雙工通信。這種能力對於要求持續數據交換的應用而言是根本性的,比如即時通訊平台、實時數據儀錶盤或多人在線遊戲。FastAPI憑藉底層Starlette實現,允許對連接和消息處理的有效管理[12]。

# You must have 'websockets' package installed
from fastapi import WebSocket

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

後台任務

[編輯]

FastAPI確使在已經將HTTP響應發送給客戶之後能執行後台任務。這允許API立即響應用戶請求,卻同時在後台處理非緊要或耗時的操作。典型應用包括發送郵件通知,更新緩存或進行數據後處理[13]。

import time
import shutil
from fastapi import BackgroundTasks, UploadFile, File
from utils import generate_thumbnail

@app.post("/upload-image/")
async def upload_image(
        image: UploadFile = File(...),
        background_tasks: BackgroundTasks):
    file_location = f"uploaded_images/{image.filename}"
    # Save uploaded image
    with open(image_path, "wb") as f:
        contents = await file.read()
        f.write(contents)
    # Add thumbnail generation as a background task
    background_tasks.add_task(generate_thumbnail, file_location, "200x200")
    return {"message": f"Image '{image.filename}' uploaded. Thumbnail generation started in background."}

例子

[編輯]

下述代碼展示了一個簡單的Web應用,它在被訪問時顯示"Hello, World!":

# Import FastAPI class from the fastapi package
from fastapi import FastAPI

# Create an instance of the FastAPI app
app = FastAPI()

# Define a GET route for the root URL ("/")
@app.get("/")
async def read_root() -> str:
    # Return a plain text response
    return "Hello, World!"

參見

[編輯]

引用

[編輯]
  1. ^ fastapi repo. GitHub. 2018-12-05. 
  2. ^ Release 0.162.0. 2026年10月23日 [2026年10月24日]. 
  3. ^ FastAPI. fastapi.tiangolo.com. [2024-04-10]. 
  4. ^ Lubanovic, Bill. Introducing Python: Modern Computing in Simple Packages 2nd. O'Reilly Media, Inc. 2019-11-06: 397, 418. ISBN 9781492051367. 
  5. ^ Why use Pydantic - Pydantic. docs.pydantic.dev. [2023-09-21]. 
  6. ^ Request Body - FastAPI. fastapi.tiangolo.com. [2025-06-30] (英語). 
  7. ^ Starlette is a lightweight ASGI framework/toolkit, which is ideal for building async web services in Python. 
  8. ^ Uvicorn is an ASGI web server implementation for Python. 
  9. ^ Restarting 'uvicorn' Workers with the 'SIGHUP' Signal. bugfactory.io. [2024-06-17]. 
  10. ^ OpenAPI docs - FastAPI. 
  11. ^ Dependencies. [30 June 2025]. 
  12. ^ WebSockets - FastAPI. fastapi.tiangolo.com. [2025-06-30] (英語). 
  13. ^ Background Tasks - FastAPI. fastapi.tiangolo.com. [2025-06-30] (英語). 

外部連結

[編輯]