Skip to content

f1sherFM/bookstore-api-course

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“š BookStore API - Production-Ready FastAPI System

Python FastAPI Docker Tests Coverage License

Modern, production-ready book management system with complete DevOps pipeline

πŸš€ Quick Start β€’ πŸ—ΊοΈ Learning Roadmap β€’ πŸ“– Documentation β€’ 🐳 Docker β€’ ☸️ Kubernetes β€’ πŸ”§ Development β€’ πŸš€ Future Roadmap


🌟 Features

⚑ Core Application

  • FastAPI with automatic OpenAPI documentation
  • SQLAlchemy ORM with PostgreSQL and SQLite support
  • JWT Authentication with secure user management
  • Pydantic models for data validation
  • Async/await support for high performance
  • CRUD operations for books, authors, users, reviews

πŸ›‘οΈ Production-Ready Infrastructure

  • Docker containerization with multi-stage builds
  • Docker Compose for local development and production
  • Kubernetes manifests for cloud deployment
  • Nginx load balancer with SSL termination
  • PostgreSQL with performance optimization
  • Redis caching for fast data access

πŸ“Š Monitoring & Observability

  • Prometheus application and system metrics collection
  • Grafana dashboards for performance visualization
  • Loki log aggregation with structured format
  • Health checks for service status monitoring
  • Structured logging with JSON format and request tracing

πŸ”’ Security & Performance

  • Rate limiting с Ρ€Π°Π·Π½Ρ‹ΠΌΠΈ Π»ΠΈΠΌΠΈΡ‚Π°ΠΌΠΈ для endpoints
  • Security headers (HSTS, CSP, XSS protection)
  • JWT tokens с secure secrets
  • Input validation с Pydantic schemas
  • Auto-scaling с Horizontal Pod Autoscaler
  • Backup procedures с автоматичСской Ρ€ΠΎΡ‚Π°Ρ†ΠΈΠ΅ΠΉ

πŸš€ CI/CD & Automation

  • GitHub Actions with complete testing pipeline
  • Automated testing (unit, integration, property-based, performance)
  • Security scanning (Bandit, Safety, Semgrep)
  • Docker registry integration with GitHub Container Registry
  • Multi-environment deployment (staging/production)
  • Automated releases with versioning

πŸš€ Quick Start

Option 1: One-Command Setup (Recommended)

# Clone and setup development environment
git clone <repository-url>
cd bookstore-api
./scripts/setup-dev.sh

# Start development server
make dev

Option 2: Docker Development

# Start all services with Docker
cd deployment/docker
docker-compose up -d

# API available at: http://localhost:8000
# Docs available at: http://localhost:8000/docs

Option 3: Manual Setup

# Install dependencies
pip install -r requirements/base.txt -r requirements/api.txt

# Setup environment
cp .env.example .env

# Run tests
pytest tests/

# Start development server
python run_bookstore.py

πŸ—ΊοΈ Learning Roadmap

Whether you're a beginner or experienced developer, this roadmap will guide you through using and understanding the BookStore API project.

🎯 Choose Your Path

πŸš€ Quick Explorer (5 minutes) - Just want to see it work?

Goal: Get the API running and make your first request

  1. Setup (2 min)

    git clone <repository-url>
    cd bookstore-api
    ./scripts/setup-dev.sh
  2. Start (1 min)

    make dev
  3. Explore (2 min)

Next Steps: Choose the "API User" or "Developer" path below

πŸ“± API User (30 minutes) - Want to integrate with the API?

Goal: Understand how to use the API in your applications

  1. Authentication Flow (10 min)

    • Register a new user: POST /auth/register
    • Login to get JWT token: POST /auth/login
    • Use token in headers: Authorization: Bearer <token>
    • πŸ“– Read: Authentication Guide
  2. Core Operations (15 min)

    • List books with pagination: GET /api/v1/books/?page=1&size=10
    • Search books: GET /api/v1/books/?q=python
    • Get book details: GET /api/v1/books/{id}
    • Add to reading list: POST /api/v1/reading-lists/books/{id}
    • πŸ“– Read: API Examples
  3. Advanced Features (5 min)

    • Rate limiting and error handling
    • Pagination and filtering
    • Real-time health monitoring
    • πŸ“– Read: API Documentation

Next Steps:

  • Build a client application
  • Explore monitoring endpoints
  • Check out the "Production User" path
πŸ‘¨β€πŸ’» Developer (2 hours) - Want to understand and modify the code?

