Files
2026-06-20 18:05:05 -05:00

108 lines
2.8 KiB
Markdown

# FastAPI Debug Launch with debugpy
This reference provides practical [`.vscode/launch.json`](https://code.visualstudio.com/docs/debugtest/debugging-configuration) patterns for [FastAPI](https://fastapi.tiangolo.com/) applications started with [uvicorn](https://www.uvicorn.org/).
## 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
}
```
Factory mode is powered by uvicorn's [`--factory`](https://www.uvicorn.org/settings/#application) option.
## Attach to an Existing FastAPI Process
If the app is launched externally, start with [`debugpy`](https://code.visualstudio.com/docs/python/debugging#_command-line-debugging):
```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.
## Source Documentation
- [FastAPI docs](https://fastapi.tiangolo.com/)
- [Uvicorn settings and CLI options](https://www.uvicorn.org/settings/)
- [Python debugging in VS Code](https://code.visualstudio.com/docs/python/debugging)
- [Debug configuration and launch.json](https://code.visualstudio.com/docs/debugtest/debugging-configuration)