# Backend Development Study & Practice Guide
## FastAPI, Docker & Database
## ๐ Study Plan (8-Week Program)
### ๐๏ธ Weekly Structure
- **Monday-Wednesday**: Theory & Concepts
- **Thursday-Friday**: Hands-on Practice
- **Weekend**: Project Work & Review
---
## ๐ฏ Week 1: Python & FastAPI Fundamentals
### ๐ Study Topics
- **Python Basics**: Type hints, async/await, decorators
- **FastAPI Introduction**: Setup, routing, request handling
- **Pydantic Models**: Data validation, serialization
### ๐ ๏ธ Practice Exercises
#### Exercise 1: Basic FastAPI App
```python
# Day 1: Create a simple book API
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
class Book(BaseModel):
id: int
title: str
author: str
year: int
books = []
@app.get("/")
async def read_root():
return {"message": "Book API"}
@app.post("/books/", response_model=Book)
async def create_book(book: Book):
books.append(book)
return book
@app.get("/books/", response_model=List[Book])
async def read_books():
return books
```
#### Exercise 2: CRUD Operations
```python
# Day 2: Implement full CRUD
from fastapi import HTTPException
@app.get("/books/{book_id}", response_model=Book)
async def read_book(book_id: int):
for book in books:
if book.id == book_id:
return book
raise HTTPException(status_code=404, detail="Book not found")
@app.put("/books/{book_id}", response_model=Book)
async def update_book(book_id: int, updated_book: Book):
for i, book in enumerate(books):
if book.id == book_id:
books[i] = updated_book
return updated_book
raise HTTPException(status_code=404, detail="Book not found")
@app.delete("/books/{book_id}")
async def delete_book(book_id: int):
for i, book in enumerate(books):
if book.id == book_id:
del books[i]
return {"message": "Book deleted"}
raise HTTPException(status_code=404, detail="Book not found")
```
### ๐ฏ Weekend Project: Personal Library API
Create a library management system with:
- Book CRUD operations
- Author management
- Search functionality
- Basic error handling
---
## ๐๏ธ Week 2: Database Fundamentals
### ๐ Study Topics
- **SQL Basics**: SELECT, INSERT, UPDATE, DELETE, JOIN
- **SQLAlchemy ORM**: Models, sessions, relationships
- **Database Design**: Normalization, relationships
### ๐ ๏ธ Practice Exercises
#### Exercise 1: SQLAlchemy Setup
```python
# Day 1: Database configuration
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Author(Base):
__tablename__ = "authors"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
books = relationship("Book", back_populates="author")
class Book(Base):
__tablename__ = "books"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
year = Column(Integer)
author_id = Column(Integer, ForeignKey("authors.id"))
author = relationship("Author", back_populates="books")
Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
```
#### Exercise 2: Database Operations
```python
# Day 2: Implement database CRUD
from sqlalchemy.orm import Session
from fastapi import Depends
@app.post("/authors/")
async def create_author(name: str, db: Session = Depends(get_db)):
db_author = Author(name=name)
db.add(db_author)
db.commit()
db.refresh(db_author)
return db_author
@app.get("/authors/{author_id}/books")
async def get_author_books(author_id: int, db: Session = Depends(get_db)):
author = db.query(Author).filter(Author.id == author_id).first()
if not author:
raise HTTPException(status_code=404, detail="Author not found")
return author.books
```
### ๐ฏ Weekend Project: Blog System with Database
Create a blogging platform with:
- User authentication (basic)
- Post creation and management
- Comment system
- User-profile relationships
---
## ๐ณ Week 3: Docker Fundamentals
### ๐ Study Topics
- **Container Concepts**: Images, containers, Dockerfile
- **Docker Compose**: Multi-container applications
- **Docker Networking**: Container communication
### ๐ ๏ธ Practice Exercises
#### Exercise 1: Create Dockerfile
```dockerfile
# Day 1: Basic Docker setup
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
```
#### Exercise 2: Docker Compose with Database
```yaml
# Day 2: Multi-service application
version: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/mydb
depends_on:
- db
volumes:
- .:/app
db:
image: postgres:13
environment:
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
- POSTGRES_DB=mydb
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
```
### ๐ฏ Weekend Project: Containerize Your Blog
Dockerize the blog system from Week 2 with:
- FastAPI container
- PostgreSQL container
- Proper environment configuration
- Volume for data persistence
---
## ๐ Week 4: Advanced FastAPI Features
### ๐ Study Topics
- **Dependency Injection**: Security, database sessions
- **Middleware**: CORS, authentication, logging
- **Background Tasks**: Async operations, email sending
### ๐ ๏ธ Practice Exercises
#### Exercise 1: Dependency Injection
```python
# Day 1: Custom dependencies
from fastapi import Depends, Header, HTTPException
async def get_token_header(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
async def get_query_token(token: str):
if token != "jessica":
raise HTTPException(status_code=400, detail="No Jessica token provided")
@app.get("/items/", dependencies=[Depends(get_token_header)])
async def read_items():
return [{"item": "Foo"}, {"item": "Bar"}]
```
#### Exercise 2: Background Tasks
```python
# Day 2: Async operations
from fastapi import BackgroundTasks
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
```
### ๐ฏ Weekend Project: Enhanced Library System
Add to your library system:
- User authentication with JWT
- Role-based access control
- Email notifications for new books
- Request logging middleware
---
## ๐ Week 5: Authentication & Security
### ๐ Study Topics
- **JWT Tokens**: Creation, validation, refresh
- **Password Hashing**: bcrypt, security best practices
- **OAuth2**: Password flow, scopes
### ๐ ๏ธ Practice Exercises
#### Exercise 1: User Authentication
```python
# Day 1: JWT implementation
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
```
#### Exercise 2: Protected Routes
```python
# Day 2: Route protection
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=401,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
return username
@app.get("/users/me")
async def read_users_me(current_user: str = Depends(get_current_user)):
return {"username": current_user}
```
### ๐ฏ Weekend Project: Secure E-commerce API
Create a secure e-commerce system with:
- User registration and login
- Product management (admin only)
- Shopping cart functionality
- Order processing with authentication
---
## ๐ Week 6: Advanced Database Concepts
### ๐ Study Topics
- **Database Relationships**: One-to-many, many-to-many
- **Query Optimization**: Indexing, eager loading
- **Database Migrations**: Alembic, schema changes
### ๐ ๏ธ Practice Exercises
#### Exercise 1: Complex Relationships
```python
# Day 1: Many-to-many relationship
from sqlalchemy import Table, Column, Integer, ForeignKey
# Association table for many-to-many
book_categories = Table(
'book_categories',
Base.metadata,
Column('book_id', Integer, ForeignKey('books.id')),
Column('category_id', Integer, ForeignKey('categories.id'))
)
class Category(Base):
__tablename__ = "categories"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
books = relationship("Book", secondary=book_categories, back_populates="categories")
class Book(Base):
__tablename__ = "books"
# ... existing fields ...
categories = relationship("Category", secondary=book_categories, back_populates="books")
```
#### Exercise 2: Database Migrations
```bash
# Day 2: Alembic setup and usage
# Install alembic
pip install alembic
# Initialize
alembic init alembic
# Create migration
alembic revision --autogenerate -m "Add categories table"
# Apply migration
alembic upgrade head
# Downgrade if needed
alembic downgrade -1
```
### ๐ฏ Weekend Project: Social Media API
Build a social media backend with:
- User profiles with followers (many-to-many)
- Posts with likes and comments
- News feed based on followed users
- Database migrations for schema changes
---
## ๐ Week 7: Production Deployment
### ๐ Study Topics
- **Production Docker**: Multi-stage builds, optimization
- **Environment Configuration**: Different environments
- **Monitoring & Logging**: Application insights
### ๐ ๏ธ Practice Exercises
#### Exercise 1: Production Dockerfile
```dockerfile
# Day 1: Optimized production setup
FROM python:3.11-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH
COPY . .
RUN useradd --create-home --shell /bin/bash app
USER app
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
```
#### Exercise 2: Environment Management
```python
# Day 2: Environment-specific config
from pydantic_settings import BaseSettings
from typing import Optional
class Settings(BaseSettings):
PROJECT_NAME: str = "My App"
ENVIRONMENT: str = "development"
DATABASE_URL: str
SECRET_KEY: str
class Config:
env_file = ".env"
settings = Settings()
# Conditional setup based on environment
if settings.ENVIRONMENT == "production":
# Production-specific settings
pass
```
### ๐ฏ Weekend Project: Deploy Your Application
Deploy one of your previous projects with:
- Production Docker configuration
- Environment variables for secrets
- Proper logging setup
- Health check endpoints
---
## ๐งช Week 8: Testing & Best Practices
### ๐ Study Topics
- **Testing Strategies**: Unit tests, integration tests
- **API Documentation**: OpenAPI, Swagger UI
- **Code Quality**: Linting, formatting, type checking
### ๐ ๏ธ Practice Exercises
#### Exercise 1: Testing Setup
```python
# Day 1: Write tests for your API
import pytest
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_create_book():
response = client.post(
"/books/",
json={"id": 1, "title": "Test Book", "author": "Test Author", "year": 2023}
)
assert response.status_code == 200
data = response.json()
assert data["title"] == "Test Book"
assert "id" in data
def test_read_book_not_found():
response = client.get("/books/999")
assert response.status_code == 404
```
#### Exercise 2: Code Quality Tools
```bash
# Day 2: Set up code quality
# Install tools
pip install black flake8 mypy
# Format code
black app/ tests/
# Check style
flake8 app/ tests/
# Type checking
mypy app/
```
### ๐ฏ Final Project: Complete Backend System
Build a complete backend system incorporating all learned concepts:
- User authentication and authorization
- Complex database relationships
- Docker containerization
- Comprehensive testing
- Production-ready configuration
---
## ๐ Progress Tracking Checklist
### โ
Week 1 Completion
- [ ] Basic FastAPI app running
- [ ] CRUD operations implemented
- [ ] Pydantic models understood
- [ ] Personal Library API completed
### โ
Week 2 Completion
- [ ] Database models created
- [ ] SQLAlchemy sessions working
- [ ] Relationships implemented
- [ ] Blog System with database completed
### โ
Week 3 Completion
- [ ] Dockerfile created
- [ ] Docker Compose setup working
- [ ] Multi-container app running
- [ ] Blog system containerized
### โ
Week 4 Completion
- [ ] Dependency injection implemented
- [ ] Middleware added
- [ ] Background tasks working
- [ ] Enhanced Library System completed
### โ
Week 5 Completion
- [ ] JWT authentication working
- [ ] Password hashing implemented
- [ ] Protected routes tested
- [ ] Secure E-commerce API completed
### โ
Week 6 Completion
- [ ] Complex relationships modeled
- [ ] Database migrations working
- [ ] Query optimization understood
- [ ] Social Media API completed
### โ
Week 7 Completion
- [ ] Production Docker setup
- [ ] Environment configuration working
- [ ] Application deployed
- [ ] Monitoring implemented
### โ
Week 8 Completion
- [ ] Test suite created
- [ ] Code quality tools configured
- [ ] Documentation completed
- [ ] Final project delivered
---
## ๐ Learning Resources
### ๐ Recommended Reading
1. **FastAPI Documentation** - Official docs
2. **Docker Documentation** - Official guides
3. **SQLAlchemy Documentation** - ORM reference
4. **"Designing Data-Intensive Applications"** - Martin Kleppmann
### ๐ฅ Video Courses
1. **FastAPI Full Course** - FreeCodeCamp
2. **Docker & Kubernetes** - TechWorld with Nana
3. **Python Backend Development** - multiple platforms
### ๐ ๏ธ Practice Platforms
1. **LeetCode** - Algorithm practice
2. **HackerRank** - SQL and Python challenges
3. **GitHub** - Open source contributions
### ๐ Project Ideas for Portfolio
1. **E-commerce Backend** - Full-featured store API
2. **Social Media API** - Twitter-like backend
3. **Task Management System** - Trello-like API
4. **Real Estate Platform** - Property listing API
5. **Learning Management System** - Course platform backend
This comprehensive study and practice guide will take you from beginner to proficient in backend development with FastAPI, Docker, and databases. Follow the weekly structure, complete all exercises, and build the projects to solidify your learning.