Goal: Understand the codebase and make your first contribution

  1. Code Structure (30 min)

    • Explore bookstore/ directory structure
    • Understand FastAPI app setup in main.py
    • Review models in models.py and schemas in schemas.py
    • Check routing in routers/ directory
    • πŸ“– Read: Project Structure
  2. Development Workflow (45 min)

    • Setup development environment: make install
    • Run tests: make test
    • Code formatting: make format
    • Add a new endpoint (try adding a genre endpoint)
    • πŸ“– Read: Development Guide
  3. Testing Deep Dive (30 min)

    • Unit tests: make test-unit
    • Integration tests: make test-integration
    • Property-based tests: make test-property
    • Add tests for your new endpoint
    • πŸ“– Read: Testing Guide
  4. Code Quality (15 min)

    • Linting: make lint
    • Type checking: mypy bookstore/
    • Security scan: make security-scan
    • πŸ“– Read: Code Examples

Next Steps:

  • Contribute to the project
  • Explore the "DevOps Engineer" path
  • Learn about production deployment
🏭 Production User (1 hour) - Ready to deploy to production?

Goal: Deploy and monitor the API in production

  1. Docker Deployment (20 min)

    • Local production stack: make docker-prod
    • Environment configuration: Edit .env.production
    • SSL setup and domain configuration
    • πŸ“– Read: Docker Guide
  2. Monitoring Setup (25 min)

    • Access Grafana dashboards
    • Configure Prometheus metrics
    • Setup log aggregation with Loki
    • Health check endpoints
    • πŸ“– Read: Production Guide
  3. Security & Backup (15 min)

    • Security headers and rate limiting
    • Database backup procedures: make db-backup
    • SSL certificate management
    • πŸ“– Read: Security Best Practices

Next Steps:

  • Setup CI/CD pipeline
  • Explore Kubernetes deployment
  • Learn about scaling strategies
☸️ DevOps Engineer (3 hours) - Want to master the entire infrastructure?

Goal: Understand and manage the complete DevOps pipeline

  1. Containerization Mastery (45 min)

    • Multi-stage Dockerfile analysis
    • Docker Compose for different environments
    • Container security and optimization
    • Registry management with GitHub Container Registry
    • πŸ“– Read: Docker DevOps Guide
  2. Kubernetes Deployment (60 min)

    • Deploy to Kubernetes: make k8s-deploy
    • Understand manifests in k8s/ directory
    • Auto-scaling configuration
    • Ingress and service mesh
    • πŸ“– Read: Kubernetes Manifests
  3. CI/CD Pipeline (45 min)

    • GitHub Actions workflows in .github/workflows/
    • Automated testing and security scanning
    • Multi-environment deployment
    • Release management
    • πŸ“– Read: CI/CD Setup
  4. Monitoring & Observability (30 min)

    • Prometheus metrics collection
    • Grafana dashboard configuration
    • Log aggregation with Loki and Promtail
    • Alerting and incident response
    • πŸ“– Read: Monitoring Setup

Next Steps:

  • Customize for your infrastructure
  • Add additional monitoring
  • Implement advanced deployment strategies
πŸŽ“ Learning Path (Ongoing) - Want to learn modern Python and DevOps?

Goal: Use this project as a learning resource for modern development practices

  1. Python & FastAPI Fundamentals

  2. Testing Methodologies

  3. DevOps & Infrastructure

  4. Production Readiness

Learning Resources:

🎯 Quick Decision Matrix

Your Goal Time Available Recommended Path
"Just show me it works" 5 minutes πŸš€ Quick Explorer
"I want to use this API" 30 minutes πŸ“± API User
"I want to modify the code" 2 hours πŸ‘¨β€πŸ’» Developer
"I want to deploy this" 1 hour 🏭 Production User
"I want to master DevOps" 3 hours ☸️ DevOps Engineer
"I want to learn from this" Ongoing πŸŽ“ Learning Path

πŸ†˜ Need Help?


πŸ“– API Documentation

πŸ” Authentication Endpoints

POST /auth/register     # Register new user
POST /auth/login        # Login and get JWT token
POST /auth/refresh      # Refresh JWT token

πŸ“š Books Management

GET    /api/v1/books/           # List books (with pagination & search)
POST   /api/v1/books/           # Create book (admin only)
GET    /api/v1/books/{id}       # Get book details
PUT    /api/v1/books/{id}       # Update book (admin only)
DELETE /api/v1/books/{id}       # Delete book (admin only)
GET    /api/v1/books/{id}/reviews # Get book reviews
POST   /api/v1/books/{id}/reviews # Add review (authenticated)

πŸ‘₯ Authors & Users

