Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR: Error loading ASGI app. Import string "main" must be in format "<module>:<attribute>"

Trying to test my first FastAPI application using uvicorn.

The following code was written on Jupyter Notebook and saved as 'main.py' in the directory: /home/user

from fastapi import FastAPI

app = FastAPI()

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

From the same directory I am running:

$uvicorn main --reload

It throws the following error:

ERROR: Error loading ASGI app. Import string "main" must be in format ":".

like image 979
forever_learner Avatar asked Sep 04 '26 17:09

forever_learner


2 Answers

As the error indicates, the "string main must be in the following format: "<module>:<attribute>"". Hence, you should use:

uvicorn main:app --reload

I would highly suggest you take a look at the FastAPI tutorial.

The command uvicorn main:app refers to:

  • main: the file main.py (the Python "module").
  • app: the object created inside of main.py with the line app = FastAPI().
  • --reload: make the server restart after code changes. Only use for development.

For further details, please take a look at this answer as well.

like image 137
Chris Avatar answered Sep 06 '26 07:09

Chris


The exact same error message, however a different scenario

import uvicorn
from fastapi import FastAPI
  
    
app = FastAPI()
    
    
@app.get('/')
def index():
    return {'Message': 'This is only a message!'}
    
    
if __name__ == '__main__':
    uvicorn.run('main:app', port=8000, reload=True)

You can now run this from your terminal (which must have fastapi package installed, either via pip or any other package indexer/distributer).

Error message breakdown. This error might be due to the script naming. The name of the file you are firing up MUST the same as the one run in the command line. Also the same in the uvicorn.run('FILE:VAR').

i.e

meaning:

uvicorn.run('main:app', port=8000, reload=True)

main <---- is the name of the file, app is the name of the variable inside your fastapi file (that is the instance of the FastAPI() class).

So when run in the CLI, everything has to jive in.

i.e

meaning:

  1. Running via uvicorn (on your terminal)

~$ uvicorn name_of_file:name_of_FastAPI_instance_variable_inside_file --reload

  1. Running via Python (on your terminal)

~$ python name_of_file.py


Most common usage

~$ uvicorn main:app --reload

or

~$ python main.py



OBS.: And typically devs name the file main.py

like image 42
victorkolis Avatar answered Sep 06 '26 08:09

victorkolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!