8000 GitHub - devloopcode/fastapi-eco · GitHub
[go: up one dir, main page]

Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

EcomAPI — Production-Ready E-Commerce Backend

A scalable, async-first e-commerce backend built with FastAPI, PostgreSQL, Redis, Celery, and Stripe. Designed to demonstrate production-grade backend engineering: clean architecture, concurrency-safe inventory, transactional order processing, and background task pipelines.


Architecture

app/
├── api/v1/          # Thin HTTP handlers — no business logic
├── services/        # Business logic layer
├── repositories/    # Data access layer (repository pattern)
├── models/          # SQLAlchemy 2.0 ORM models
├── schemas/         # Pydantic v2 request/response schemas
├── core/            # Security (JWT, bcrypt), exception hierarchy
├── db/              # Engine, session factory
├── tasks/           # Celery async workers
├── middleware/       # Rate limiting
├── dependencies/    # FastAPI dependency injection (auth)
└── utils/           # Redis cache helpers, structured logging

Request flow:
Route → Dependency (auth) → Service → Repository → Database

Business logic never leaks into routes. Routes never touch the database directly.


Tech Stack

Layer Technology
API Framework FastAPI 0.115
Database PostgreSQL 16 + SQLAlchemy 2.0 (async)
Migrations Alembic
Cache / Queue Redis 7
Background Jobs Celery 5 + Flower
Payments Stripe Checkout + Webhooks
Auth JWT (access + refresh tokens) + bcrypt
Validation Pydantic v2
Rate Limiting SlowAPI
Logging Structlog (JSON in prod)
Testing Pytest + pytest-asyncio + HTTPX
Containers Docker + Docker Compose

Database Schema

Table Purpose
users Customers and admins with role-based access
refresh_tokens Revocable refresh token store
categories Self-referential product taxonomy
products Inventory with SKU, pricing, stock tracking
product_images Multiple images per product
carts Persistent per-user cart (1:1 with user)
cart_items Line items with live price snapshots
orders Immutable order records with status tracking
order_items Frozen product snapshots (name, SKU, price)
coupons Discount codes (percentage or fixed amount)
payments Stripe transaction records

All primary keys use UUID v4. All timestamps are timezone-aware.


Key Engineering Patterns

Concurrency-Safe Inventory

Stock deduction during checkout uses SELECT FOR UPDATE row-level locking:

product = await self.product_repo.get_for_update(product_id)
# Lock held — no other transaction can modify this row
product.stock_quantity -= cart_item.quantity

This prevents overselling under simultaneous checkout requests.

Transactional Order Creation

The entire checkout flow runs in a single database transaction:

  1. Validate and lock all products
  2. Deduct stock
  3. Create order + items
  4. Apply coupon + increment usage
  5. Clear cart

If any step fails, the transaction rolls back atomically.

Repository Pattern

class ProductRepository(BaseRepository[Product]):
    async def get_for_update(self, product_id) -> Product | None:
        # SELECT ... FOR UPDATE
    async def get_filtered(self, params) -> tuple[Sequence, int]:
        # Dynamic filtering, sorting, pagination

Stripe Webhook Verification

Payment status is never trusted from the frontend. All payment confirmations come through Stripe webhooks with HMAC signature verification:

event = stripe.Webhook.construct_event(payload, sig_header, webhook_secret)

API Endpoints

Authentication

POST /api/v1/auth/register     Register new customer
POST /api/v1/auth/login        Get access + refresh tokens
POST /api/v1/auth/refresh      Rotate refresh token
GET  /api/v1/auth/me           Current user profile

Products (public read, admin write)

GET    /api/v1/products                List with filtering, sorting, pagination
GET    /api/v1/products/{id}           Product detail
POST   /api/v1/products                Create product [admin]
PATCH  /api/v1/products/{id}           Update product [admin]
DELETE /api/v1/products/{id}           Delete product [admin]

Query params: search, category_id, min_price, max_price, in_stock, sort_by, sort_order, page, page_size

Cart (authenticated)

GET    /api/v1/cart                    Get current user's cart
POST   /api/v1/cart/items              Add item (validates stock)
PATCH  /api/v1/cart/items/{id}         Update quantity
DELETE /api/v1/cart/items/{id}         Remove item