GET    /api/v1/authors/         # List authors
POST   /api/v1/authors/         # Create author (admin only)
GET    /api/v1/authors/{id}     # Get author details
GET    /api/v1/users/{id}       # Get user profile
PUT    /api/v1/users/{id}       # Update user profile

πŸ“– Reading Lists

GET    /api/v1/reading-lists/           # Get user's reading lists
POST   /api/v1/reading-lists/books/{id} # Add book to reading list
DELETE /api/v1/reading-lists/books/{id} # Remove from reading list

πŸ₯ System Endpoints

GET /health     # Health check with detailed status
GET /metrics    # Prometheus metrics
GET /info       # Application information

πŸ“‹ Interactive Documentation:

🐳 Docker Deployment

Local Development

# Start development environment
cd deployment/docker
docker-compose up -d

# View logs
docker-compose logs -f api

# Stop services
docker-compose down

Production Deployment

# Setup production environment
cp .env.production .env
# Edit .env with your production values

# Deploy to production
cd deployment/docker
docker-compose -f docker-compose.prod.yml up -d

# Check status
docker-compose -f docker-compose.prod.yml ps

Production Stack Includes:

  • BookStore API (3 replicas with auto-restart)
  • PostgreSQL (optimized for production)
  • Redis (with persistence)
  • Nginx (load balancer with SSL)
  • Prometheus (metrics collection)
  • Grafana (monitoring dashboards)
  • Loki (log aggregation)

☸️ Kubernetes Deployment

Quick Deploy

# Deploy to Kubernetes cluster
cd deployment/k8s
./deploy.sh

# Check deployment status
./deploy.sh status

# Update deployment
./deploy.sh update

Manual Kubernetes Setup

cd deployment/k8s/

# Deploy all components
kubectl apply -f namespace.yaml
kubectl apply -f configmap.yaml
kubectl apply -f secrets.yaml
kubectl apply -f postgresql.yaml
kubectl apply -f redis.yaml
kubectl apply -f api-deployment.yaml
kubectl apply -f monitoring.yaml
kubectl apply -f ingress.yaml

# Check status
kubectl get pods -n bookstore-api

Kubernetes Features:

  • Horizontal Pod Autoscaling (3-10 replicas)
  • Persistent storage for database and cache
  • Ingress with SSL termination
  • Service discovery and health checks
  • Resource limits and requests
  • Rolling updates with zero downtime

πŸ”§ Development

Available Commands

make help              # Show all available commands
make install           # Install dependencies
make dev              # Start development server
make test             # Run all tests
make test-unit        # Run unit tests only
make test-integration # Run integration tests
make test-property    # Run property-based tests
make test-performance # Run performance tests
make lint             # Run code linting
make format           # Format code
make security-scan    # Run security scans
make load-test        # Run load tests

Testing Framework

  • Unit Tests: 17/17 βœ… (100% core functionality)
  • Integration Tests: 25/25 βœ… (API endpoints)
  • Property-Based Tests: 8/10 βœ… (Hypothesis testing)
  • Performance Tests: 11/11 βœ… (Load testing with Locust)
  • Security Tests: Automated scanning with multiple tools

Code Quality

  • Black code formatting
  • isort import sorting
  • flake8 linting
  • mypy type checking
  • pytest testing framework
  • coverage reporting (95%+ coverage)

πŸ“Š Monitoring & Observability

Grafana Dashboards

Access monitoring at: https://monitoring.yourdomain.com

Key Metrics Tracked:

  • Request rate and response times
  • Error rates and status codes
  • Database performance and connections
  • System resources (CPU, memory, disk)
  • Cache hit rates and performance
  • Security events and rate limiting

Structured Logging

{
  "timestamp": "2026-01-10T18:13:38.385801Z",
  "level": "INFO",
  "service": "bookstore-api",
  "version": "1.0.0",
  "environment": "production",
  "request_id": "uuid-here",
  "user_id": "user-456",
  "endpoint": "/api/v1/books",
  "method": "GET",
  "status_code": 200,
  "duration_ms": 45.67,
  "message": "API request completed"
}

Health Monitoring

# Check application health
make health

# Run comprehensive health check
./development/scripts/production-health-check.sh

# Continuous monitoring
./development/scripts/production-health-check.sh monitor

πŸ”’ Security Features

Application Security

  • JWT authentication with secure secrets
  • Input validation with Pydantic schemas
  • SQL injection protection via SQLAlchemy ORM
  • XSS protection headers
  • CSRF protection
  • Rate limiting per IP and endpoint

