2

I installed FASTAPI and was running below mentioned code

from fastapi import FastAPI
    
app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

and am getting below mentioned error in console on executing the file

(venv) D:\FASTAPI>uvicorn main:app --reload
INFO:     Will watch for changes in these directories: ['D:\\FASTAPI']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [7900] using watchgod
ERROR:    Error loading ASGI app. Attribute "app" not found in module "main".

I really appreciate any recommendations or suggestions

ljmc
  • 4,830
  • 2
  • 7
  • 26
Vikas Jha
  • 21
  • 1
  • 1
  • 2

5 Answers5

2

First look the project tree. The main.py file is under app directory.

In my project like this:

fastapi 
   -> app
      -> main.py

My project folder tree

Copy codes to main.py:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Run the server:

uvicorn app.main:app --reload

But if you try to run this server like:

uvicorn main:app --reload

This will cause the error:

Error loading ASGI app. Attribute "app" not found in module "main"

Hope you understood. Run and enjoy coding....

Subarata Talukder
  • 5,407
  • 2
  • 34
  • 50
2

It work like this: uvicorn root-file-name:root-function-in-the-file --reload

Just put the name of the root function:

def root():
 print('works')

uvicorn main:root --reload

1

Suggestion: Make sure you have set VS Studio Code to "autosave". If updated code not saved, interpreter will not allow app startup.

0

I was stuck in the same issue.

here is the solution

Go to main.py (file created in the file folder)

--> Paste the piece of code

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
  return {"Hello": "World"}

---> right click main.py

-------> Select 'Run python file in terminal'

--> Now run the script : uvicorn main:app

--> It'll work

-1

your folder should be in C/: name src and then create main.pyenter image description here