Skip to content

FastAPI Development Environment

Overview

Setting up an efficient FastAPI development environment is the first step in learning and development. This chapter will detail how to configure a FastAPI development environment on different operating systems, including Python installation, virtual environment creation, dependency management, and development tool configuration.

🐍 Python Environment Preparation

Check Python Version

FastAPI requires Python 3.7 or higher, with Python 3.8+ recommended:

bash
# Check Python version
python --version
# or
python3 --version

# Expected output: Python 3.8+

Python Installation

Windows System

powershell
# Method 1: Download from official website
# Visit https://www.python.org/downloads/
# Download the latest Python installer

# Method 2: Using Chocolatey
choco install python

# Method 3: Using Microsoft Store
# Search for "Python" and install

# Verify installation
python --version
pip --version

macOS System

bash
# Method 1: Using Homebrew (recommended)
brew install python

# Method 2: Download from official website
# Visit https://www.python.org/downloads/

# Verify installation
python3 --version
pip3 --version

Linux System

bash
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip python3-venv

# CentOS/RHEL
sudo yum install python3 python3-pip

# Fedora
sudo dnf install python3 python3-pip

# Verify installation
python3 --version
pip3 --version

🔧 Virtual Environment Management

Python's built-in virtual environment tool:

bash
# Create virtual environment
python -m venv fastapi_env

# Activate virtual environment
# Windows
fastapi_env\Scripts\activate

# macOS/Linux
source fastapi_env/bin/activate

# Confirm virtual environment is activated
# Command line prefix will show (fastapi_env)
which python  # Should point to Python in virtual environment

# Deactivate virtual environment
deactivate

Using conda

If you use Anaconda or Miniconda:

bash
# Create environment
conda create -n fastapi_env python=3.9

# Activate environment
conda activate fastapi_env

# Confirm environment
conda info --envs

# Deactivate environment
conda deactivate

Using pipenv

Modern Python dependency management tool:

bash
# Install pipenv
pip install pipenv

# Create project directory
mkdir my_fastapi_project
cd my_fastapi_project

# Create virtual environment and install dependencies
pipenv install

# Activate environment
pipenv shell

# Install packages
pipenv install fastapi uvicorn

# View dependency graph
pipenv graph

📦 FastAPI Installation

Basic Installation

bash
# Ensure virtual environment is activated
pip install fastapi

# Install ASGI server
pip install "uvicorn[standard]"

# Verify installation
python -c "import fastapi; print(fastapi.__version__)"
bash
# Install FastAPI with common dependencies
pip install "fastapi[all]"

# This includes:
# - uvicorn: ASGI server
# - pydantic[email]: Email validation
# - jinja2: Template engine
# - python-multipart: Form and file uploads
# - itsdangerous: Session support
# - python-jose[cryptography]: JWT support
# - passlib[bcrypt]: Password hashing
# - aiofiles: Async file operations

Development Dependencies

bash
# Install development and testing tools
pip install pytest pytest-asyncio httpx

# Code formatting and checking
pip install black isort flake8 mypy

# API testing tools
pip install requests

📄 Dependency Management

requirements.txt

Create and manage project dependencies:

bash
# Generate requirements.txt
pip freeze > requirements.txt

# Install from requirements.txt
pip install -r requirements.txt

Example requirements.txt file:

txt
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic[email]==2.5.0
sqlalchemy==2.0.23
alembic==1.13.1
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.6
aiofiles==23.2.1
pytest==7.4.3
pytest-asyncio==0.21.1
httpx==0.25.2
black==23.11.0
isort==5.12.0
mypy==1.7.1

pyproject.toml (Modern Way)

toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "my-fastapi-app"
version = "0.1.0"
description = "My FastAPI Application"
authors = [{name = "Your Name", email = "your.email@example.com"}]
dependencies = [
    "fastapi>=0.104.0",
    "uvicorn[standard]>=0.24.0",
    "pydantic[email]>=2.5.0",
    "sqlalchemy>=2.0.0",
    "alembic>=1.13.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.4.0",
    "pytest-asyncio>=0.21.0",
    "httpx>=0.25.0",
    "black>=23.11.0",
    "isort>=5.12.0",
    "mypy>=1.7.0",
]

[tool.black]
line-length = 88
target-version = ['py38']

[tool.isort]
profile = "black"
multi_line_output = 3