Infrastructure Security

  • HTTPS with TLS 1.2+
  • Security headers (HSTS, CSP, X-Frame-Options)
  • Non-root containers
  • Secrets management
  • Network isolation
  • Regular security scanning

Operational Security

  • Automated backups with encryption
  • Log monitoring and alerting
  • Health checks and incident response
  • Access controls and audit logging
  • Vulnerability scanning in CI/CD

πŸ“ˆ Performance Specifications

  • Response Time: < 200ms (95th percentile)
  • Throughput: 100+ RPS per instance
  • Availability: 99.9% uptime target
  • Scalability: Auto-scaling 3-10 replicas
  • Database: Connection pooling, optimized queries
  • Cache Hit Rate: 80%+ for frequently accessed data

πŸ—‚οΈ Project Structure

bookstore-api/
β”œβ”€β”€ πŸ“ bookstore/              # Main application code
β”‚   β”œβ”€β”€ routers/               # API route handlers
β”‚   β”œβ”€β”€ models.py              # Database models
β”‚   β”œβ”€β”€ schemas.py             # Pydantic schemas
β”‚   β”œβ”€β”€ auth.py                # Authentication logic
β”‚   β”œβ”€β”€ database.py            # Database configuration
β”‚   └── main.py                # FastAPI application
β”œβ”€β”€ πŸ“ tests/                  # Comprehensive test suite
β”‚   β”œβ”€β”€ test_unit_basic.py     # Unit tests
β”‚   β”œβ”€β”€ test_api_integration.py # Integration tests
β”‚   β”œβ”€β”€ test_property_based.py # Property-based tests
β”‚   └── test_performance.py    # Performance tests
β”œβ”€β”€ πŸ“ deployment/             # Deployment configurations
β”‚   β”œβ”€β”€ docker/                # Docker configurations
β”‚   β”œβ”€β”€ k8s/                   # Kubernetes manifests
β”‚   β”œβ”€β”€ config/                # Environment configurations
β”‚   └── monitoring/            # Monitoring dashboards
β”œβ”€β”€ πŸ“ development/            # Development tools
β”‚   β”œβ”€β”€ scripts/               # Utility scripts
β”‚   β”œβ”€β”€ examples/              # Code examples and tutorials
β”‚   └── tools/                 # Development utilities
β”œβ”€β”€ πŸ“ documentation/          # Project documentation
β”‚   β”œβ”€β”€ guides/                # Step-by-step guides
β”‚   β”œβ”€β”€ api/                   # API documentation
β”‚   └── project/               # Project summaries
β”œβ”€β”€ πŸ“ requirements/           # Python dependencies
β”‚   β”œβ”€β”€ base.txt               # Core dependencies
β”‚   β”œβ”€β”€ api.txt                # FastAPI dependencies
β”‚   └── testing.txt            # Testing dependencies
β”œβ”€β”€ πŸ“ alembic/                # Database migrations
β”œβ”€β”€ πŸ“ archive/                # Archived files
β”œβ”€β”€ 🐳 deployment/docker/Dockerfile # Docker configuration
β”œβ”€β”€ βš™οΈ Makefile                # Development commands
β”œβ”€β”€ πŸ“‹ alembic.ini             # Migration configuration
β”œβ”€β”€ πŸ“š README.md               # This file
β”œβ”€β”€ πŸ“š README_RU.md            # Russian documentation
└── πŸ“„ LICENSE                 # MIT License

πŸš€ Deployment Options

Environment Command URL Features
Development make dev http://localhost:8000 Hot reload, debug logging
Docker Local make docker-dev http://localhost:8000 Full stack, easy setup
Production make deploy-prod https://api.yourdomain.com SSL, monitoring, backups
Kubernetes make k8s-deploy https://api.yourdomain.com Auto-scaling, high availability

πŸ“ž Support & Maintenance

Documentation

Troubleshooting

# Check application logs
make logs

# Check health status
make health

# Run diagnostics
./development/scripts/production-health-check.sh

# View system metrics
make metrics

Backup & Recovery

# Create database backup
make db-backup

# Restore from backup
make db-restore BACKUP_FILE=/path/to/backup.sql

# Run backup script
./development/scripts/backup-script.sh

# List available backups
ls -la backups/

πŸš€ Future Roadmap

🎯 Planned Features

πŸ“… Short Term (Next 2-4 weeks)

Core Features

  • Advanced Search - Full-text search with Elasticsearch
  • Book Recommendations - ML-based recommendation engine
  • User Preferences - Customizable user settings and themes
  • Book Categories - Enhanced categorization and tagging
  • Wishlist Management - Advanced wishlist features

