Shaw0xyz 发表于 2024-5-29 14:59:21

Python FastAPI 库基本使用指南

1. 引言

FastAPI是一个基于Python的现代Web框架,因其高性能和简单易用而备受欢迎。FastAPI使用Python 3.6及以上版本的类型提示和异步功能,使得构建快速、高效的API变得更加容易。本文将介绍FastAPI的基本使用方法,帮助读者快速上手这一强大的Web框架。

1.1 FastAPI的安装

在开始使用FastAPI之前,需要先安装它。推荐使用pip进行安装:

pip install fastapi
pip install "uvicorn"

Uvicorn是一个轻量级的ASGI服务器,用于运行FastAPI应用程序。

1.2 创建第一个FastAPI应用

创建一个名为app.py的文件,并在其中编写以下代码:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, World!"}

这个简单的应用定义了一个GET请求的根路径(/),返回一个包含问候消息的JSON响应。

1.3 运行FastAPI应用

使用Uvicorn运行FastAPI应用:

uvicorn app:app --reload

其中,app:app指的是app模块中的app实例。--reload选项用于在代码更改时自动重新加载服务器。

1.4 路由与请求处理

FastAPI支持多种HTTP方法(GET、POST、PUT、DELETE等)和路径参数。以下示例展示了如何定义多个路由和处理请求:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, World!"}

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

@app.post("/items/")
def create_item(name: str):
    return {"name": name}

1.5 数据验证与类型提示

FastAPI利用Pydantic进行数据验证和序列化。可以通过定义Pydantic模型来验证请求数据。以下示例展示了如何使用Pydantic模型:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
def create_item(item: Item):
    return item

在此示例中,定义了一个Item模型,并在POST请求中使用它来验证请求数据。

1.6 异步支持

FastAPI原生支持异步编程,可以使用async def定义异步路由处理函数:

import asyncio
from fastapi import FastAPI

app = FastAPI()

@app.get("/async")
async def read_async():
    await asyncio.sleep(1)
    return {"message": "This is an async response"}

1.7 自动生成文档

FastAPI自动生成交互式API文档,默认提供Swagger UI和ReDoc文档。启动应用后,可以通过以下URL访问文档:

Swagger UI: http://127.0.0.1:8000/docs
ReDoc: http://127.0.0.1:8000/redoc

1.8 中间件与依赖注入

FastAPI支持中间件和依赖注入,使得在请求处理过程中执行特定操作变得更加方便。以下是一个简单的中间件示例:

from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_custom_header(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Custom-Header"] = "Custom value"
    return response

1.9 结论

FastAPI是一个强大且高效的Web框架,通过类型提示和异步支持简化了API开发过程。本文介绍了FastAPI的基本使用方法,包括安装、路由与请求处理、数据验证、异步支持、自动生成文档以及中间件。希望本文能帮助读者快速上手FastAPI,并在实际项目中充分利用其优势。

页: [1]
查看完整版本: Python FastAPI 库基本使用指南