跳到主要内容

FastAPI 安装配置

本章介绍如何安装 FastAPI 并配置开发环境。

系统要求

  • Python 3.8 或更高版本
  • pip 包管理器

推荐使用 Python 3.10+ 以获得最佳的类型提示支持。

安装 FastAPI

标准安装(推荐)

# 安装 FastAPI 及所有标准依赖
pip install "fastapi[standard]"

这会安装以下组件:

  • FastAPI:核心框架
  • Uvicorn:ASGI 服务器
  • Pydantic:数据验证
  • 其他工具:email-validator、httpx 等

最小安装

如果只需要核心功能:

pip install fastapi uvicorn

使用虚拟环境(推荐)

# 创建虚拟环境
python -m venv .venv

# 激活虚拟环境
# Windows
.venv\Scripts\activate
# macOS/Linux
source .venv/bin/activate

# 安装 FastAPI
pip install "fastapi[standard]"

使用 Poetry

# 创建新项目
poetry new my-api
cd my-api

# 添加依赖
poetry add "fastapi[standard]"

# 激活环境
poetry shell

验证安装

# test_install.py
import fastapi
import uvicorn
import pydantic

print(f"FastAPI 版本: {fastapi.__version__}")
print(f"Uvicorn 版本: {uvicorn.__version__}")
print(f"Pydantic 版本: {pydantic.__version__}")

运行测试:

python test_install.py

运行第一个应用

创建 main.py

from fastapi import FastAPI

# 创建 FastAPI 实例
app = FastAPI()

# 定义路由
@app.get("/")
async def root():
return {"message": "Hello, FastAPI!"}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}

使用 FastAPI CLI(推荐)

# 开发模式(自动重载)
fastapi dev main.py

# 生产模式
fastapi run main.py

输出:

╭────────── FastAPI CLI - Development mode ───────────╮
│ │
│ Serving at: http://127.0.0.1:8000 │
│ │
│ API docs: http://127.0.0.1:8000/docs │
│ │
╰─────────────────────────────────────────────────────╯

使用 Uvicorn 直接运行

# 开发模式
uvicorn main:app --reload

# 指定端口和主机
uvicorn main:app --host 0.0.0.0 --port 8080

# 生产模式(多 worker)
uvicorn main:app --workers 4

项目结构

小型项目结构

my_api/
├── main.py # 主应用文件
├── requirements.txt # 依赖列表
└── .env # 环境变量(可选)

中型项目结构

my_api/
├── main.py # 应用入口
├── routers/ # 路由模块
│ ├── __init__.py
│ ├── users.py
│ └── items.py
├── models/ # 数据模型
│ ├── __init__.py
│ └── schemas.py
├── services/ # 业务逻辑
│ └── __init__.py
├── config.py # 配置管理
├── requirements.txt
└── .env

大型项目结构

my_api/
├── app/
│ ├── __init__.py
│ ├── main.py # 应用入口
│ ├── core/ # 核心配置
│ │ ├── __init__.py
│ │ ├── config.py # 配置
│ │ └── security.py # 安全相关
│ ├── api/ # API 路由
│ │ ├── __init__.py
│ │ ├── deps.py # 依赖
│ │ └── v1/ # API 版本
│ │ ├── __init__.py
│ │ └── endpoints/
│ │ ├── users.py
│ │ └── items.py
│ ├── models/ # 数据库模型
│ │ └── __init__.py
│ ├── schemas/ # Pydantic 模型
│ │ └── __init__.py
│ ├── services/ # 业务逻辑
│ │ └── __init__.py
│ └── utils/ # 工具函数
│ └── __init__.py
├── tests/ # 测试
│ └── test_main.py
├── alembic/ # 数据库迁移
├── pyproject.toml # 项目配置
└── README.md

配置管理

使用环境变量

# config.py
import os
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
"""应用配置"""
app_name: str = "FastAPI Application"
debug: bool = False
database_url: str = "sqlite:///./app.db"

class Config:
env_file = ".env"

settings = Settings()
# main.py
from fastapi import FastAPI
from config import settings

app = FastAPI(
title=settings.app_name,
debug=settings.debug
)

@app.get("/info")
async def info():
return {"app_name": settings.app_name}

.env 文件

# .env
APP_NAME=我的API
DEBUG=true
DATABASE_URL=postgresql://user:pass@localhost/db

开发工具配置

VS Code 配置

.vscode/launch.json

{
"version": "0.2.0",
"configurations": [
{
"name": "FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"main:app",
"--reload"
],
"jinja": true
}
]
}

requirements.txt

fastapi[standard]>=0.109.0
python-dotenv>=1.0.0
pydantic-settings>=2.0.0

# 开发依赖
pytest>=7.0.0
httpx>=0.25.0
black>=23.0.0
ruff>=0.1.0
mypy>=1.0.0

pyproject.toml(Poetry)

[tool.poetry]
name = "my-api"
version = "0.1.0"
description = "My FastAPI Application"

[tool.poetry.dependencies]
python = "^3.10"
fastapi = {extras = ["standard"], version = "^0.109.0"}
pydantic-settings = "^2.0.0"

[tool.poetry.group.dev.dependencies]
pytest = "^7.0.0"
httpx = "^0.25.0"
black = "^23.0.0"
ruff = "^0.1.0"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

常见问题

1. 端口被占用

# 查找占用端口的进程
# Windows
netstat -ano | findstr :8000
taskkill /PID <pid> /F

# macOS/Linux
lsof -i :8000
kill -9 <pid>

# 或使用其他端口
uvicorn main:app --port 8001

2. 模块找不到

确保在项目根目录运行,或将项目添加到 Python 路径:

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))

3. 热重载不工作

检查文件是否在监控目录下:

uvicorn main:app --reload --reload-dir ./app

小结

本章我们学习了:

  1. FastAPI 的安装方式
  2. 使用 FastAPI CLI 和 Uvicorn 运行应用
  3. 项目结构组织
  4. 配置管理
  5. 开发工具配置

练习

  1. 创建一个 FastAPI 项目并成功运行
  2. 使用环境变量配置应用名称
  3. 访问自动生成的 API 文档页面
  4. 组织一个小型项目的文件结构