[tool.mypy]
python_version = "3.8"
warn_return_any = true
warn_unused_configs = true

🛠️ Development Tool Configuration

VS Code Settings

Create .vscode/settings.json:

json
{
    "python.defaultInterpreterPath": "./fastapi_env/bin/python",
    "python.formatting.provider": "black",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true,
    "python.linting.mypyEnabled": true,
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    },
    "files.associations": {
        "*.py": "python"
    }
}

Recommended VS Code extensions:

json
// .vscode/extensions.json
{
    "recommendations": [
        "ms-python.python",
        "ms-python.vscode-pylance", 
        "ms-python.black-formatter",
        "ms-python.isort",
        "ms-python.mypy-type-checker",
        "ms-python.flake8",
        "humao.rest-client"
    ]
}

PyCharm Settings

  1. Configure Python Interpreter:

    • File → Settings → Project → Python Interpreter
    • Select Python interpreter in virtual environment
  2. Code Formatting:

    • File → Settings → Tools → External Tools
    • Add Black formatting tool
  3. Type Checking:

    • File → Settings → Editor → Inspections
    • Enable Python type checking

Git Configuration

Create .gitignore file:

gitignore
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
env.bak/
venv.bak/
fastapi_env/

# FastAPI
.env
.env.local
.env.production

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

# Testing
.pytest_cache/
.coverage
htmlcov/

# Database
*.db
*.sqlite3

# Logs
*.log
logs/

🚀 Project Structure Initialization

Create Basic Project Structure

bash
mkdir my_fastapi_project
cd my_fastapi_project

# Create directory structure
mkdir -p {app,tests,docs,scripts}
mkdir -p app/{api,core,db,models,schemas,services}
mkdir -p app/api/v1

# Create basic files
touch app/__init__.py
touch app/main.py
touch app/core/__init__.py
touch app/core/config.py
touch app/api/__init__.py
touch app/api/v1/__init__.py
touch tests/__init__.py
touch tests/test_main.py
touch README.md
touch requirements.txt
touch .env
touch .gitignore

Project Structure Explanation

my_fastapi_project/
├── app/                    # Application code
│   ├── __init__.py
│   ├── main.py            # FastAPI application entry
│   ├── api/               # API routes
│   │   ├── __init__.py
│   │   └── v1/            # API v1 version
│   │       ├── __init__.py
│   │       ├── endpoints/  # Route endpoints
│   │       └── api.py     # API route aggregation
│   ├── core/              # Core configuration
│   │   ├── __init__.py
│   │   ├── config.py      # Configuration file
│   │   └── security.py    # Security related
│   ├── db/                # Database
│   │   ├── __init__.py
│   │   ├── database.py    # Database connection
│   │   └── base.py        # Database base class
│   ├── models/            # Database models
│   │   └── __init__.py
│   ├── schemas/           # Pydantic models
│   │   └── __init__.py
│   └── services/          # Business logic
│       └── __init__.py
├── tests/                 # Test code
│   ├── __init__.py
│   └── test_main.py
├── docs/                  # Documentation
├── scripts/               # Scripts
├── requirements.txt       # Dependency list
├── .env                   # Environment variables
├── .gitignore            # Git ignore file
└── README.md             # Project description

🔧 Environment Variable Configuration

Create .env File

bash
# .env
# Application configuration
APP_NAME="My FastAPI App"
APP_VERSION="0.1.0"
DEBUG=True
SECRET_KEY="your-secret-key-here"

# Server configuration
HOST=0.0.0.0
PORT=8000

# Database configuration
DATABASE_URL="sqlite:///./app.db"
# DATABASE_URL="postgresql://user:pass@localhost:5432/dbname"

# Redis configuration
REDIS_URL="redis://localhost:6379"

# Logging configuration
LOG_LEVEL=INFO

# CORS configuration
ALLOWED_ORIGINS=["http://localhost:3000", "http://localhost:8080"]

Configuration Management Code

Create app/core/config.py:

python
from typing import List, Optional
from pydantic import BaseSettings, validator

