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

Create a Virtual Environment

bash
mkdir fastapi-hello
cd fastapi-hello
python -m venv .venv

Activate:

OSCommand
macOS / Linuxsource .venv/bin/activate
Windows (PowerShell).venv\Scripts\Activate.ps1

Upgrade pip:

bash
python -m pip install -U pip

See pip and uv on this site for package manager details.

Install FastAPI and Uvicorn

Recommended bundle:

bash
pip install "fastapi[standard]"

Or explicit packages:

bash
pip install "fastapi>=0.110" "uvicorn[standard]"

Development tools:

bash
pip install python-dotenv httpx pytest

Pin dependencies:

bash
pip freeze > requirements.txt

Example requirements.txt:

text
fastapi==0.115.0
uvicorn[standard]==0.30.6
python-dotenv==1.0.1
httpx==0.27.2
pytest==8.3.3

Verify:

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

Start simple, grow into this structure:

Chapters 3–8 start with app/main.py; chapter 7 expands into api/ packages.

.gitignore

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:

bash
pip install mypy
mypy app/ --ignore-missing-imports

Type hints power FastAPI validation and editor autocomplete—use them from day one.

Verify Imports

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