FastAPI 基础:安装、项目结构与第一个 API

开发
FastAPI 是一个高性能、基于类型提示的现代 Web 框架,具备自动生成 API 文档、数据验证和异步支持等特性。

FastAPI 是一个高性能、基于类型提示的现代 Web 框架,具备自动生成 API 文档、数据验证和异步支持等特性。

在本篇文章中,你将学到:

  • 如何安装 FastAPI 并运行你的第一个 API
  • 标准的 FastAPI 项目结构
  • 如何拆分 API 代码,提高可维护性

1. 安装 FastAPI

FastAPI 依赖 Python 3.7+,你可以使用 pip 进行安装:

pip install fastapi
  • 1.

FastAPI 需要一个 ASGI 服务器来运行,我们使用 Uvicorn:

pip install uvicorn
  • 1.

Uvicorn 是 FastAPI 推荐的高性能 ASGI 服务器,支持并发处理!

2. 规划 FastAPI 项目结构

在开发实际项目时,建议使用模块化结构,方便扩展与维护:

fastapi_project/
│── app/
│   ├── main.py          # 入口文件
│   ├── routes/          # 路由管理
│   │   ├── users.py     # 用户相关 API
│   │   ├── items.py     # 物品相关 API
│   ├── models/          # 数据库模型
│   │   ├── user.py      # 用户模型
│   ├── schemas/         # Pydantic 数据验证
│   ├── services/        # 业务逻辑层
│   ├── dependencies.py  # 依赖注入
│   ├── config.py        # 配置文件
│── requirements.txt     # 依赖包
│── .env                 # 环境变量
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

为什么这样组织代码?

  • routes/ 👉 负责 API 逻辑,按功能拆分
  • models/ 👉 定义数据库表结构(ORM)
  • schemas/ 👉 负责请求和响应数据校验(Pydantic)
  • services/ 👉 处理核心业务逻辑
  • dependencies.py 👉 依赖注入,提升代码复用性
  • config.py 👉 统一管理配置文件

推荐使用这种结构,避免 main.py 变得臃肿,提高代码可维护性!

3. 编写你的第一个 FastAPI API

(1) 创建 main.py

from fastapi import FastAPI

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

# 定义 API 端点
@app.get("/")
def read_root():
    return {"message": "🚀 Hello, FastAPI!"}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

这个 API 处理 GET / 请求,并返回 JSON 响应:

{"message": "🚀 Hello, FastAPI!"}
  • 1.

(2) 运行 FastAPI 服务器

uvicorn app.main:app --reload
  • 1.
  • app.main:app:表示 main.py 中的 app 实例
  • --reload:启用热重载,代码变更后无需手动重启

启动后,你可以访问:

  • 主页 API: http://127.0.0.1:8000/
  • Swagger API 文档: http://127.0.0.1:8000/docs
  • ReDoc API 文档: http://127.0.0.1:8000/redoc

FastAPI 内置 API 文档,省去手写文档的烦恼!

4. 组织 API 路由

为了更好地管理 API,我们将 API 拆分到 routes/ 目录下。

(1) 创建 app/routes/items.py

from fastapi import APIRouter

router = APIRouter()

@router.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

(2) 在 main.py 中注册路由

from fastapi import FastAPI
from app.routes import items

app = FastAPI()

# 注册 API 路由
app.include_router(items.router, prefix="/api")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

现在,你可以访问 http://127.0.0.1:8000/api/items/1 进行测试!

5. FastAPI 的异步支持

FastAPI 原生支持 async/await,提高并发能力!例如,我们可以用 async def 让 API 异步运行:

from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/async")
async def async_example():
    await asyncio.sleep(2)  # 模拟异步任务
    return {"message": "异步任务完成!"}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

这样,FastAPI 能同时处理多个请求,而不会阻塞主线程!

6. 解析请求参数(路径参数 & 查询参数)

(1) 路径参数

@app.get("/users/{user_id}")
def read_user(user_id: int):
    return {"user_id": user_id}
  • 1.
  • 2.
  • 3.

访问 http://127.0.0.1:8000/users/10,返回:

{"user_id": 10}
  • 1.

(2) 查询参数

@app.get("/search/")
def search(q: str, limit: int = 10):
    return {"query": q, "limit": limit}
  • 1.
  • 2.
  • 3.

访问 http://127.0.0.1:8000/search/?q=FastAPI&limit=5,返回:

{"query": "FastAPI", "limit": 5}
  • 1.

7. 结论:FastAPI 让 API 开发更简单!

FastAPI 优势总结:

  • 超快性能(比 Flask 快 3~5 倍)
  • 自动生成 API 文档(Swagger & ReDoc)
  • 基于类型提示,代码更清晰
  • 原生支持异步 async/await
责任编辑:赵宁宁 来源: Ssoul肥鱼
相关推荐

2010-08-04 13:16:23

Flex项目

2023-09-21 22:43:17

Django框架

2021-11-02 08:00:00

机器学习API技术

2010-07-30 14:50:38

Flex项目

2015-04-17 09:18:35

JavaiOS

2011-06-24 13:38:32

QT 编译 安装

2025-01-13 00:00:10

SwaggerAI项目

2021-04-07 13:38:27

Django项目视图

2023-06-01 08:24:08

OpenAIChatGPTPython

2013-01-14 09:44:58

JavaScriptJSJS框架

2011-03-03 21:04:08

bug程序员

2011-03-21 14:24:13

Debian 6

2012-02-08 11:15:38

HibernateJava

2010-07-30 14:58:06

Flex应用

2017-11-16 14:31:21

LinuxLinux LiteLinux 4.14

2022-10-17 10:28:05

Web 组件代码

2009-10-23 09:21:08

2013-10-30 22:10:28

Clouda程序

2009-09-22 10:00:08

曙光BBSBBS站

2021-03-24 08:00:44

项目Vue 3Typescript
点赞
收藏

51CTO技术栈公众号