class Settings(BaseSettings):
    # Application configuration
    app_name: str = "FastAPI App"
    app_version: str = "0.1.0"
    debug: bool = False
    secret_key: str
    
    # Server configuration
    host: str = "0.0.0.0"
    port: int = 8000
    
    # Database configuration
    database_url: str
    
    # Redis configuration
    redis_url: Optional[str] = None
    
    # CORS configuration
    allowed_origins: List[str] = []
    
    @validator("allowed_origins", pre=True)
    def assemble_cors_origins(cls, v):
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",")]
        return v
    
    class Config:
        env_file = ".env"
        case_sensitive = False

# Create global settings instance
settings = Settings()

✅ Environment Verification

Create Test Application

Create app/main.py:

python
from fastapi import FastAPI
from app.core.config import settings

app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    debug=settings.debug
)

@app.get("/")
async def root():
    return {
        "message": "Hello FastAPI!", 
        "app_name": settings.app_name,
        "version": settings.app_version
    }

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

Run Application Test

bash
# Ensure virtual environment is activated
# Enter project directory
cd my_fastapi_project

# Run application
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Or use environment variables
uvicorn app.main:app --reload

Verify Installation

bash
# Test API endpoints
curl http://localhost:8000/
curl http://localhost:8000/health

# Access interactive documentation
# Open in browser: http://localhost:8000/docs
# Or: http://localhost:8000/redoc

🐳 Docker Environment (Optional)

Dockerfile

dockerfile
FROM python:3.9-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Copy dependency file
COPY requirements.txt .

# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY ./app /app/app

# Expose port
EXPOSE 8000

# Start command
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

docker-compose.yml

yaml
version: '3.8'

services:
  web:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - ./app:/app/app
    environment:
      - DEBUG=True
      - DATABASE_URL=postgresql://user:pass@db:5432/fastapi_db
    depends_on:
      - db
      - redis

  db:
    image: postgres:13
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: fastapi_db
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  postgres_data:

📋 Development Workflow

Daily Development Commands

bash
# Activate virtual environment
source fastapi_env/bin/activate  # Linux/macOS
# fastapi_env\Scripts\activate   # Windows

# Start development server
uvicorn app.main:app --reload

# Run tests
pytest

# Code formatting
black app/ tests/
isort app/ tests/

# Type checking
mypy app/

# Code quality check
flake8 app/ tests/

Development Script

Create scripts/dev.sh:

bash
#!/bin/bash
set -e

echo "Starting FastAPI development environment..."

# Check virtual environment
if [[ "$VIRTUAL_ENV" == "" ]]; then
    echo "Please activate virtual environment first"
    exit 1
fi

# Install dependencies
pip install -r requirements.txt

# Run code checks
echo "Running code quality checks..."
black --check app/ tests/
isort --check-only app/ tests/
flake8 app/ tests/
mypy app/

# Run tests
echo "Running tests..."
pytest

# Start development server
echo "Starting development server..."
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

🔍 Troubleshooting

Common Issues

1. Python Version Incompatibility

bash
# Error: ModuleNotFoundError
# Solution: Check Python version
python --version

# Ensure using Python 3.7+
# If multiple versions exist, specify explicitly
python3.9 -m venv fastapi_env

2. Virtual Environment Issues

bash
# Error: Cannot activate virtual environment
# Solution: Recreate virtual environment
rm -rf fastapi_env
python -m venv fastapi_env
source fastapi_env/bin/activate

3. Dependency Installation Failure

bash
# Error: Compilation error
# Solution: Install system dependencies
# Ubuntu/Debian
sudo apt-get install python3-dev build-essential

# macOS
xcode-select --install

# Upgrade pip
pip install --upgrade pip setuptools wheel

4. Port Already in Use

bash
# Error: Address already in use
# Solution: Find and kill process using port
lsof -i :8000
kill -9 <PID>

# Or use different port
uvicorn app.main:app --port 8001

Summary

In this chapter, we completed the full setup of a FastAPI development environment, including:

  • Python environment installation and configuration
  • Virtual environment creation and management
  • FastAPI and related dependency installation
  • Development tool configuration and optimization
  • Project structure initialization
  • Environment variable and configuration management
  • Docker containerized deployment

Now you have a fully functional FastAPI development environment and can start building your first FastAPI application!

Environment Management Recommendations

  • Always use virtual environments for development
  • Regularly update dependency package versions
  • Use code formatting tools to maintain consistent code style
  • Configure IDE for the best development experience

In the next chapter, we will create our first FastAPI application and experience FastAPI's powerful features.

Content is for learning and research only.