← Back to Home

Storefront UI

Adding a User Interface

You've built an API that stores products. Now let's create a simple HTML + JavaScript UI so people can browse and "buy" items.

Set up the UI

In your store-api folder, create a file index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Store</title>
  <style>
    body { font-family: Arial; max-width: 800px; margin: 40px auto; padding: 20px; }
    .product { border: 1px solid #ccc; padding: 15px; margin: 10px 0; border-radius: 8px; }
    button { background: #ff6b9d; color: white; border: none; padding: 8px 16px; 
             border-radius: 5px; cursor: pointer; }
    button:hover { background: #c06bff; }
    input { padding: 8px; width: 200px; margin-right: 10px; border: 1px solid #ccc; border-radius: 4px; }
  </style>
</head>
<body>
  <h1>🛒 My Store</h1>
  <input id="search" type="text" placeholder="Search products...">
  <button onclick="loadProducts()">Search</button>
  <div id="products"></div>

  <script>
    async function loadProducts() {
      const search = document.getElementById('search').value;
      const res = await fetch('http://127.0.0.1:8000/products');
      const products = await res.json();
      
      const filtered = products.filter(p => 
        p.name.toLowerCase().includes(search.toLowerCase())
      );
      
      const container = document.getElementById('products');
      container.innerHTML = filtered.map(p => `
        <div class="product">
          <h3>${p.name}</h3>
          <p>Price: $${p.price}</p>
          <button onclick="buyProduct('${p.name}')">Buy</button>
        </div>
      `).join('');
    }

    function buyProduct(name) {
      alert(\`You bought: \${name}!\`);
    }

    loadProducts();
  </script>
</body>
</html>

Enable CORS

Your browser won't let the HTML page talk to the API without CORS. Update main.py:

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from tinydb import TinyDB, Query
from pydantic import BaseModel

app = FastAPI()

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# ... rest of your code

Restart the server with uv run uvicorn main:app --reload.

Try It Out

Open index.html in your browser. You'll see all your products! Use the search box to filter, and click "Buy" to simulate a purchase.

Congratulations!

You've built a complete stack—Python backend API with a database, and a simple frontend UI. From here, you can add features like user accounts, real payment processing, image uploads, and more.

Keep coding and building amazing things! 🎉

← Previous