Installation and Setup
Before writing a single route, you need a clean Python environment with FastAPI, a compatible ASGI server, and the right tooling. Skipping this step causes dependency conflicts and confusing errors later.
By the end of this lesson you can: create an isolated virtual environment, install FastAPI with all standard extras, verify the installation, and understand what each installed package does.
Python Version Requirements
FastAPI requires Python 3.8+ but this track targets Python 3.11+ for best async performance and improved type hint syntax.
python3 --version
# Expected: Python 3.11.x or 3.12.x
# If your system Python is older, install pyenv
curl https://pyenv.run | bash
pyenv install 3.11.9
pyenv local 3.11.9
| Python Version | FastAPI Support | Recommended |
|---|---|---|
| 3.8, 3.9 | ✅ Supported | ❌ Avoid for new projects |
| 3.10 | ✅ Supported | ⚠️ Works, but prefer newer |
| 3.11 | ✅ Supported | ✅ Recommended |
| 3.12 | ✅ Supported | ✅ Also fine |
Creating a Virtual Environment
Always use a virtual environment. This prevents package version conflicts across projects.
# Create project directory
mkdir my-api && cd my-api
# Create virtual environment
python3.11 -m venv .venv
# Activate (Linux/macOS)
source .venv/bin/activate
# Confirm activation — prompt should show (.venv)
which python # → /path/to/my-api/.venv/bin/python
Add .venv/ to your .gitignore. Never commit the virtual environment directory.
Installing FastAPI
The fastapi[standard] extra installs FastAPI plus the recommended dependencies for development:
pip install "fastapi[standard]>=0.111"
# Verify
python -c "import fastapi; print(fastapi.__version__)"
The [standard] extra includes:
| Package | Purpose |
|---|---|
uvicorn[standard] | ASGI server with performance extras |
httpx | HTTP client used by TestClient |
python-multipart | File upload support |
email-validator | Email field validation in Pydantic |
pydantic-settings | Settings management via .env files |
Production vs Development Packages
For development, also install these:
pip install \
pytest \
pytest-asyncio \
httpx \
"sqlalchemy[asyncio]>=2.0" \
asyncpg \
alembic \
"python-jose[cryptography]" \
passlib[bcrypt]
Save your dependencies:
pip freeze > requirements.txt
# Or use pyproject.toml for modern projects (preferred)
Recommended Project Layout
my-api/
├── .venv/ # Virtual environment (gitignored)
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI app instance
│ ├── routers/ # APIRouter modules
│ ├── models/ # Pydantic models
│ ├── db/ # SQLAlchemy models + session
│ ├── services/ # Business logic
│ └── core/
│ ├── config.py # Settings (pydantic-settings)
│ └── security.py # Auth helpers
├── tests/
│ ├── conftest.py
│ └── test_main.py
├── alembic/ # Database migrations
├── .env # Development secrets (gitignored)
├── .env.example # Template (committed)
├── requirements.txt
└── pyproject.toml
Verifying Your Setup
# Create minimal app
cat > app/main.py << 'EOF'
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
async def health():
return {"status": "ok"}
EOF
# Run Uvicorn
uvicorn app.main:app --reload
# Verify in another terminal
curl http://localhost:8000/health
# → {"status":"ok"}
# Check OpenAPI schema is valid
curl http://localhost:8000/openapi.json | python -m json.tool
Environment Variables Setup
FastAPI apps should never have secrets in code. Set up .env from the start:
# Development only — never commit real secrets
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/mydb
SECRET_KEY=dev-only-change-in-production
ALLOWED_ORIGINS=http://localhost:3000
DEBUG=true
.venv/
.env
__pycache__/
*.pyc
.pytest_cache/
Common Pitfalls
| Pitfall | Cause / Symptom | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'fastapi' | Virtual environment not activated | Run source .venv/bin/activate |
Address already in use on port 8000 | Another process is using 8000 | Kill it: `lsof -ti:8000 |
ImportError: cannot import name 'Annotated' | Python < 3.9 with wrong syntax | Upgrade to Python 3.11 or use from typing import Annotated |
| Uvicorn exits immediately | Syntax error in main.py | Check terminal output for the traceback |
pydantic_settings not found | Installed FastAPI without [standard] extra | pip install pydantic-settings |
Hands-On Practice
# Step 1: create a clean project
mkdir fastapi-practice && cd fastapi-practice
python3.11 -m venv .venv && source .venv/bin/activate
# Step 2: install
pip install "fastapi[standard]>=0.111"
# Step 3: create a minimal working API
mkdir -p app
cat > app/__init__.py << 'EOF'
EOF
cat > app/main.py << 'EOF'
from fastapi import FastAPI
app = FastAPI(
title="FastAPI Practice",
version="0.1.0",
description="Learning FastAPI step by step",
)
@app.get("/")
async def root() -> dict:
return {"message": "Setup complete!"}
EOF
# Step 4: run and test
uvicorn app.main:app --reload &
sleep 2
curl -s http://localhost:8000/ | python -m json.tool
# Expected: {"message": "Setup complete!"}
curl -s http://localhost:8000/openapi.json | python -c "import json,sys; d=json.load(sys.stdin); print('Title:', d['info']['title'])"
# Expected: Title: FastAPI Practice
# Step 5: clean up
kill %1