skip to Main Content

I am using Visual Studio 2022 on Win11, and trying to get to grips with Python. In particular, I am trying out FastAPI.

I have installed FastAPI and Uvicorn. I have a virtual environment set up for Python 3.9.

How do I get VS to run the Uvicorn server when testing? I am trying to follow the start up guide (https://fastapi.tiangolo.com/tutorial/first-steps/). I have created a main.py file, with the required code. When I try to run it from an interactive console, I type uvicorn -m main:app --reload.

The console comes back with

File "stdin", line 1
    uvicorn -m main:app --reload
               ^
SyntaxError: invalid syntax

I have tried moving the example code to another file and trying to get uvicorn to run that file, but no joy. I think either uvicorn is not running, or the environment cannot find either uvicorn or the target main.py file.

I have tried running a DOS prompt, executing the python.exe in the venv folder, and trying to point to uvicorn directly…

"C:Program Files (x86)Microsoft Visual StudioSharedPython39_64python" -m "C:UsersUserDocumentsVisual Studio 2022ReposPythonApplicationFastAPITest1envScriptsuvicorn" main:app --reload

…and I get "No module named …uvicorn".

2

Answers


  1. Chosen as BEST ANSWER

    I got this working with MKrieger1's engagement.

    Uvicorn is a self contained app, uvicorn.exe, a server. I was trying to start it in a Python interpreter session, which was failing.

    I got it working by running uvicorn in an external DOS prompt. I referenced the uvicorn.exe that had been installed with the FastAPI package. The -m switch did not seem to work.

    When in DOS, I changed directory to the project folder holding my main.py file. I then issued the command...

    .envscriptsuvicorn main:app --reload
    

    ...and this started uvicorn.exe, found main.py, app object, and ran it. I was then able to browse to 127.0.0.1:8000 and get my "Hello, world" achievement.

    INFO:     Will watch for changes in these directories: ['C:\Users\User\Documents\Visual Studio 2022\Repos\PythonApplicationFastAPITest1']
    INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
    INFO:     Started reloader process [23000] using WatchFiles
    INFO:     Started server process [20528]
    INFO:     Waiting for application startup.
    INFO:     Application startup complete.
    INFO:     127.0.0.1:49891 - "GET / HTTP/1.1" 200 OK
    

  2. Python cannot find the uvicorn module when trying to run your FastAPI application. Ensure that the uvicorn package is installed in your virtual environment. You can install it using command:
    pip install uvicorn

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search