fastAPI
时间: 2025-05-30 08:12:10 浏览: 15
### FastAPI 使用指南
FastAPI 是一种现代、快速(高性能)、基于 Python 的 Web 开发框架,特别适合构建 API 接口。以下是关于 FastAPI 的一些核心概念和常见问题解答。
#### 1. 安装与环境准备
要开始使用 FastAPI,首先需要安装它以及 ASGI 服务器(如 Uvicorn)。可以通过 pip 进行安装:
```bash
pip install fastapi uvicorn
```
启动应用时可以运行如下命令[^3]:
```bash
uvicorn main:app --reload
```
这里的 `main` 表示包含 FastAPI 实例的应用文件名,而 `--reload` 参数用于开发模式下的自动重载功能。
---
#### 2. 创建基本的 FastAPI 应用程序
下面是一个简单的 FastAPI 示例代码,展示了如何定义路径操作函数并返回 JSON 数据:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, this is a basic FastAPI app."}
```
此代码创建了一个根路径 `/` 并响应 GET 请求,返回消息 `"Hello, this is a basic FastAPI app."`[^3]。
---
#### 3. 路径参数与查询参数
通过路径参数传递动态数据非常简单。例如,获取用户的 ID 可以这样实现:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
```
如果希望支持可选的查询参数,则可以在函数签名中指定默认值为 None:
```python
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
def read_item(item_id: str, q: Union[str, None] = None):
result = {"item_id": item_id}
if q:
result.update({"q": q})
return result
```
这里引入了 `typing.Union` 来表示可能为空的情况[^3]。
---
#### 4. 数据验证与 Pydantic 模型
Pydantic 提供强大的数据校验能力,集成到 FastAPI 中可以帮助开发者轻松处理输入输出的数据结构化需求。以下是如何定义一个请求体模型的例子:
```python
from pydantic import BaseModel
from fastapi import FastAPI
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item.dict()
```
在这个例子中,`Item` 类继承自 `BaseModel`,并通过字段声明指定了必要的属性及其类型约束[^3]。
---
#### 5. 认证与授权机制
对于涉及敏感信息的操作,通常需要加入认证逻辑来保护资源访问权限。推荐使用的库之一是 `fastapi-auth`[^2],它可以方便地集成 OAuth2 和其他身份验证方式。
假设已经集成了 JWT Token 验证方案,那么受保护端点看起来像这样:
```python
from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends, HTTPException, status
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def authenticate_user(token: str = Depends(oauth2_scheme)):
if token != "valid_token":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return True
@app.get("/protected-resource", dependencies=[Depends(authenticate_user)])
def protected_resource():
return {"data": "This resource requires valid auth"}
```
上述片段展示了一种依赖注入的方式来进行用户鉴权检查。
---
#### 6. 文件上传与下载支持
当涉及到多媒体内容传输时,FastAPI 同样提供了简洁易懂的方法完成这些任务。比如允许客户端提交图片文件至服务器存储目录下:
```python
from fastapi import File, UploadFile, FastAPI
app = FastAPI()
@app.post("/uploadfile/")
async def upload_file(file: UploadFile = File(...)):
contents = await file.read() # Read the entire content of uploaded file.
saved_path = f"/tmp/{file.filename}"
with open(saved_path, 'wb') as destination:
destination.write(contents)
return {"filename": file.filename, "saved_at": saved_path}
```
同时也可以让浏览器直接预览或者下载远程文档链接:
```python
from starlette.responses import FileResponse
@app.get("/download/{file_name:path}")
def download_file(file_name: str):
path_to_file = "/path/to/files/" + file_name
return FileResponse(path=path_to_file, filename=file_name)
```
以上两段分别演示了接收二进制流保存本地磁盘以及按需分发静态资产的功能[^3]。
---
#### 7. 错误处理最佳实践
为了提升用户体验,在遇到异常状况时应该给出明确提示而不是暴露底层细节给外部调用者。利用 FastAPI 自带工具箱能够很好地达成目标:
```python
from fastapi import Request, Response, FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return PlainTextResponse(str(exc), status_code=400)
# Add CORS middleware to allow cross-origin requests safely.
origins = ["*"]
app.add_middleware(CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
```
这段脚本设置了全局范围内的错误处理器,并启用了跨域资源共享策略以便于前端项目对接后端服务。
---
### 总结
本文介绍了有关 FastAPI 的基础知识点,包括但不限于其初始化过程、路由设计原则、内置中间件运用技巧等方面的内容。此外还提及了一些高级特性诸如安全控制措施、异步 I/O 支持等主题。希望对你有所帮助!
阅读全文
相关推荐
















