DEV Community

Cover image for Build a Production-Ready FastAPI E-Commerce API with RapidKit (Step-by-Step)
RapidKit
RapidKit

Posted on • Edited on

Build a Production-Ready FastAPI E-Commerce API with RapidKit (Step-by-Step)

Let's Build Something Real

Not a hello-world demo. A real FastAPI project you can deploy.

We'll build a Product Management API with:
• Authentication
• PostgreSQL database
• Redis caching
• Email notifications
• Production deployment

Let's begin.


Before We Begin: Three Ways to Create Projects

🎯 Approach 1: Workspace-First (Recommended)

npx rapidkit my-workspace
cd my-workspace
rapidkit create project fastapi.standard product-api
Enter fullscreen mode Exit fullscreen mode

Best for: Teams, multiple services, production


🚀 Approach 2: Direct Project Creation

npx rapidkit create project fastapi.standard product-api
cd product-api
npx rapidkit init
Enter fullscreen mode Exit fullscreen mode

Best for: Single project, learning, prototyping


🎨 Approach 3: VS Code Extension

  1. Install extension
  2. Ctrl+Shift+P → "RapidKit: Create Project"
  3. Choose FastAPI
  4. Enter name

Best for: Visual learners, GUI preference


We'll use Approach 1 (workspace) for this tutorial.


Prerequisites

You need:
• Node.js 20+
• Python 3.10+
• Docker (for PostgreSQL/Redis)

That's it. RapidKit handles the rest.


Step 1: Create Workspace and Project

# Create workspace
npx rapidkit my-workspace
cd my-workspace

# Create FastAPI project
rapidkit create project fastapi.standard product-api
cd product-api
Enter fullscreen mode Exit fullscreen mode

What you get:
• Clean src/ architecture
• Health check endpoint (/health)
• Testing setup (pytest)
• Docker configs
• CI/CD templates


Step 2: Initialize Project

rapidkit init
Enter fullscreen mode Exit fullscreen mode

This installs:
• Poetry (if needed)
• All dependencies
• Development tools

Then start the server:

rapidkit dev
Enter fullscreen mode Exit fullscreen mode

Output:

INFO: Uvicorn running on http://127.0.0.1:8000
Enter fullscreen mode Exit fullscreen mode

Visit: http://localhost:8000/docs

You see Swagger UI with /health endpoint.


Step 3: Add Configuration Module

rapidkit add module settings
Enter fullscreen mode Exit fullscreen mode

Settings module provides:
• Multi-source config (.env, env vars, CLI)
• Type-safe with Pydantic
• Environment-specific overrides

Create .env:

APP_NAME=Product API
APP_ENV=development
LOG_LEVEL=INFO
Enter fullscreen mode Exit fullscreen mode

Health check now shows:

