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)
- Environment Setup & Python Virtual Environments
- FastAPI Basics: Your First API Endpoint
- Project Structure & Configuration Management
Phase 2: Core Backend (Posts 4-7)
- Request/Response Models with Pydantic
- Dependency Injection & Service Layer Pattern
- Error Handling & Validation
- Logging & Monitoring Basics
Phase 3: AI Integration (Posts 8-11)
- Setting Up Ollama Locally
- Building the AI Service Abstraction Layer
- Implementing Chat Endpoints
- Streaming Responses (Real-time AI Chat)
Phase 4: Testing & Frontend (Posts 12-14)
- Simple HTML Test Interface
- API Testing with Pytest
- CORS & React Frontend Integration
Phase 5: Advanced Features (Posts 15-18)
- Adding HuggingFace Models
- RunPod GPU Integration
- Rate Limiting & Authentication
- 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 projects | Disk Space: Each project has its own copy of packages |
| Reproducibility: Easy to share exact dependencies | Setup Time: Need to create venv for each project |
| Clean System: Global Python stays clean | Learning Curve: One more step for beginners |
| Version Control: Lock specific package versions | Activation 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 modulevenv(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:
- Changes PATH: Your system now looks in
venv/binfirst for Python and pip - Isolates pip: Any package you install goes into
venv/lib, not globally - 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:
- FastAPI: The web framework we’ll use
- Modern, fast, based on Python type hints
- Automatic API documentation
- Built-in validation
- 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:
- Python: The language.
- FastAPI: The framework (the logic, validation, and routes perfect for API development).
- Uvicorn: The server (the delivery guy who brings the requests to the door).
- 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
- Click Extensions icon (or press
Ctrl+Shift+X/Cmd+Shift+X) - Search for “Python”
- Install the extension by Microsoft
C. Select Your Virtual Environment
- Press
Ctrl+Shift+P(orCmd+Shift+Pon Mac) - Type: “Python: Select Interpreter”
- 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 Pythonterminal.activateEnvironment: Auto-activate venv in terminalformatOnSave: Auto-format code when you savefiles.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:
- Imports: We import FastAPI class
- App Instance:
app = FastAPI(...)creates our application - Decorators:
@app.get("/")defines a route@: Python decorator (modifies the function below)get: HTTP method (GET request)"/": URL path (root)
- async def: Asynchronous function (allows concurrent requests)
- 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 installedmain: 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:
- Click on
GET / - Click “Try it out”
- Click “Execute”
- 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 (
.envfiles)
🎯 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
- Experiment: Add a new endpoint
@app.get("/about")that returns information about yourself - Explore: Try breaking the code on purpose, see what errors FastAPI gives you
- Read: Visit http://127.0.0.1:8000/docs and click around the generated documentation
- 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?
Why should I use a virtual environment instead of global installation?
How do I create a virtual environment in Python?
How do I activate and deactivate a virtual environment?
Should I include the virtual environment folder in my Git repository?
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