安装与配置 #

环境要求 #

Python 版本 #

FastAPI 需要 Python 3.8 或更高版本。推荐使用 Python 3.10+ 以获得最佳体验。

text
┌─────────────────────────────────────────────────────────────┐
│                    Python 版本要求                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   Python 3.8   ✅ 最低要求                                   │
│   Python 3.9   ✅ 支持                                       │
│   Python 3.10  ✅ 推荐(更好的类型提示)                       │
│   Python 3.11  ✅ 推荐(性能提升)                            │
│   Python 3.12  ✅ 支持                                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

检查 Python 版本 #

bash
python --version
# 或
python3 --version

安装 FastAPI #

基础安装 #

bash
pip install fastapi

安装 ASGI 服务器 #

FastAPI 需要 ASGI 服务器来运行,推荐使用 Uvicorn:

bash
pip install uvicorn[standard]

一次性安装 #

bash
pip install fastapi uvicorn[standard]

虚拟环境 #

为什么使用虚拟环境? #

text
┌─────────────────────────────────────────────────────────────┐
│                    虚拟环境的作用                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   系统Python                                                │
│   └── 全局包(可能与其他项目冲突)                            │
│                                                             │
│   项目A虚拟环境                                              │
│   └── fastapi==0.100.0                                      │
│                                                             │
│   项目B虚拟环境                                              │
│   └── fastapi==0.95.0                                       │
│                                                             │
│   ✅ 隔离项目依赖                                            │
│   ✅ 避免版本冲突                                            │
│   ✅ 便于部署和复现                                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

使用 venv #

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

# 激活虚拟环境
# macOS/Linux
source venv/bin/activate

# Windows
venv\Scripts\activate

# 安装依赖
pip install fastapi uvicorn[standard]

使用 Poetry #

bash
# 安装 Poetry
pip install poetry

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

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

# 激活虚拟环境
poetry shell

使用 uv #

bash
# 安装 uv
pip install uv

# 创建项目
uv init my-api
cd my-api

# 添加依赖
uv add fastapi uvicorn[standard]

# 运行
uv run uvicorn main:app --reload

项目结构 #

最简结构 #

text
my-api/
├── main.py
└── requirements.txt

推荐结构 #

text
my-api/
├── app/
│   ├── __init__.py
│   ├── main.py           # FastAPI 应用入口
│   ├── config.py         # 配置管理
│   ├── dependencies.py   # 依赖注入
│   ├── routers/          # 路由模块
│   │   ├── __init__.py
│   │   ├── users.py
│   │   └── items.py
│   ├── models/           # Pydantic 模型
│   │   ├── __init__.py
│   │   ├── user.py
│   │   └── item.py
│   ├── schemas/          # 请求/响应模式
│   │   ├── __init__.py
│   │   ├── user.py
│   │   └── item.py
│   ├── services/         # 业务逻辑
│   │   ├── __init__.py
│   │   └── user_service.py
│   └── utils/            # 工具函数
│       ├── __init__.py
│       └── security.py
├── tests/                # 测试文件
│   ├── __init__.py
│   ├── conftest.py
│   └── test_main.py
├── .env                  # 环境变量
├── .gitignore
├── requirements.txt
└── README.md

requirements.txt #

创建 requirements.txt #

txt
fastapi>=0.100.0
uvicorn[standard]>=0.23.0
pydantic>=2.0.0
python-multipart>=0.0.6

安装依赖 #

bash
pip install -r requirements.txt

导出依赖 #

bash
pip freeze > requirements.txt

配置管理 #

使用环境变量 #

python
import os
from fastapi import FastAPI

app = FastAPI()

DEBUG = os.getenv('DEBUG', 'false').lower() == 'true'
DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///./test.db')

@app.get('/config')
def get_config():
    return {
        'debug': DEBUG,
        'database_url': DATABASE_URL
    }

使用 Pydantic Settings #

bash
pip install pydantic-settings
python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    app_name: str = 'My API'
    debug: bool = False
    database_url: str = 'sqlite:///./test.db'
    
    class Config:
        env_file = '.env'

settings = Settings()

.env 文件 #

env
APP_NAME=My FastAPI App
DEBUG=true
DATABASE_URL=postgresql://user:pass@localhost/db

运行应用 #

开发模式 #

bash
# 基本运行
uvicorn main:app

# 开发模式(自动重载)
uvicorn main:app --reload

# 指定端口
uvicorn main:app --reload --port 8080

# 指定主机
uvicorn main:app --reload --host 0.0.0.0

生产模式 #

bash
# 多进程
uvicorn main:app --workers 4

# 使用 Gunicorn + Uvicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker

在代码中运行 #

python
import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def read_root():
    return {'Hello': 'World'}

if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8000)

访问 API 文档 #

启动应用后,可以访问自动生成的 API 文档:

text
┌─────────────────────────────────────────────────────────────┐
│                    API 文档地址                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   Swagger UI:  http://localhost:8000/docs                   │
│   ReDoc:       http://localhost:8000/redoc                  │
│   OpenAPI:     http://localhost:8000/openapi.json           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

IDE 配置 #

VS Code #

安装推荐扩展:

  • Python
  • Pylance
  • Python Debugger

配置 .vscode/launch.json

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

PyCharm #

  1. 打开 Run/Debug Configurations
  2. 添加 Python 配置
  3. Module name: uvicorn
  4. Parameters: main:app --reload

常见问题 #

端口被占用 #

bash
# 查找占用端口的进程
lsof -i :8000

# 终止进程
kill -9 <PID>

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

模块找不到 #

bash
# 确保在正确的目录
cd /path/to/project

# 确保虚拟环境已激活
source venv/bin/activate

# 检查 Python 路径
python -c "import sys; print(sys.path)"

导入错误 #

python
# 错误示例
from app.main import app  # 可能导致导入问题

# 正确做法:在项目根目录运行
uvicorn app.main:app --reload

开发工具 #

HTTP 客户端 #

测试 API 的工具:

工具 类型 特点
Postman GUI 功能全面
Insomnia GUI 界面美观
HTTPie CLI 命令行友好
curl CLI 系统自带
httpx Python 代码测试

使用 HTTPie #

bash
# 安装
pip install httpie

# GET 请求
http GET http://localhost:8000/

# POST 请求
http POST http://localhost:8000/items name="Item 1" price:=10.5

使用 curl #

bash
# GET 请求
curl http://localhost:8000/

# POST 请求
curl -X POST http://localhost:8000/items \
  -H "Content-Type: application/json" \
  -d '{"name": "Item 1", "price": 10.5}'

下一步 #

环境配置完成后,让我们创建 第一个应用,开始 FastAPI 开发之旅!

最后更新:2026-03-29