跳转到内容

FastAPI

维基百科,自由的百科全书
FastAPI
Image
開發者Sebastián Ramírez
首次发布2018年12月5日,​7年前​(2018-12-05)[1]
当前版本0.143.3[2]在维基数据编辑(2026年10月16日)
源代码库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.143.3. 2026年10月16日 [2026年10月17日]. 
  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] (英语). 

外部链接

[编辑]