0
0
FastapiHow-ToBeginner · 3 min read

How to Run FastAPI App: Simple Steps to Start Your Server

To run a 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.

bash
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.

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, FastAPI!"}

# Run this app with: uvicorn main:app --reload
Output
INFO: Started server process [PID] 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

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.

bash
## Wrong way (won't start server):
# python main.py

## Right way:
# uvicorn main:app --reload
📊

Quick Reference

CommandDescription
uvicorn main:appRun FastAPI app without auto-reload
uvicorn main:app --reloadRun FastAPI app with auto-reload on code changes
pip install fastapi uvicornInstall FastAPI and Uvicorn packages
Ctrl+CStop the running server

Key Takeaways

Use the command uvicorn module_name:app --reload to run your FastAPI app with live reload.
Ensure your Python file and app variable names match the uvicorn command arguments exactly.
Install Uvicorn before running your app using pip install uvicorn.
Do not run the FastAPI file directly with python; always use uvicorn to start the server.
The --reload flag helps during development by restarting the server on code changes.