How to Run FastAPI App: Simple Steps to Start Your Server
FastAPI app, create your app instance and then start the server using uvicorn with a command like uvicorn main:app --reload. This runs your app locally and reloads on code changes for easy development.Syntax
To run a FastAPI app, you use the uvicorn command with the format:
uvicorn module_name:app_instance --reload
Here, module_name is the Python file name without .py, and app_instance is the FastAPI app variable.
The --reload flag makes the server restart automatically when you change your code, which is helpful during development.
uvicorn main:app --reload
Example
This example shows a simple FastAPI app with one route. Running it with uvicorn starts a server on http://127.0.0.1:8000. Visiting this URL in a browser shows the greeting message.
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello, FastAPI!"} # Run this app with: uvicorn main:app --reload
Common Pitfalls
1. Wrong module or app name: Make sure the uvicorn command matches your Python file and app variable names exactly.
2. Forgetting to install Uvicorn: You must install Uvicorn with pip install uvicorn before running the server.
3. Running Python file directly: Running python main.py won't start the server unless you add code to do so; use uvicorn instead.
## Wrong way (won't start server):
# python main.py
## Right way:
# uvicorn main:app --reloadQuick Reference
| Command | Description |
|---|---|
| uvicorn main:app | Run FastAPI app without auto-reload |
| uvicorn main:app --reload | Run FastAPI app with auto-reload on code changes |
| pip install fastapi uvicorn | Install FastAPI and Uvicorn packages |
| Ctrl+C | Stop the running server |
Key Takeaways
uvicorn module_name:app --reload to run your FastAPI app with live reload.uvicorn command arguments exactly.pip install uvicorn.python; always use uvicorn to start the server.--reload flag helps during development by restarting the server on code changes.