99 lines
2.2 KiB
Markdown
99 lines
2.2 KiB
Markdown
# FastAPI Debug Launch with debugpy
|
|
|
|
This reference provides practical `.vscode/launch.json` patterns for FastAPI applications started with uvicorn.
|
|
|
|
## Launch FastAPI via Module
|
|
|
|
Preferred profile:
|
|
|
|
```json
|
|
{
|
|
"name": "FastAPI: Uvicorn (debug)",
|
|
"type": "debugpy",
|
|
"request": "launch",
|
|
"module": "uvicorn",
|
|
"args": [
|
|
"your_package.main:app",
|
|
"--host",
|
|
"127.0.0.1",
|
|
"--port",
|
|
"8000",
|
|
"--reload",
|
|
"--log-level",
|
|
"debug"
|
|
],
|
|
"cwd": "${workspaceFolder}",
|
|
"envFile": "${workspaceFolder}/.env",
|
|
"console": "integratedTerminal",
|
|
"justMyCode": true,
|
|
"jinja": true
|
|
}
|
|
```
|
|
|
|
Why module mode: it matches `python -m uvicorn ...` behavior and avoids path ambiguity.
|
|
|
|
## Launch with Factory Pattern
|
|
|
|
If app is created via factory function:
|
|
|
|
```json
|
|
{
|
|
"name": "FastAPI: Uvicorn factory (debug)",
|
|
"type": "debugpy",
|
|
"request": "launch",
|
|
"module": "uvicorn",
|
|
"args": [
|
|
"your_package.main:create_app",
|
|
"--factory",
|
|
"--host",
|
|
"127.0.0.1",
|
|
"--port",
|
|
"8000",
|
|
"--reload"
|
|
],
|
|
"cwd": "${workspaceFolder}",
|
|
"console": "integratedTerminal",
|
|
"justMyCode": true
|
|
}
|
|
```
|
|
|
|
## Attach to an Existing FastAPI Process
|
|
|
|
If the app is launched externally, start with debugpy:
|
|
|
|
```bash
|
|
python -m debugpy --listen 5678 -m uvicorn your_package.main:app --host 127.0.0.1 --port 8000 --reload
|
|
```
|
|
|
|
Attach profile:
|
|
|
|
```json
|
|
{
|
|
"name": "FastAPI: Attach (5678)",
|
|
"type": "debugpy",
|
|
"request": "attach",
|
|
"connect": {
|
|
"host": "127.0.0.1",
|
|
"port": 5678
|
|
},
|
|
"justMyCode": true
|
|
}
|
|
```
|
|
|
|
## Common FastAPI Debug Pitfalls
|
|
|
|
1. Wrong import target in `your_package.main:app` or factory symbol.
|
|
2. `cwd` does not match source layout.
|
|
3. Auto-reload creating confusion about active process when breakpoints are set in startup code.
|
|
4. Port collisions from old uvicorn processes.
|
|
5. Environment variables not loaded because `envFile` path is wrong.
|
|
|
|
## Practical Quality Gate
|
|
|
|
A profile is considered valid when:
|
|
|
|
1. Server starts from VS Code Run and Debug.
|
|
2. A breakpoint inside an endpoint is hit on request.
|
|
3. A breakpoint in startup/lifespan logic is hit at app boot.
|
|
4. Terminal output appears in integrated terminal with expected log level.
|