Orders (authenticated)

POST /api/v1/orders/checkout           Create order from cart
GET  /api/v1/orders                    Order history
GET  /api/v1/orders/{id}              Order detail

Payments

POST /api/v1/payments/create-checkout  Create Stripe Checkout session
POST /api/v1/payments/webhook          Stripe webhook handler

Coupons

POST /api/v1/coupons                   Create coupon [admin]
POST /api/v1/coupons/apply             Validate and preview discount

Admin

GET   /api/v1/admin/orders                     All orders with filters
PATCH /api/v1/admin/orders/{id}/status         Update order status
GET   /api/v1/admin/analytics/overview         Revenue and key metrics

Setup

Prerequisites

  • Docker & Docker Compose
  • (Optional) Python 3.12 + PostgreSQL + Redis for local dev

Quick Start with Docker

# Clone and configure
git clone <repo>
cd ecom
cp .env.example .env
# Edit .env with your STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET

# Start all services
docker compose up --build

# Run migrations (first time)
docker compose exec api alembic upgrade head

# API available at http://localhost:8000
# Flower (Celery monitor) at http://localhost:5555
# Docs at http://localhost:8000/docs (DEBUG=true only)

Local Development

python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt

cp .env.example .env
# Configure DATABASE_URL, REDIS_URL, STRIPE keys

# Run migrations
alembic upgrade head

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

# Start Celery worker (separate terminal)
celery -A app.tasks.celery_app worker --loglevel=info

Migrations

# Create a new migration after model changes
alembic revision --autogenerate -m "describe your change"

# Apply all pending migrations
alembic upgrade head

# Rollback one migration
alembic downgrade -1

# View migration history
alembic history

Testing

# Install test dependencies (included in requirements.txt)
pip install -r requirements.txt

# Run all tests (uses in-memory SQLite — no external services needed)
pytest

# With verbose output and coverage
pytest -v --tb=short

# Run specific test module
pytest app/tests/test_auth.py -v

Tests use an in-memory SQLite database and HTTPX async test client. No real Stripe or Redis connections are required to run the test suite.


Environment Variables

Variable Description Default
DATABASE_URL PostgreSQL connection (asyncpg) Required
REDIS_URL Redis connection redis://localhost:6379/0
SECRET_KEY JWT signing secret Required (change in prod)
ACCESS_TOKEN_EXPIRE_MINUTES Access token TTL 30
REFRESH_TOKEN_EXPIRE_DAYS Refresh token TTL 7
STRIPE_SECRET_KEY Stripe secret key Required for payments
STRIPE_WEBHOOK_SECRET Stripe webhook signing secret Required for webhooks
STRIPE_SUCCESS_URL Redirect after successful payment http://localhost:3000/checkout/success
STRIPE_CANCEL_URL Redirect after cancelled payment http://localhost:3000/checkout/cancel
CELERY_BROKER_URL Celery broker redis://localhost:6379/1
CELERY_RESULT_BACKEND Celery results redis://localhost:6379/2
DEBUG Enable debug mode + Swagger UI false

Stripe Integration

  1. Create a Stripe account and get your API keys from the Dashboard
  2. Set STRIPE_SECRET_KEY in your .env
  3. For webhooks, install the Stripe CLI and forward events locally:
    stripe listen --forward-to localhost:8000/api/v1/payments/webhook
  4. Copy the webhook signing secret to STRIPE_WEBHOOK_SECRET

Payment flow:

  1. Customer completes checkout → POST /api/v1/orders/checkout → order created (status: pending)
  2. Frontend calls POST /api/v1/payments/create-checkout → receives Stripe Checkout URL
  3. Customer completes payment on Stripe hosted page
  4. Stripe calls POST /api/v1/payments/webhook → order status updated to paid
  5. Background task fires → sends confirmation email

Background Workers

Celery workers process two queues:

  • email — order confirmations, shipment notifications
  • orders — post-payment processing

Tasks use bind=True with max_retries=3 and exponential backoff.

Monitor tasks via Flower at http://localhost:5555.


About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0