If I have written an application in FastAPI, I can just run the main.py file. But then I can also run it using uvicorn via command line?

Option 1: Run the script directly If the main.py has this at the bottom:

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)

Then yes — you can just run: python main.py

The FastAPI app starts up. That’s because we're explicitly calling uvicorn.run() inside our script.

Option 2: Use the command line (the "clean" pro way™) If we don’t want to hardcode that uvicorn.run() block, we can launch it from the CLI:

uvicorn main:app --reload

This tells uvicorn to look in main.py, grab the app object, and run it.

Most pros lean toward the CLI approach (option 2), especially in production setups or Dockerized environments. - Why?

🧠 1. Separation of concerns When we run uvicorn main:app --reload from the command line, we keep our application logic (main.py) separate from our server configuration. That’s clean code 101. We don’t tie our app to a specific way of running it (uvicorn, waitress or other WSGI servers) — makes it easier to test, import, and reuse elsewhere.

🚀 2. Production-grade control Using the CLI lets you easily swap in:

--host, --port

--workers (for multiprocessing with uvicorn[gunicorn])

--reload, --env-file, and more!

That flexibility is crucial in production where performance, scalability, and fine-tuning are key.

🐳 3. Docker & orchestration compatibility In Docker, Kubernetes, etc., we often specify entrypoints or commands like:

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

It’s leaner and makes the container's behavior more transparent and configurable — especially when configs come from environment variables.

🧪 4. Testability When we don’t embed the server startup (uvicorn.run(...)) in our code, our app is more easily testable. We can import app in a test suite without accidentally firing up a whole server. We’ve got clean module imports, and pytest won’t have a panic attack.

💼 5. Standard practice for deployment tools Tools like gunicorn, supervisor, or systemd want to launch our app with a command, not execute Python code directly. CLI commands integrate naturally with these systems.