39

i'm trying to debug an application (a web api) that use FastAPI (uvicorn) I'm also using poetry and set the projev virtual environment in vscode.

i read this tutorial to setup uvicorn and this one to setup vscode but i think i'm doing something wrong in set it up.

I tried to setup the launch.json both as python: module and python: current file

The problem seems that it doesn't recognize the project structure cause when i run the debug it stopped in an import statement with this error:

Exception has occurred: ImportError
attempted relative import with no known parent package

This is my current launch.json configuration:

"configurations": [
    {
        "name": "Python: local debug",
        "type": "python",
        "request": "launch",
        "program": "${workspaceFolder}/src/topic_service/service/__init__.py",
        "args" : ["--port", "8000"]
    },
]

I also tried to add a .env file setting PYTHONPATH:

PYTHONPATH=.:${PYTHONPATH}

Locally i run the application as follow:

poetry run uvicorn src.main:app --port 8080 --reload

Does anyone know how to correctly setup vscode to debug an uvicorn application?

Thank you

UPDATE: I also tried what this article says. the debugger seems to start but nothing happen (no breakpoint is triggered)

6 Answers 6

66

Try this configuration.

{
    "name": "Python: Module",
    "type": "python",
    "request": "launch",
    "module": "uvicorn",
    "args": ["src.main:app","--reload"]
}
1
41

Likewise you provide uvicorn module with necessary args during development of FastAPI application, you need to configure your launch.json located in .vscode directory with respective values.

I did a write up for custom project configurations to debug FastAPI in VS Code here

Suppose you issue the following command to run FastAPI on uvicorn server with args mentioned as below

uvicorn main:app --reload --port 8000

then your launch.json should have module with value of uvicorn and each of the args separated by space as items of the args array.

"module": "uvicorn",
"type": "debugpy",
"request": "launch",
"args": [
    "main:app",
    "--reload",
    "--port",
    "8000"
],
"env": {
    "usersecret": "some$Ecret",
}

You can have this launch.json file in .vscode and then modify the args array in the JSON configuration as per your project structure.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: FastAPI",
            "type": "debugpy",
            "request": "launch",
            "module": "uvicorn",
            "env": {
                "db_username": "postgres",
                "db_password": "secret",
                "host_server": "localhost",
                "database_name": "fastapi",
                "ssl_mode": "prefer",
                "db_server_port": "5432"
            },
            "args": [
                "main:app",
                "--reload",
                "--port",
                "8000"
            ]
        }
    ]
}
3
  • 1
    Additionally, you can also specify from where to get the .env file instead of declaring each environment variable in the "env" property, just by adding the property -> "envFile": "./some_folder/foo/.env" Commented Jul 16, 2021 at 15:03
  • I was able to get the debugger working thanks to your tutorial, however I'm unable to get breakpoints anywhere but main.py to get detected. I tried setting justMyCode = false in settings.json to no effect. Why could that be? Commented Nov 23, 2022 at 13:34
  • In my case "--host", "0.0.0.0", as args were needed Commented Aug 20 at 15:27
22

For me worked with this configurations:

On Debug section on VSCode, choose create launch.json option. Probally it will open launch.json on .vscode folder in your root folder explorer like this, inside of launch.json put this:

"version": "0.2.0",
  "configurations": [
    {
      "name": "Python: FastAPI",
      "type": "python",
      "request": "launch",
      "module": "uvicorn",
      "cwd": "${workspaceFolder}/<folder to your main.py>",
      "args": [
        "main:app",
        "--reload",
        "--port", //these arg are optional
        "3003"
      ]
    }
  ]
}

Now , just run your debugger and have a nice day!

Edit: The cwd ensure that your debbuger will find the right path to your main.py file. So, for whos use multiple debuggers or uses outside vsCode with launch.json it's a nice choice use it.

1
  • 1
    Personally I use debugger on VSCODE in .vscode directory with launch.json. But there`s an way to use it inside vscode, maybe you going to have problems for yours debugger find where your main.py is it. So If you simply need run your fastAPI aplication the simplest way is use cwd with your debugger.
    – Suzik
    Commented Nov 12, 2021 at 21:00
13

The quick and easy way: launch debugger F5 and then select FastAPI Debug Configuration: (p.s. this works on the VSCode Insiders; haven't tried it on a regular version)

enter image description here

4

The way i debug is quite basic, hope it helps i have .py file with this config:

import uvicorn
from app.main import api
    
if __name__ == "__main__":
    dev = 1
    if dev==0:
        #use this one
        uvicorn.run(api, host="127.0.0.1", port=5000, log_level="info")
    if dev == 1:
        #or this one
        uvicorn.run('app.main:api', host="127.0.0.1", port=5000, log_level="info", reload=True, debug=True)
    if dev == 2:
        uvicorn.run('app.main:api', host="127.0.0.1", port=5000, log_level="info", workers=2)

and run the file with the vscode debugger, the important thing is to run the app with the debug flag because otherwise the debugger skips the breakpoints (at least in my case)

1
  • with uvicorn version 0.20.0, there is no debug parameter... Commented Dec 3, 2022 at 0:44
0

Answering this 4 years late since none of the other answers were helpful for me and I figured it out. The FastApi docs don't explain how to run the debugger with a multiple-file project. Relative paths only work within a package, but if you execute a script from within the package, the package is not loaded. The solution I came up with was to have a server file outside the package and put everything relevant to the application within a "main_package" package, so that relative imports work within that package. Then you just have to configure fastapi or your debugger or whatever to run server.py

directory structure:

- server.py
- .vscode
-- launch.json
- main_package
-- __init__.py
-- app.py
-- routers
--- tasks.py

server.py:

import uvicorn
from main_package.app import app 

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

app.py:

from fastapi import FastAPI
from .routers import tasks

app = FastAPI()

app.include_router(tasks.router)

tasks.py:

from fastapi import APIRouter
router = APIRouter(
    prefix="/items",
    responses={status.HTTP_404_NOT_FOUND: {"description": "Not found"}}
)
@router.post("/", status_code=201)
def create(task):
    return { "message": "created"}

launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python Debugger: FastAPI",
      "type": "debugpy",
      "request": "launch",
      "module": "uvicorn",
      "args": ["server:app", "--reload"],
      "jinja": true
    }
  ]
}

To run the server yourself: fastapi dev server.py To run the debugger:

  1. Run -> Add Configuration -> (add in the configuration I included above)
  2. Run -> Start Debugging Make sure in the debugging tab you're running "Python Debugger: FastAPI"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.