{
  "status": "healthy",
  "modules": {
    "settings": "ok"
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Add Database (PostgreSQL)

rapidkit add module db_postgres
Enter fullscreen mode Exit fullscreen mode

Update .env:

POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=myuser
POSTGRES_PASSWORD=mypass
POSTGRES_DB=productdb
Enter fullscreen mode Exit fullscreen mode

Start PostgreSQL:

docker-compose up -d postgres
Enter fullscreen mode Exit fullscreen mode

The module provides:
• Async SQLAlchemy setup
• Connection pooling
• Health checks
• Alembic migrations

Test connection:

curl http://localhost:8000/health
Enter fullscreen mode Exit fullscreen mode
{
  "status": "healthy",
  "modules": {
    "db_postgres": "ok",
    "settings": "ok"
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Create Product Model

src/app/models/product.py:

from sqlalchemy import Column, Integer, String, Float, Boolean
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Product(Base):
    __tablename__ = "products"

    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    description = Column(String(500))
    price = Column(Float, nullable=False)
    stock = Column(Integer, default=0)
    active = Column(Boolean, default=True)
Enter fullscreen mode Exit fullscreen mode

Run migration:

rapidkit db migrate "Create products table"
rapidkit db upgrade
Enter fullscreen mode Exit fullscreen mode

Step 6: Add Redis Caching

rapidkit add module redis
Enter fullscreen mode Exit fullscreen mode

Update .env:

REDIS_URL=redis://localhost:6379
Enter fullscreen mode Exit fullscreen mode

Start Redis:

docker-compose up -d redis
Enter fullscreen mode Exit fullscreen mode

Use for caching:

from app.modules.redis import get_redis

async def get_product_cached(product_id: int):
    redis = await get_redis()
    cached = await redis.get(f"product:{product_id}")
    if cached:
        return json.loads(cached)

    # Fetch from DB
    product = await fetch_from_db(product_id)

    # Cache for 5 minutes
    await redis.setex(
        f"product:{product_id}",
        300,
        json.dumps(product)
    )
    return product
Enter fullscreen mode Exit fullscreen mode

Step 7: Add Authentication

rapidkit add module auth_core
Enter fullscreen mode Exit fullscreen mode

Features:
• PBKDF2 password hashing
• JWT token generation
• Token validation middleware

Create user:

from app.modules.auth_core import hash_password, create_token

# Hash password
hashed = hash_password("secure123")

# Store in DB
user = User(email="user@example.com", password=hashed)
db.add(user)
await db.commit()

# Generate token
token = create_token({"user_id": user.id})
Enter fullscreen mode Exit fullscreen mode

Protected endpoint:

from app.modules.auth_core import require_auth

@app.post("/products")
@require_auth
async def create_product(
    product: ProductCreate,
    current_user: User = Depends(get_current_user)
):
    # Only authenticated users can create
    new_product = Product(**product.dict())
    db.add(new_product)
    await db.commit()
    return new_product
Enter fullscreen mode Exit fullscreen mode

Step 8: Add Email Module

rapidkit add module email
Enter fullscreen mode Exit fullscreen mode

Update .env:

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
SMTP_FROM=noreply@productapi.com
Enter fullscreen mode Exit fullscreen mode

Send email:

from app.modules.email import send_email

await send_email(
    to="customer@example.com",
    subject="Product Added to Cart",
    body="Your product is ready!",
    html=True
)
Enter fullscreen mode Exit fullscreen mode

Step 9: Add Security Headers & CORS

rapidkit add module cors
rapidkit add module security_headers
Enter fullscreen mode Exit fullscreen mode

Update .env:

CORS_ORIGINS=http://localhost:3000,https://yourapp.com
Enter fullscreen mode Exit fullscreen mode

Your API now has:
• CSP, HSTS, X-Frame-Options
• Origin whitelisting
• Credential support
• Preflight handling


Step 10: Add Logging

rapidkit add module logging
Enter fullscreen mode Exit fullscreen mode

Features:
• Structured JSON logs
• Correlation IDs
• Multi-sink (console, file, HTTP)

Logs look like:

{
  "timestamp": "2026-02-14T10:30:00Z",
  "level": "INFO",
  "message": "Product created",
  "correlation_id": "abc123",
  "user_id": 42,
  "product_id": 123
}
Enter fullscreen mode Exit fullscreen mode

Step 11: Run Tests

rapidkit test
Enter fullscreen mode Exit fullscreen mode

Output:

===== test session starts =====
collected 24 items

tests/test_products.py ........
tests/test_auth.py ....
tests/test_cache.py ....
tests/test_health.py ....

===== 24 passed in 3.2s =====
Enter fullscreen mode Exit fullscreen mode

Every module includes tests.


Step 12: Deploy

Build Docker image:

docker build -t product-api .
Enter fullscreen mode Exit fullscreen mode

Run container:

docker run -p 8000:8000 \
  -e POSTGRES_HOST=db.example.com \
  -e REDIS_URL=redis://cache.example.com \
  product-api
Enter fullscreen mode Exit fullscreen mode

Or use GitHub Actions (already configured in .github/workflows/).


Project Structure (Final)

product-api/
├── src/
│   ├── app/
│   │   ├── main.py
│   │   ├── models/
│   │   │   └── product.py
│   │   ├── routes/
│   │   │   └── products.py
│   │   └── modules/
│   │       ├── settings/
│   │       ├── db_postgres/
│   │       ├── redis/
│   │       ├── auth_core/
│   │       ├── email/
│   │       ├── cors/
│   │       ├── security_headers/
│   │       └── logging/
│   └── tests/
├── docker-compose.yml
├── Dockerfile
├── .env
└── pyproject.toml
Enter fullscreen mode Exit fullscreen mode

What You Built

✅ Product CRUD API

✅ PostgreSQL database

✅ Redis caching

✅ JWT authentication

✅ Email notifications

✅ CORS protection

✅ Security headers

✅ Structured logging

✅ Docker deployment

✅ CI/CD ready

✅ Tests passing

Time spent: ~2 hours

Lines written: ~200

Lines generated: ~3,000


Key Takeaways

1. Modules are composable

rapidkit add module X
rapidkit add module Y
# They work together automatically
Enter fullscreen mode Exit fullscreen mode

2. Everything is configurable
All settings via .env — no code changes needed.

3. Health checks included
Every module reports health at /health.

4. Tests included
Every module brings its own tests.

5. Standard FastAPI code
No lock-in. Modify anything. It's your code.


🧩 Explore More Modules

This tutorial used 8 modules, but RapidKit offers 27 free modules:

Authentication & Security (9):
auth_core, api_keys, oauth, passwordless, session, rbac, cors, security_headers, rate_limiting

Database & Caching (4):
db_postgres, db_mongodb, db_mysql, redis

Payments & E-commerce (3):
stripe_payment, paypal_payment, cart

Communication (2):
email, email_templates

Business (3):
storage (S3/MinIO), deployment, observability_core

Essentials (4):
settings, logging, celery, users_core

AI (1):
ai_recommender

Don't know which module?
🤖 Use AI:

npx rapidkit modules recommend "I need user authentication and email"
Enter fullscreen mode Exit fullscreen mode

Read full AI guide →


🚀 Clone Example Projects

RapidKit VS Code Extension connects to real production-style workspaces:

  1. Quickstart Product API (quickstart-workspace/product-api)
  2. E-Commerce API (quickstart-workspace/ecommerce-api)
  3. AI Agent Workspace (my-ai-workspace)
  4. SaaS Starter Workspace (saas-starter-workspace)

Clone from VS Code:

  1. Open Welcome Panel → Example Workspaces
  2. Select workspace
  3. Run rapidkit init && rapidkit dev

Clone from terminal:

git clone https://github.com/getrapidkit/rapidkit-examples
cd rapidkit-examples/quickstart-workspace/ecommerce-api
source .rapidkit/activate
rapidkit init
rapidkit dev
Enter fullscreen mode Exit fullscreen mode

E-Commerce Flow (Visual Summary)

If you run quickstart-workspace/ecommerce-api, this is the core payment lifecycle:

stateDiagram-v2
  [*] --> Cart
  Cart --> Confirmed: POST /checkout
  Confirmed --> Paid: POST /payments/intents/{id}/confirm
  Confirmed --> Paid: webhook payment.succeeded
  Confirmed --> PaymentFailed: webhook payment.failed
Enter fullscreen mode Exit fullscreen mode

And the request sequence:

sequenceDiagram
  participant C as Client
  participant A as ecommerce-api
  participant P as Payment Provider (Mock)

  C->>A: Add items to cart
  C->>A: POST /checkout
  A-->>C: order.status=confirmed

  C->>A: POST /payments/intents
  C->>A: POST /payments/intents/{id}/confirm
  A-->>C: order.status=paid

  P->>A: POST /webhooks/payments
  A-->>P: 202 accepted
Enter fullscreen mode Exit fullscreen mode

What's Next?

Next: Build a NestJS microservice and see how it compares to FastAPI.

After that: New AI tracks (support triage, provider failover, cost control).


Learn More


You just built a production API.

Now ship it.


Tags:

rapidkit #fastapi #tutorial #python #backend #api #postgresql #redis #docker #beginners

Top comments (0)