0%

FastAPI自学教程(2)- Hello World

1. 最小化应用示例

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

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

# 根路由(同步/异步函数均可)
@app.get("/")
async def root():
return {"message": "Hello World"}

2. 运行开发服务器

1
uvicorn main:app --reload
  • main: 模块文件名(不含.py)
  • app: FastAPI实例变量名
  • --reload: 开发模式自动重载(生产环境移除)

3. 访问验证

  • API响应http://127.0.0.1:8000 ➔ 返回JSON数据
  • 交互文档
    • Swagger UI:http://127.0.0.1:8000/docs
    • ReDoc:http://127.0.0.1:8000/redoc

4. 路径参数示例

1
2
3
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
  • 类型验证:自动转换URL参数为整数类型
  • 错误处理:输入非数字时返回详细错误

5. 查询参数示例

1
2
3
@app.get("/items/")
async def list_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
  • 默认参数:http://127.0.0.1:8000/items/ 自动应用默认值
  • 显式传参:http://127.0.0.1:8000/items/?skip=20&limit=30

6. 核心优势

  1. 自动文档:基于OpenAPI标准生成交互式文档
  2. 类型安全:基于Python类型声明自动数据验证
  3. 开发高效
    • 代码自动补全支持
    • 错误反馈详细
  4. 高性能:基于Starlette(ASGI框架)和Pydantic

7. 进阶准备

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 组合使用路径参数和查询参数
@app.get("/users/{user_id}/items/{item_id}")
async def get_user_item(
user_id: int,
item_id: str,
q: str = None,
short: bool = False
):
item = {"item_id": item_id, "owner_id": user_id}
if q:
item.update({"q": q})
if not short:
item.update({"description": "示例描述"})
return item