3

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 ":".

Chris
  • 18,724
  • 6
  • 46
  • 80

2 Answers2

4

As the error indicates, the "string main must be in 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.
Chris
  • 18,724
  • 6
  • 46
  • 80
1

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)

This message might occur because of a call on the method run, where it does not accept positional nor keyword arguments as variables. But rather as plain text. Like done in the example above.

victorkolis
  • 780
  • 13
  • 13