主页
文章
分类
标签
关于
Fastapi的基础实验
发布于: 2025-7-2   更新于: 2025-7-2   收录于: Fastapi
文章字数: 1176   阅读时间: 3 分钟   阅读量:

实验前提

  • 基于 Python 3.10+,使用 venvconda 虚拟环境
  • 核心依赖:fastapi + uvicorn + pydantic

一、环境配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 创建虚拟环境(任选其一)
python -m venv venv          # venv
conda create -n fastapi_env python=3.10  # conda

# 激活环境
source venv/bin/activate     # Linux (venv)
.\venv\Scripts\activate      # Windows (venv)
conda activate fastapi_env   # conda

# 安装依赖
pip install fastapi uvicorn pydantic

二、第一个 FastAPI 应用

main.py

1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()  # 创建应用实例

@app.get("/")  # 路由装饰器
async def root():
    return {"message": "Hello World!"}

运行服务:

1
uvicorn main:app --reload
  • main:appmain.py 中的 app 实例
  • --reload:代码修改时自动重启,方便开发

访问 http://127.0.0.1:8000 查看结果
自动文档:http://127.0.0.1:8000/docs Swagger UI

自动 API 文档

FastAPI 自动生成两套文档:

路径 工具
/docs Swagger UI 交互式文档
/redoc ReDoc 简洁式文档

支持:

  • 在线测试 API
  • 查看请求/响应模型
  • 自动填充参数

注意:如果访问docs一片空白,说明网络有问题,因为docs需要读取页面文件,服务器在外网,可能读不了


三、路由 与 HTTP 方法

FastAPI 使用装饰器绑定 URL 路径与处理函数:

装饰器 HTTP 方法
@app.get() GET
@app.post() POST
@app.put() PUT
@app.delete() DELETE

四、参数类型

1. 路径参数(Path Parameters)

  • 出现在 URL 路径中,如 /user/123
  • 在函数参数中直接声明,类型注解可自动校验
1
2
3
@app.get("/user/{user_id}")
async def get_user(user_id: int): 
    return {"user_id": user_id}

如果需要更多的限制,使用fastapi的路径类型注解 Path

1
2
3
4
5
from fastapi import Path

@app.get("/user/{user_id}")
async def get_user(user_id: int = Path(title="this is uesr id", ge=1, le=100)): 
    return {"user_id": user_id}

Path可以为路径参数做更多的限制,比如ge为大于等于,le为小于等于


2. 查询参数(Query Parameters)

  • 出现在 ? 后,如 /user?limit=10&skip=0
  • 函数参数名即为查询参数名
1
2
3
@app.get("/user")
async def list_users(limit: int = 10, skip: int = 0):
    return {"limit": limit, "skip": skip}

注意:默认值可选;无默认值则为必填

和路径参数一样,查询参数也可以做更多的限制,需要使用fastapi的查询参数注解Query

1
2
3
4
5
6
@app.get("/user")
async def list_users(
    skip: int = Query(default=1, ge=0, le=10),
    limit: int = Query(default=1, ge=0, le=50)
):
    return {"limit": limit, "skip": skip}

3. 请求体参数(Request Body)

需使用 Pydantic 模型 定义数据结构:

1
2
3
4
5
6
7
8
9
from pydantic import BaseModel

class UserCreate(BaseModel):
    name: str
    age: int

@app.post("/user")
async def create_user(user: UserCreate):  
    return {"name": user.name, "age": user.age}

如果需要对模型参数有更多的约束,使用PydanticField

1
2
3
4
5
from pydantic import BaseModel, Field

class UserCreate(BaseModel):
    name: str = Field(default="张三", min_length=2, max_length=10) # 默认值为张三,最短2个字,最长3个字
    age: int = Field(..., ge=1, le=100) # 大于等于1岁 小于等于100岁

五、响应(Response)

1. 默认响应

  • 返回字典/Pydantic 模型 → 自动转为 JSONResponse
  • 状态码默认为 200

2. 自定义响应类型

方法一:装饰器指定

1
2
3
4
5
from fastapi.responses import HTMLResponse

@app.get("/html", response_class=HTMLResponse)
async def get_html():
    return "<h1>Hello HTML</h1>"

方法二:函数内返回响应对象

1
2
3
4
5
from fastapi.responses import FileResponse

@app.get("/image")
async def get_image():
    return FileResponse("image.png")

常用响应类:

  • JSONResponse
  • HTMLResponse
  • FileResponse
  • StreamingResponse(流式响应)

3. 响应模型(Response Model)

response_model 指定返回结构,自动过滤多余字段,缺少字段则会报错:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class News(BaseModel):
    id: int
    title: str
    content: str

@app.get("/news/{id}", response_model= News)
async def get_news(id: int):
    return {
        "id": id,
        "title": f"News {id}",
        "content": "Content...",
        "secret": "hidden"  # 会自动过滤掉
    }

六、异常处理

使用 HTTPException 抛出自定义错误:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from fastapi import HTTPException

@app.get("/item/{item_id}")
async def get_item(item_id: int):
    if item_id <= 0:
        raise HTTPException(
            status_code=400,
            detail="Item ID must be positive"
        )
    return {"item_id": item_id}

自动返回 JSON 格式的错误响应