How to Use Uvicorn with FastAPI: Simple Guide
To run a FastAPI app with
uvicorn, use the command uvicorn your_module:app --reload. Here, your_module is the Python file name without .py, and app is the FastAPI instance inside that file.Syntax
The basic command to start a FastAPI app with Uvicorn is:
uvicorn: The server command to run ASGI apps.your_module:app: The Python file name (without.py) and the FastAPI app instance name separated by a colon.--reload: Optional flag to auto-restart the server on code changes, useful during development.
bash
uvicorn your_module:app --reload
Example
This example shows a simple FastAPI app and how to run it with Uvicorn. The app responds with a greeting message at the root URL.
python
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello, FastAPI with Uvicorn!"} # Save this as main.py # Run with: # uvicorn main:app --reload
Output
INFO: Started server process [12345]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Common Pitfalls
Common mistakes when using Uvicorn with FastAPI include:
- Using the wrong module or app name in the command, causing import errors.
- Forgetting to add
--reloadduring development, so code changes don't reflect automatically. - Running the app with
python main.pyinstead of usinguvicorn, which won't start the ASGI server properly.
bash
Wrong command example: uvicorn main.py --reload Correct command: uvicorn main:app --reload
Quick Reference
Summary tips for using Uvicorn with FastAPI:
- Always specify
module_name:app_instancein the command. - Use
--reloadfor development to see changes live. - Use
--hostand--portoptions to customize server address and port. - Run
uvicorn --helpto see all options.
Key Takeaways
Run FastAPI apps with Uvicorn using the syntax: uvicorn module_name:app --reload.
The module name is the Python file without .py, and app is the FastAPI instance name.
Use --reload during development to auto-restart on code changes.
Avoid running FastAPI apps directly with python; always use Uvicorn to serve them.
Customize host and port with Uvicorn options as needed.