Ep.01 Setting Up Your Python Development Environment with Virtual Environments

Views: 5

A Python virtual environment is an isolated directory that allows you to manage project-specific dependencies without affecting your global system. By using the venv module, developers can avoid version conflicts and ensure consistent development environments across different machines.

What We’re Building: A scalable FastAPI backend that serves AI models, starting with Ollama (free, local), with the architecture to easily add HuggingFace, RunPod, or any other AI service. Learning Outcomes Include: Python fundamentals, FastAPI mastery, AI integration patterns, production best practices.

📚 Complete Development Roadmap

Phase 1: Foundation (Posts 1-3)

  1. Environment Setup & Python Virtual Environments
  2. FastAPI Basics: Your First API Endpoint
  3. Project Structure & Configuration Management

Phase 2: Core Backend (Posts 4-7)

  1. Request/Response Models with Pydantic
  2. Dependency Injection & Service Layer Pattern
  3. Error Handling & Validation
  4. Logging & Monitoring Basics

Phase 3: AI Integration (Posts 8-11)

  1. Setting Up Ollama Locally
  2. Building the AI Service Abstraction Layer
  3. Implementing Chat Endpoints
  4. Streaming Responses (Real-time AI Chat)

Phase 4: Testing & Frontend (Posts 12-14)

  1. Simple HTML Test Interface
  2. API Testing with Pytest
  3. CORS & React Frontend Integration

Phase 5: Advanced Features (Posts 15-18)

  1. Adding HuggingFace Models
  2. RunPod GPU Integration
  3. Rate Limiting & Authentication
  4. Docker & Deployment Preparation

Let’s start the Episode 1. In this episode you’ll learn:

  • Installing your first packages
  • What virtual environments are and why they’re essential
  • How to create and manage virtual environments
  • Setting up VS Code for Python development

📖 Understanding Virtual Environments

What is a Virtual Environment?

A virtual environment is an isolated Python workspace for your project. Think of it like a separate container where your project lives with its own set of Python packages.

Real-world analogy: Imagine you’re a chef working on multiple recipes. Each recipe needs specific ingredients (packages). Instead of mixing all ingredients in one pantry (which could cause conflicts), you have separate ingredient boxes for each recipe. That’s what virtual environments do for Python projects!

Why Do We Need Virtual Environments?

Problem Without Virtual Environments:

Your Computer (Global Python)
├── Project A needs Django 3.2
├── Project B needs Django 4.0  ❌ CONFLICT!
└── Project C needs Flask 2.0 + Django 3.2  ❌ CONFUSION!

Solution With Virtual Environments:

Your Computer
├── venv_projectA/
│   └── Django 3.2 ✅
├── venv_projectB/
│   └── Django 4.0 ✅
└── venv_projectC/
    ├── Flask 2.0 ✅
    └── Django 3.2 ✅

Pros and Cons

Pros ✅Cons ❌
Isolation: No package conflicts between projectsDisk Space: Each project has its own copy of packages
Reproducibility: Easy to share exact dependenciesSetup Time: Need to create venv for each project
Clean System: Global Python stays cleanLearning Curve: One more step for beginners
Version Control: Lock specific package versionsActivation Required: Must activate before working

🛠️ Step-by-Step Implementation

Step 1: Verify Python Installation

Open your terminal (or Command Prompt on Windows) and check your Python version:

python --version
# or on some systems:
python3 --version

Expected Output: Python 3.8.0 or higher

If Python is not installed:

  • Windows: Download from python.org
  • macOS: brew install python3 (if you have Homebrew)
  • Linux: sudo apt update && sudo apt install python3 python3-pip python3-venv

Step 2: Create Your Project Directory

# Navigate to where you want your project
cd ~/Documents  # or C:\Users\YourName\Documents on Windows

# Create project folder
mkdir fastapi-ai-backend
cd fastapi-ai-backend

