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

https://code.visualstudio.com

2. 安装必备扩展

扩展安装命令(Ctrl+Shift+X 搜索)
Pythonms-python.python
Pylancems-python.vscode-pylance(类型检查神器)
Ruffcharliermarsh.ruff(超快 lint + 格式化)
Black Formatterms-python.black-formatter
isortms-python.isort
FastAPI Snippetshumao.rest-client(可选)
REST Clienthumao.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+Spacemain.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 调试实战
dockerVS Code + Docker 集成
testPytest + 覆盖率配置

回复 vscode模板 立刻获取一个可直接运行的完整项目!


现在就打开 VS Code,F5 启动你的 FastAPI 之旅!

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注