Skip to main content

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.

Learning Focus

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.

check-python-version.sh
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 VersionFastAPI SupportRecommended
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-venv.sh
# 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
note

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:

install-fastapi.sh
pip install "fastapi[standard]>=0.111"

# Verify
python -c "import fastapi; print(fastapi.__version__)"

The [standard] extra includes:

PackagePurpose
uvicorn[standard]ASGI server with performance extras
httpxHTTP client used by TestClient
python-multipartFile upload support
email-validatorEmail field validation in Pydantic
pydantic-settingsSettings management via .env files

Production vs Development Packages

For development, also install these:

install-dev-deps.sh
pip install \
pytest \
pytest-asyncio \
httpx \
"sqlalchemy[asyncio]>=2.0" \
asyncpg \
alembic \
"python-jose[cryptography]" \
passlib[bcrypt]

Save your dependencies:

save-requirements.sh
pip freeze > requirements.txt
# Or use pyproject.toml for modern projects (preferred)
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

verify-setup.sh
# 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:

.env
# 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
.gitignore
.venv/
.env
__pycache__/
*.pyc
.pytest_cache/

Common Pitfalls

PitfallCause / SymptomFix
ModuleNotFoundError: No module named 'fastapi'Virtual environment not activatedRun source .venv/bin/activate
Address already in use on port 8000Another process is using 8000Kill it: `lsof -ti:8000
ImportError: cannot import name 'Annotated'Python < 3.9 with wrong syntaxUpgrade to Python 3.11 or use from typing import Annotated
Uvicorn exits immediatelySyntax error in main.pyCheck terminal output for the traceback
pydantic_settings not foundInstalled FastAPI without [standard] extrapip install pydantic-settings

Hands-On Practice

setup-practice.sh
# 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

What's Next