What we just did:

  • mkdir: Make directory (creates a new folder)
  • cd: Change directory (moves into that folder)

Step 3: Create a Virtual Environment

# Create virtual environment named 'venv'
python -m venv venv

# On some systems, use:
python3 -m venv venv

Breaking down this command:

  • python: Calls the Python interpreter
  • -m venv: Runs the virtual environment module
  • venv (last word): Name of the folder where the virtual environment will be stored

What happened? A new folder named venv was created with this structure:

venv/
├── bin/          # (or Scripts/ on Windows) - Activation scripts
├── include/      # C headers for compiling packages
├── lib/          # Where packages get installed
└── pyvenv.cfg    # Configuration file

Step 4: Activate the Virtual Environment

On macOS/Linux:

source venv/bin/activate

On Windows (Command Prompt):

venv\Scripts\activate

On Windows (PowerShell):

venv\Scripts\Activate.ps1

If you get an error on Windows PowerShell about execution policies:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

How to know it worked? Your terminal prompt should now start with (venv):

(venv) user@computer:~/fastapi-ai-backend$

Step 5: Understand What Activation Does

When you activate a virtual environment:

  1. Changes PATH: Your system now looks in venv/bin first for Python and pip
  2. Isolates pip: Any package you install goes into venv/lib, not globally
  3. Sets environment variables: Points to the virtual environment’s Python

Test it:

# Check which Python is being used
which python  # macOS/Linux
where python  # Windows

# Should point to: /path/to/your/project/venv/bin/python
# OR: /path/to/your/project/venv/Scripts/python.exe

Step 6: Upgrade pip (Package Installer)

pip install --upgrade pip 
#if error use this:
python -m pip install --upgrade pip

What is pip?

  • Pip Installs Packages (recursive acronym!)
  • It’s Python’s package manager, like npm for Node.js or apt for Ubuntu
  • Downloads packages from PyPI (Python Package Index)

Step 7: Install FastAPI and Dependencies

python -m pip install fastapi uvicorn[standard]

What we’re installing:

  1. FastAPI: The web framework we’ll use
    • Modern, fast, based on Python type hints
    • Automatic API documentation
    • Built-in validation
  2. Uvicorn: ASGI server
    • Runs your FastAPI application
    • Handles HTTP requests
    • [standard] installs extra features (websockets, colored logs)

Watch the installation: You’ll see output like:

Collecting fastapi
  Downloading fastapi-0.109.0-py3-none-any.whl (92 kB)
Collecting uvicorn[standard]
  Downloading uvicorn-0.27.0-py3-none-any.whl (60 kB)
...
Successfully installed fastapi-0.109.0 uvicorn-0.27.0 ...

Summary: The “FastAPI Stack”

Think of these terms like this:

  1. Python: The language.
  2. FastAPI: The framework (the logic, validation, and routes perfect for API development).
  3. Uvicorn: The server (the delivery guy who brings the requests to the door).
  4. Pydantic: The security guard (validates that the data coming in is correct).

Step 8: Create a Requirements File

pip freeze > requirements.txt

What is requirements.txt?

  • A file listing all installed packages and their versions
  • Allows others (or future you) to recreate the exact environment
  • Industry standard for Python projects

View it:

bash

cat requirements.txt  # macOS/Linux
type requirements.txt # Windows

Example output:

annotated-types==0.6.0
anyio==4.2.0
fastapi==0.109.0
idna==3.6
pydantic==2.5.3
pydantic-core==2.14.6
sniffio==1.3.0
starlette==0.35.1
typing-extensions==4.9.0
uvicorn==0.27.0

Step 9: Set Up VS Code

A. Open VS Code in Your Project

# If you have 'code' command installed:
code .

# Otherwise, open VS Code manually and:
# File > Open Folder > Select 'fastapi-ai-backend'

B. Install Python Extension

  1. Click Extensions icon (or press Ctrl+Shift+X / Cmd+Shift+X)
  2. Search for “Python”
  3. Install the extension by Microsoft

