FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 支持。它具有异步处理能力,这使得它能够处理大量并发连接,同时保持响应速度快。本文将带你一步步学会FastAPI,并构建一个高效的API。
快速入门
安装FastAPI
首先,确保你的Python环境已经安装了pip。然后,使用以下命令安装FastAPI:
pip install fastapi uvicorn
创建项目
创建一个新的目录,用于存放你的FastAPI项目。在这个目录中,创建一个名为main.py的文件,这是你的主应用程序文件。
编写第一个API
在main.py中,编写以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
这段代码创建了一个简单的FastAPI应用,并定义了一个根路由/,当访问这个路由时,会返回一个包含消息的JSON对象。
运行应用
在终端中,运行以下命令来启动你的FastAPI应用:
uvicorn main:app --reload
这将启动一个开发服务器,并在浏览器中访问http://127.0.0.1:8000/,你应该能看到“Hello World”的消息。
高效API构建
路由和视图函数
FastAPI 使用路由和视图函数来定义API。路由定义了API的URL和HTTP方法,视图函数则处理请求并返回响应。
以下是一个包含多个路由的示例:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 404:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
@app.post("/items/")
async def create_item(item: Item):
# 这里可以添加保存item的逻辑
return item
数据模型
FastAPI 使用 Pydantic 库来定义数据模型。Pydantic 提供了数据验证和序列化功能。
以下是一个简单的数据模型示例:
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
description: str = None
price: float
tax: float = None
异步处理
FastAPI 支持异步处理,这意味着你可以使用异步函数来处理请求。这有助于提高应用的性能,特别是在处理大量并发请求时。
以下是一个异步视图函数的示例:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 404:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
中间件
FastAPI 支持中间件,允许你在请求处理过程中添加自定义逻辑。
以下是一个中间件的示例:
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def log_requests(request: Request, call_next):
print(f"Request: {request.method} {request.url}")
response = await call_next(request)
print(f"Response: {response.status_code}")
return response
实战案例
用户认证
FastAPI 支持多种认证机制,如 JWT、OAuth2、Session等。以下是一个使用JWT进行用户认证的示例:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: str
@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
# 这里可以添加验证用户逻辑
return {"access_token": "your_access_token", "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
# 这里可以添加验证token逻辑
return {"username": "your_username"}
数据库集成
FastAPI 可以与多种数据库集成,如 SQLite、PostgreSQL、MySQL等。以下是一个使用 SQLite 数据库的示例:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
import sqlite3
app = FastAPI()
class Item(BaseModel):
id: int
name: str
description: Optional[str] = None
price: float
@app.post("/items/")
async def create_item(item: Item):
# 这里可以添加保存item到数据库的逻辑
return item
@app.get("/items/{item_id}")
async def read_item(item_id: int):
# 这里可以添加从数据库获取item的逻辑
return {"item_id": item_id}
总结
FastAPI 是一个功能强大、易于使用的Web框架,可以帮助你快速构建高效的API。通过本文的学习,你应该已经掌握了FastAPI的基本用法,并能够将其应用于实际项目中。祝你学习愉快!
