FastAPI Environment and Installation
Introduction
FastAPI runs in a Python virtual environment like any modern Python project. This chapter creates a venv, installs FastAPI with Uvicorn, sets up a scalable folder layout, and adds .gitignore rules so secrets never enter Git.
Prerequisites
- What Is FastAPI
- Python 3.10+ installed
- Basic terminal use
Create a Virtual Environment
mkdir fastapi-hello
cd fastapi-hello
python -m venv .venvActivate:
| OS | Command |
|---|---|
| macOS / Linux | source .venv/bin/activate |
| Windows (PowerShell) | .venv\Scripts\Activate.ps1 |
Upgrade pip:
python -m pip install -U pipSee pip and uv on this site for package manager details.
Install FastAPI and Uvicorn
Recommended bundle:
pip install "fastapi[standard]"Or explicit packages:
pip install "fastapi>=0.110" "uvicorn[standard]"Development tools:
pip install python-dotenv httpx pytestPin dependencies:
pip freeze > requirements.txtExample requirements.txt:
fastapi==0.115.0
uvicorn[standard]==0.30.6
python-dotenv==1.0.1
httpx==0.27.2
pytest==8.3.3Verify:
python -c "import fastapi; print(fastapi.__version__)"Recommended Project Layout
Start simple, grow into this structure:
Chapters 3–8 start with app/main.py; chapter 7 expands into api/ packages.
.gitignore
.venv/
__pycache__/
*.py[cod]
.env
.pytest_cache/
.mypy_cache/
.ruff_cache/
dist/
*.egg-info/See Git .gitignore patterns.
Warning
Never Commit .env
Store SECRET_KEY, database URLs, and JWT secrets in environment variables—not in Git history.
Editor and Type Checking
- VS Code: select interpreter
.venv/bin/python; install Pylance - PyCharm: configure project interpreter to venv
Optional static analysis:
pip install mypy
mypy app/ --ignore-missing-importsType hints power FastAPI validation and editor autocomplete—use them from day one.
Verify Imports
python -c "from fastapi import FastAPI; import uvicorn; print('OK')"FAQ
python vs python3?
Use whichever starts Python 3.10+ on your system. Inside venv, python is correct.
fastapi[standard] includes what?
Uvicorn, httptools, uvloop (where supported), and common extras—good default for learning.
Global pip install?
Avoid—one venv per project.
pyproject.toml instead of requirements.txt?
Supported—this track uses requirements.txt for simplicity.
WSL2 on Windows?
Same Linux commands; browser hits http://127.0.0.1:8000.
Version conflicts with Pydantic?
FastAPI 0.100+ requires Pydantic v2—do not pin pydantic v1.