Building a Website with API
Complete guide to building a custom website using the ShadowGrow API as your backend.
Frequently Asked Questions
Can I build a complete website using only the API?
Yes, you can build a complete website using the API as your backend. Your website (frontend) communicates with the API (backend) which handles data storage in the database. You can build product pages, shopping cart, checkout, user authentication, order management, and all e-commerce features using the API.
How do I display products on my website using the API?
Fetch products using GET /api/v1/user/products endpoint with your API key, parse the response data, and render products in your UI. You can filter by category, search term, status, and paginate results. Cache product data to reduce API calls and improve performance.
How do I implement shopping cart and checkout with the API?
Add items to cart using POST /api/v1/user/cart endpoint, manage cart state in your frontend, create orders using POST /api/v1/user/orders endpoint with cart items and customer information, handle payment through the API, and display order confirmation. Use user authentication tokens for cart operations.
How do I implement user authentication on my website using the API?
Use POST /api/v1/user/auth/login endpoint for user login, store the returned JWT token securely (localStorage or httpOnly cookies), use the token in Authorization header for authenticated requests, implement token refresh for long-lived sessions, and handle token expiration gracefully with automatic logout.
What security considerations should I follow when building a website with the API?
Never expose API keys in client-side code, use server-side API routes for sensitive operations, implement CORS properly, use HTTPS for all API communications, validate and sanitize all user inputs, implement rate limiting on your side, and use secure token storage methods.
Architecture Overview
Frontend + API Architecture
Build your website as a frontend application that communicates with the ShadowGrow API:
Building Product Pages
Product Listing Page
Example React component:
import { useState, useEffect } from 'react';
function ProductsPage() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchProducts() {
try {
const response = await fetch(
'https://your-domain.com/api/v1/user/products',
{
headers: {
'Authorization': `Bearer ${process.env.REACT_APP_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
const data = await response.json();
setProducts(data.data);
} catch (error) {
console.error('Error fetching products:', error);
} finally {
setLoading(false);
}
}
fetchProducts();
}, []);
if (loading) return <div>Loading...</div>;
return (
<div className="products-grid">
{products.map(product => (
<div key={product.id} className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>{`$${product.price}`}</p>
<button>Add to Cart</button>
</div>
))}
</div>
);
}Shopping Cart & Checkout
Cart Management
// Add to cart
async function addToCart(productId, quantity) {
const response = await fetch(
'https://your-domain.com/api/v1/user/cart',
{
method: 'POST',
headers: {
'Authorization': `Bearer ${userToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
product_id: productId,
quantity: quantity
})
}
</>
);
return await response.json();
}
// Create order
async function checkout(cartItems, shippingInfo) {
const response = await fetch(
'https://your-domain.com/api/v1/user/orders',
{
method: 'POST',
headers: {
'Authorization': `Bearer ${userToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
items: cartItems,
shipping_address: shippingInfo,
payment_method: 'wallet'
})
}
</>
);
return await response.json();
}User Authentication
Login Implementation
async function login(email, password) {
const response = await fetch(
'https://your-domain.com/api/v1/user/auth/login',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
}
</>
);
const data = await response.json();
if (data.status === 'success') {
// Store token securely
localStorage.setItem('authToken', data.data.token);
localStorage.setItem('user', JSON.stringify(data.data.user));
return data.data;
} else {
throw new Error(data.message);
}
}
// Use token for authenticated requests
function getAuthHeaders() {
const token = localStorage.getItem('authToken');
return {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
}Complete Example: Next.js Website
Project Structure
my-website/ ├── lib/ │ └── api.js # API client ├── pages/ │ ├── index.js # Home page │ ├── products.js # Products listing │ ├── product/[id].js # Product detail │ ├── cart.js # Shopping cart │ ├── checkout.js # Checkout page │ └── account.js # User account ├── components/ │ ├── ProductCard.js │ ├── Cart.js │ └── Header.js └── .env.local # API configuration
API Client Setup
// lib/api.js
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL;
const API_KEY = process.env.NEXT_PUBLIC_API_KEY;
export async function apiRequest(endpoint, options = {}) {
const token = typeof window !== 'undefined'
? localStorage.getItem('authToken')
: null;
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options,
headers: {
'Authorization': token
? `Bearer ${token}`
: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
...options.headers
},
body: options.body ? JSON.stringify(options.body) : undefined
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
return await response.json();
}
// API methods
export const api = {
products: {
list: (params) => apiRequest('/user/products', {
method: 'GET'
}),
get: (id) => apiRequest(`/user/products/${id}`, {
method: 'GET'
})
},
orders: {
create: (data) => apiRequest('/user/orders', {
method: 'POST',
body: data
})
},
auth: {
login: (credentials) => apiRequest('/user/auth/login', {
method: 'POST',
body: credentials
})
}
};Deployment Considerations
Security
- Never expose API keys in client-side code
- Use server-side API routes for sensitive operations
- Implement CORS properly
- Use HTTPS for all API communications
- Validate and sanitize all user inputs
Performance
- Implement caching for product data
- Use pagination for large datasets
- Optimize images and assets
- Implement lazy loading
- Use CDN for static assets