VS Code 开发 FastAPI
VS Code 开发 FastAPI:终极配置指南(2025 最新)
一、目标:打造 极致 FastAPI 开发体验
| 功能 | 效果 |
|---|---|
| 智能补全 | 自动提示 app.get()、Depends()、Pydantic 字段 |
| 类型检查 | 实时发现 int vs str 错误 |
| 热重载 | 保存即刷新 |
| 调试断点 | 一键调试 API |
| 自动文档 | 点击跳转 /docs |
| 测试集成 | 一键运行 Pytest |
| 代码格式化 | Ruff + Black 自动美化 |
二、VS Code 安装与基础配置
1. 下载 VS Code
2. 安装必备扩展
| 扩展 | 安装命令(Ctrl+Shift+X 搜索) |
|---|---|
| Python | ms-python.python |
| Pylance | ms-python.vscode-pylance(类型检查神器) |
| Ruff | charliermarsh.ruff(超快 lint + 格式化) |
| Black Formatter | ms-python.black-formatter |
| isort | ms-python.isort |
| FastAPI Snippets | humao.rest-client(可选) |
| REST Client | humao.rest-client(替代 Postman) |
三、项目结构(推荐)
fastapi-project/
├── .vscode/
│ ├── settings.json
│ └── launch.json
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── routers/
│ ├── models/
│ ├── schemas/
│ └── dependencies.py
├── tests/
├── .env
├── requirements.txt
└── pyproject.toml
四、VS Code 配置:.vscode/settings.json
{
// Python 环境
"python.defaultInterpreterPath": "./venv/bin/python",
// 格式化
"editor.formatOnSave": true,
"python.formatting.provider": "none",
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.fixAll": true
}
},
// Ruff 配置
"ruff.organizeImports": true,
"ruff.format": true,
// Pylance 类型检查
"python.analysis.typeCheckingMode": "basic",
"python.analysis.autoImportCompletions": true,
// 文件关联
"files.associations": {
"*.html": "html"
},
// 终端
"terminal.integrated.defaultProfile.windows": "Command Prompt",
"terminal.integrated.profiles.windows": {
"FastAPI": {
"path": "cmd",
"args": ["/K", "venv\\Scripts\\activate"]
}
}
}
五、调试配置:.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "FastAPI: Debug",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"app.main:app",
"--reload",
"--port", "8000"
],
"jinja": true,
"justMyCode": false,
"env": {
"ENV": "development"
}
},
{
"name": "Pytest: Current File",
"type": "python",
"request": "launch",
"module": "pytest",
"args": [
"-v",
"${file}"
],
"console": "integratedTerminal"
}
]
}
F5 一键启动 + 断点调试
六、开发工作流(一步步操作)
1. 创建项目
mkdir fastapi-project && cd fastapi-project
python -m venv venv
venv\Scripts\activate # Windows
# source venv/bin/activate # macOS/Linux
pip install fastapi uvicorn[standard] python-dotenv
2. 初始化 app/main.py
from fastapi import FastAPI
app = FastAPI(title="VS Code FastAPI 项目")
@app.get("/")
def read_root():
return {"message": "Hello from VS Code!"}
3. 启动方式(三选一)
| 方式 | 操作 |
|---|---|
| 终端 | uvicorn app.main:app --reload |
| 调试(F5) | 选择 “FastAPI: Debug” |
| 任务(Ctrl+Shift+B) | 配置 tasks.json |
七、任务配置:.vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "Run FastAPI",
"type": "shell",
"command": "uvicorn app.main:app --reload",
"group": "none",
"presentation": {
"echo": true,
"reveal": "always",
"panel": "dedicated"
},
"isBackground": true,
"problemMatcher": []
},
{
"label": "Run Tests",
"type": "shell",
"command": "pytest -v",
"group": "test"
}
]
}
八、智能补全与类型提示
1. Pydantic 模型补全
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
@app.post("/users/")
def create_user(user: User):
user. # 自动提示 name, age
return user
2. Depends 依赖提示
def get_db():
return "db"
@app.get("/items/")
def read_items(db: str = Depends(get_db)):
db. # 提示字符串方法
九、REST Client 测试(替代 Postman)
创建 requests.http
### 创建用户
POST http://127.0.0.1:8000/users/
Content-Type: application/json
{
"name": "Alice",
"age": 25
}
### 获取用户
GET http://127.0.0.1:8000/users/1
### 健康检查
GET http://127.0.0.1:8000/health
点击 “Send Request” 直接测试
十、环境变量管理
.env
DATABASE_URL=sqlite:///./test.db
SECRET_KEY=your-secret-key
ENV=development
app/main.py
from dotenv import load_dotenv
load_dotenv()
import os
DATABASE_URL = os.getenv("DATABASE_URL")
十一、代码片段(Snippets)
按 Ctrl+Space 在 main.py 中输入:
# 输入 fastapi → 自动生成
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
十二、Git 集成与提交
git init
git add .
git commit -m "init: fastapi vscode project"
.gitignore:
venv/
__pycache__/
*.pyc
.env
*.sqlite
十三、完整 pyproject.toml(推荐)
[project]
name = "fastapi-vscode"
version = "0.1.0"
dependencies = [
"fastapi",
"uvicorn[standard]",
"python-dotenv",
"pydantic>=2.0"
]
[tool.ruff]
select = [“E”, “F”, “W”, “I”] fixable = [“ALL”]
[tool.black]
line-length = 88
十四、快捷键速查
| 快捷键 | 功能 |
|---|---|
F5 | 启动调试 |
Ctrl+Shift+B | 运行任务 |
| `Ctrl+“ | 打开终端 |
Ctrl+Shift+P | 命令面板 |
Ctrl+Space | 触发补全 |
Shift+Alt+F | 格式化文档 |
F12 | 跳转定义 |
十五、常见问题解决
| 问题 | 解决方案 |
|---|---|
| 无补全 | 检查 Pylance 是否启用 |
| 热重载不生效 | 确保 --reload 参数 |
| 端口被占用 | 修改 --port 8001 |
| Ruff 报错 | pip install ruff |
| 调试不启动 | 检查 launch.json 路径 |
十六、推荐扩展组合
[
"ms-python.python",
"ms-python.vscode-pylance",
"charliermarsh.ruff",
"ms-python.black-formatter",
"ms-python.isort",
"humao.rest-client",
"ms-azuretools.vscode-docker",
"GitHub.copilot"
]
十七、最终效果演示
graph TD
A[保存 main.py] --> B[热重载]
B --> C[浏览器自动刷新]
C --> D[/docs 交互测试]
F5[按 F5] --> E[断点调试]
Ctrl+Shift+P[Ctrl+Shift+P] --> F[运行 Pytest]
总结:VS Code + FastAPI 黄金组合
| 工具 | 作用 |
|---|---|
| Pylance | 类型检查 + 补全 |
| Ruff | 超快 lint + 格式化 |
| Debug | 断点 + 变量查看 |
| REST Client | 替代 Postman |
| Tasks | 一键启动/测试 |
下一步行动
| 关键词 | 获取内容 |
|---|---|
模板 | 完整 VS Code FastAPI 项目模板(含所有配置) |
调试 | 数据库 + JWT 调试实战 |
docker | VS Code + Docker 集成 |
test | Pytest + 覆盖率配置 |
回复
vscode模板立刻获取一个可直接运行的完整项目!
现在就打开 VS Code,F5 启动你的 FastAPI 之旅!