API Enhancements

  • GraphQL Support - Alternative to REST API
  • Webhooks - Event-driven notifications
  • Bulk Operations - Batch create/update/delete
  • Advanced Filtering - Complex query capabilities
  • API Versioning - v2 API with enhanced features

Performance & Scalability

  • Database Sharding - Horizontal database scaling
  • CDN Integration - Static asset optimization
  • Advanced Caching - Multi-layer caching strategy
  • Connection Pooling - Optimized database connections
🎯 Medium Term (1-3 months)

Advanced Features

  • Multi-tenancy - Support for multiple bookstore instances
  • Real-time Features - WebSocket support for live updates
  • Mobile API - Optimized endpoints for mobile apps
  • Social Features - User interactions and book sharing
  • Analytics Dashboard - Business intelligence and reporting

Infrastructure

  • Multi-region Deployment - Global availability
  • Advanced Monitoring - APM and distributed tracing
  • Disaster Recovery - Cross-region backup and failover
  • Service Mesh - Istio integration for microservices
  • GitOps - ArgoCD for automated deployments

Security & Compliance

  • OAuth2 Integration - Social login support
  • RBAC System - Role-based access control
  • Audit Logging - Comprehensive audit trails
  • GDPR Compliance - Data privacy and protection
  • SOC 2 Compliance - Security and availability standards
🌟 Long Term (3-6 months)

Microservices Architecture

  • Service Decomposition - Break into microservices
  • Event Sourcing - Event-driven architecture
  • CQRS Pattern - Command Query Responsibility Segregation
  • Saga Pattern - Distributed transaction management
  • API Gateway - Centralized API management

AI & Machine Learning

  • Recommendation Engine - Personalized book suggestions
  • Sentiment Analysis - Review sentiment scoring
  • Price Optimization - Dynamic pricing algorithms
  • Fraud Detection - Automated fraud prevention
  • Content Moderation - AI-powered content filtering

Advanced DevOps

  • Chaos Engineering - Resilience testing
  • Canary Deployments - Gradual rollout strategies
  • Feature Flags - Dynamic feature management
  • Infrastructure as Code - Terraform automation
  • Policy as Code - Open Policy Agent integration

🀝 Community Contributions

How You Can Help:

  • πŸ› Bug Reports - Help us identify and fix issues
  • πŸ’‘ Feature Requests - Suggest new functionality
  • πŸ“ Documentation - Improve guides and examples
  • πŸ§ͺ Testing - Add test cases and scenarios
  • 🎨 UI/UX - Design improvements and user experience
  • πŸ”§ DevOps - Infrastructure and deployment improvements

Contribution Areas:

  • Backend Development - Python, FastAPI, SQLAlchemy
  • Frontend Development - React, Vue.js, or Angular integration
  • Mobile Development - React Native or Flutter apps
  • DevOps & Infrastructure - Kubernetes, Docker, CI/CD
  • Data Science - Analytics, ML models, recommendations
  • Security - Penetration testing, security audits
  • Documentation - Technical writing, tutorials, guides

πŸ“Š Success Metrics

Technical Goals:

  • ⚑ Performance: < 100ms average response time
  • πŸ”„ Availability: 99.99% uptime
  • πŸ“ˆ Scalability: Handle 10,000+ concurrent users
  • πŸ›‘οΈ Security: Zero critical vulnerabilities
  • πŸ§ͺ Quality: 98%+ test coverage

Community Goals:

  • ⭐ GitHub Stars: 1,000+ stars
  • 🀝 Contributors: 50+ active contributors
  • πŸ“š Documentation: Complete guides for all features
  • 🌍 Adoption: Used in 100+ production environments
  • πŸŽ“ Education: Teaching resource in 10+ courses

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite (make test)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

Development Workflow

# Setup development environment
./development/scripts/setup-dev.sh

# Make changes and test
make test

# Check code quality
make lint

# Run security scan
make security-scan

# Submit PR

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸŽ‰ Acknowledgments

  • FastAPI for the amazing web framework
  • SQLAlchemy for the powerful ORM
  • Pydantic for data validation
  • Docker for containerization
  • Kubernetes for orchestration
  • Prometheus & Grafana for monitoring
  • GitHub Actions for CI/CD

πŸš€ From Idea to Production in 2 Days! πŸš€

Built with ❀️ using modern Python and DevOps best practices

⭐ Star this repo β€’ πŸ› Report Bug β€’ πŸ’‘ Request Feature

About

πŸŽ“ Complete Python development course: FastAPI + Docker + Kubernetes + Alembic + DevOps. From basics to production with 95% test coverage.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors