Python基础入门 Day50:使用 FastAPI 构建现代 Web API 服务

95次阅读
没有评论

共计 1102 个字符,预计需要花费 3 分钟才能阅读完成。

FastAPI 是一个用于构建 API 的现代、快速(高性能)Web 框架,它基于 Python 3.7+ 的类型提示,构建在 Starlette 和 Pydantic 上。它兼顾高性能与开发效率,成为近年开发 RESTful 服务的首选之一。

一、安装 FastAPI 和 uvicorn
FastAPI 本身是框架,uvicorn 是 ASGI 的服务器实现:

pip install fastapi uvicorn

二、最小示例
下面是一个简单的 Hello World 级别的 API:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello FastAPI"}

运行服务:

uvicorn main:app --reload

访问:http://127.0.0.1:8000/

三、自动生成 API 文档
FastAPI 自带交互式 API 文档界面:

这些文档会根据你的接口和类型注解自动生成,极大提升调试与对接效率。

四、路径参数与查询参数

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

五、请求体(POST)与数据模型
FastAPI 使用 Pydantic 定义数据模型并自动校验数据:

from pydantic import BaseModel

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

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

请求体 JSON 自动转为 Item 实例,并进行字段校验。

六、异步支持
FastAPI 原生支持 async/await,适合 IO 密集型场景(如数据库、爬虫等)。

七、中间件和依赖注入
支持中间件、路由分组、依赖注入等企业级功能,利于大型项目开发。

八、实战应用场景

  • 快速构建数据接口
  • 支持 JWT 的权限认证系统
  • 可接入数据库 ORM(如 SQLAlchemy、Tortoise ORM)
  • 支持 WebSocket、GraphQL 等扩展场景

FastAPI 兼具 Flask 的开发简洁性和 aiohttp 的高性能,是目前 Python Web API 领域的首选之一。明天将介绍如何使用 FastAPI 与数据库集成,构建完整的数据接口服务。

正文完
 0
评论(没有评论)