Back to Examples |

E-Commerce with Offline Mode

REST API + Cache

A full e-commerce experience with offline support powered by Flaxon REST APIs and client-side caching.

Products

Synced

Cart

Your cart is empty.

Total $0.00

Flaxon REST API

from flaxon import Flaxon
from flaxon.validation import Schema, fields

app = Flaxon("ecommerce-backend")

products = [
    {"id": 1, "name": "Laptop", "price": 999.99, "stock": 10},
    {"id": 2, "name": "Mouse", "price": 29.99, "stock": 25},
]

class CartItem(Schema):
    product_id = fields.Integer(required=True)
    quantity = fields.Integer(required=True, minimum=1)

@app.get("/api/products")
async def get_products():
    return {"products": products}

@app.post("/api/cart")
async def add_to_cart(data: CartItem):
    product = next((p for p in products if p["id"] == data.product_id), None)
    if not product:
        return {"error": "Product not found"}, 404
    if product["stock"] < data.quantity:
        return {"error": "Insufficient stock"}, 400
    return {"success": True, "item": data.to_dict()}

@app.post("/api/checkout")
async def checkout(request):
    data = await request.json()
    # Process order
    return {"order_id": "ORD-123", "total": data.get("total", 0)}

Offline Sync Strategy

// Client-side offline storage
const CART_KEY = 'flaxon_cart';

function saveCartToLocal(cart) {
    localStorage.setItem(CART_KEY, JSON.stringify(cart));
}

function loadCartFromLocal() {
    const data = localStorage.getItem(CART_KEY);
    return data ? JSON.parse(data) : [];
}

// Sync when online
async function syncCart() {
    const cart = loadCartFromLocal();
    if (cart.length === 0) return;

    for (const item of cart) {
        try {
            const res = await fetch('/api/cart', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(item)
            });
            if (res.ok) {
                // Remove synced items
                const updated = cart.filter(i => i.id !== item.id);
                saveCartToLocal(updated);
            }
        } catch (e) {
            // Offline - keep in local storage
            console.log('Offline, waiting for sync');
        }
    }
}