FastAPI 简介
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 支持。它旨在提供高性能和简洁的 API 开发体验。FastAPI 使用标准 Python 类型注解来定义端点,这使得代码更易于编写、阅读和维护。
快速入门
安装 FastAPI
首先,确保你已经安装了 Python 3.6 或更高版本。然后,使用 pip 安装 FastAPI:
pip install fastapi
创建第一个 FastAPI 应用
创建一个新的 Python 文件,例如 main.py,并添加以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
运行该文件:
uvicorn main:app --reload
打开浏览器并访问 http://127.0.0.1:8000/,你将看到 “Hello World” 信息。
路由和端点
FastAPI 允许你通过装饰器来创建路由和端点。下面是一些常见的路由类型:
@app.get():处理 HTTP GET 请求@app.post():处理 HTTP POST 请求@app.put():处理 HTTP PUT 请求@app.delete():处理 HTTP DELETE 请求
参数
你可以使用参数来传递数据到你的端点:
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
在这个例子中,item_id 是一个路径参数,它是一个整数。
数据验证
FastAPI 使用 Pydantic 来验证传入的数据。下面是一个简单的例子:
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item):
return item
在这个例子中,我们定义了一个 Pydantic 模型 Item,它包含 name、description、price 和 tax 字段。当用户发送 POST 请求到 /items/ 时,FastAPI 会自动验证传入的数据。
异步支持
FastAPI 支持异步操作,这意味着你可以使用 async 和 await 关键字。下面是一个异步函数的例子:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
item = await get_item_by_id(item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
在这个例子中,get_item_by_id 是一个异步函数,它负责从数据库中获取项目。
实战案例
创建一个简单的博客系统
在这个案例中,我们将创建一个包含以下功能的简单博客系统:
- 创建帖子
- 获取帖子列表
- 获取单个帖子
- 删除帖子
首先,我们需要定义一个 Pydantic 模型来表示帖子:
class Post(BaseModel):
title: str
content: str
published_at: datetime.datetime
然后,我们可以使用 FastAPI 创建端点来处理这些操作:
@app.post("/posts/")
async def create_post(post: Post):
# 保存帖子到数据库
# ...
return post
@app.get("/posts/")
async def get_posts():
# 获取所有帖子
# ...
return posts
@app.get("/posts/{post_id}")
async def get_post(post_id: int):
# 获取单个帖子
# ...
return post
@app.delete("/posts/{post_id}")
async def delete_post(post_id: int):
# 删除帖子
# ...
return {"detail": "Post deleted"}
创建一个用户认证系统
在这个案例中,我们将创建一个简单的用户认证系统,支持用户注册、登录和验证令牌。
首先,我们需要定义一个 Pydantic 模型来表示用户:
class User(BaseModel):
username: str
email: str
password: str
然后,我们可以使用 FastAPI 创建端点来处理这些操作:
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# 验证用户
# ...
return {"access_token": "token", "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
# 获取当前用户信息
# ...
return user
总结
在这个教程中,我们介绍了 FastAPI 的基本概念和功能,并提供了入门教程和实战案例。希望这个教程能帮助你快速掌握 FastAPI 框架,并在实际项目中应用它。