C. Select Your Virtual Environment

  1. Press Ctrl+Shift+P (or Cmd+Shift+P on Mac)
  2. Type: “Python: Select Interpreter”
  3. Choose the one that shows ./venv/bin/python

Visual confirmation: Bottom-left of VS Code should show:

Python 3.x.x ('venv': venv)

D. Configure VS Code Settings (Optional but Recommended)

Create .vscode/settings.json in your project:

mkdir .vscode

Create the file .vscode/settings.json with this content:

{
    "python.defaultInterpreterPath": "${workspaceFolder}/venv/Scripts/python.exe",
    "python.terminal.activateEnvironment": true,
    
    // Use specific extensions for Linting and Formatting
    "flake8.enabled": true,
    "black-formatter.importStrategy": "fromEnvironment",

    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": "explicit"
    },

    "[python]": {
        // Corrected: ms-python.python is the language server, NOT the formatter
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.tabSize": 4,
        "editor.insertSpaces": true
    },

    "files.exclude": {
        "**/__pycache__": true,
        "**/*.pyc": true,
        "**/.venv": false // Keep this visible so you can see your scripts
    }
}

Make sure “Black Formatter” extension by Microsoft is installed in the VSCode.

What each setting does:

  • defaultInterpreterPath: Always use venv Python
  • terminal.activateEnvironment: Auto-activate venv in terminal
  • formatOnSave: Auto-format code when you save
  • files.exclude: Hide compiled Python files from sidebar

Step 10: Create Your First Python File

Create main.py:

"""
FastAPI AI Backend - Main Application Entry Point

This is our first FastAPI application!
We'll build upon this in future tutorials.
"""

from fastapi import FastAPI

# Create FastAPI application instance
app = FastAPI(
    title="AI Backend API",
    description="A production-ready FastAPI backend for AI models",
    version="0.1.0"
)


# Define a route (endpoint)
@app.get("/")
async def root():
    """
    Root endpoint - Health check
    
    Returns:
        dict: Welcome message and status
    """
    return {
        "message": "Welcome to FastAPI AI Backend!",
        "status": "running",
        "version": "0.1.0"
    }


@app.get("/health")
async def health_check():
    """
    Health check endpoint for monitoring
    
    Returns:
        dict: Health status
    """
    return {"status": "healthy"}

Code Explanation:

  1. Imports: We import FastAPI class
  2. App Instance: app = FastAPI(...) creates our application
  3. Decorators: @app.get("/") defines a route
    • @: Python decorator (modifies the function below)
    • get: HTTP method (GET request)
    • "/": URL path (root)
  4. async def: Asynchronous function (allows concurrent requests)
  5. Docstrings: """...""" document what functions do

Step 11: Run Your First FastAPI Server

uvicorn main:app --reload

Breaking down this command:

  • uvicorn: The ASGI server we installed
  • main: The Python file name (main.py)
  • app: The FastAPI instance variable in that file
  • --reload: Auto-restart server when code changes (development only!)

Expected output:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12345] using StatReload
INFO:     Started server process [12346]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Step 12: Test Your API

Option 1: Browser

Open: http://127.0.0.1:8000

You should see:

json

{
  "message": "Welcome to FastAPI AI Backend!",
  "status": "running",
  "version": "0.1.0"
}

Option 2: Automatic Documentation

FastAPI generates interactive docs automatically!

Open: http://127.0.0.1:8000/docs

You’ll see Swagger UI – an interactive API testing interface!

Try it:

  1. Click on GET /
  2. Click “Try it out”
  3. Click “Execute”
  4. See the response!

Option 3: Alternative Docs

Open: http://127.0.0.1:8000/redoc

ReDoc – Another documentation style, great for reading.


Step 13: Create a .gitignore File

If you plan to use Git (version control):

Create .gitignore file with these contents:

# Virtual Environment
venv/
env/
ENV/

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python

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

