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 ":".
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:apprefers to:
main: the filemain.py(the Python"module").app: the object created inside ofmain.pywith the lineapp = 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.
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:
~$ uvicorn name_of_file:name_of_FastAPI_instance_variable_inside_file --reload
~$ python name_of_file.py
~$ uvicorn main:app --reload
or
~$ python main.py
OBS.: And typically devs name the file main.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With