# Environment variables
.env
.env.local

# OS
.DS_Store
Thumbs.db

# Logs
*.log

# Testing
.pytest_cache/
.coverage
htmlcov/

Why .gitignore?

  • Prevents committing unnecessary files to Git
  • Keeps your repository clean
  • Avoids sharing secrets (.env files)

🎯 Project Structure So Far

fastapi-ai-backend/
├── venv/                  # Virtual environment (not in Git)
├── .vscode/              
│   └── settings.json      # VS Code configuration
├── .gitignore            # Git ignore rules
├── main.py               # Our FastAPI application
└── requirements.txt      # Package dependencies

🔧 Common Issues & Solutions

Issue 1: “python: command not found”

Solution: Try python3 instead of python

Issue 2: Virtual environment won’t activate on Windows

Solution: Run PowerShell as Administrator and execute:

powershell

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Issue 3: “ModuleNotFoundError: No module named ‘fastapi’”

Solution: Make sure your virtual environment is activated (you should see (venv) in terminal)

Issue 4: Port 8000 already in use

Solution:

# Use a different port
uvicorn main:app --reload --port 8001

📚 Key Concepts Summary

Virtual Environments

  • ✅ Isolated Python workspace per project
  • ✅ Prevents package conflicts
  • ✅ Reproducible environments via requirements.txt

Commands to Remember

# Create venv
python -m venv venv

# Activate
source venv/bin/activate  # Mac/Linux
venv\Scripts\activate     # Windows

# Deactivate
deactivate

# Install packages
pip install package-name

# Save dependencies
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

# Run FastAPI
uvicorn main:app --reload

FastAPI Basics

  • Modern Python web framework
  • Auto-generates documentation
  • Built on type hints and Pydantic
  • Fast performance (comparable to Node.js, Go)

🎓 Homework / Practice

  1. Experiment: Add a new endpoint @app.get("/about") that returns information about yourself
  2. Explore: Try breaking the code on purpose, see what errors FastAPI gives you
  3. Read: Visit http://127.0.0.1:8000/docs and click around the generated documentation
  4. Challenge: Add a @app.get("/time") endpoint that returns the current server time (hint: from datetime import datetime)

🚀 Next Steps

In Blog Post 2, we’ll dive into:

  • Understanding HTTP methods (GET, POST, PUT, DELETE)
  • Path parameters and query parameters
  • Request/response models with Pydantic
  • Creating our first POST endpoint

💬 Quick Reference Card

# Create & activate venv
python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows

# Install packages
pip install fastapi uvicorn[standard]
pip freeze > requirements.txt

# Basic FastAPI app
from fastapi import FastAPI
app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

# Run server
uvicorn main:app --reload

What is a Python virtual environment?

A virtual environment is an isolated directory that contains a specific Python installation and its own set of libraries. It allows you to manage dependencies for different projects separately, ensuring that an update in one project doesn’t break another.
Using global installations can lead to “dependency hell,” where different projects require conflicting versions of the same library. Virtual environments prevent this by sandboxing each project’s requirements.
You can create one using the built-in venv module by running the command python -m venv venv in your project’s root directory.
On Windows: Run .\venv\Scripts\activate. On macOS/Linux: Run source venv/bin/activate. To stop using it, simply type deactivate in your terminal.
No. You should add the environment folder (usually named venv/ or .venv/) to your .gitignore file. Instead, share your dependencies using a requirements.txt file so others can recreate the environment themselves.

Congratulations! 🎉 You’ve completed the first step in building a production-ready FastAPI AI backend. You now understand:

  • What virtual environments are and why they matter
  • How to set up a proper Python development environment
  • How to create your first FastAPI application
  • How to use FastAPI’s automatic documentation

Save this as a reference, and let’s move on to the next tutorial when you’re ready!


Did you find this helpful? Let me know if anything needs clarification!

Leave a Reply

Your email address will not be published. Required fields are marked *

Search