API routes are located in app/api/ and act as a proxy layer between the frontend and WooCommerce. They handle authentication, request transformation, and error handling.
Products API
Endpoint: /api/products
GET – List Products
// GET /api/products
// Query params: include (comma-separated IDs)
const response = await fetch("/api/products?include=1,2,3");
const products = await response.json(); // Get products from response
// Response: Array of product objects
[
{
"id": 1,
"name": "Product Name",
"price": "29.99",
"regular_price": "39.99",
"sale_price": "29.99",
"images": [...],
"categories": [...]
}
]Cart API
Endpoint: /api/cart
GET – Fetch Cart
const response = await fetch("/api/cart"); // Get cart from response
const cartData = await response.json();
// Returns: { items: [], totals: {} }POST – Add to Cart
const response = await fetch("/api/cart", { // Add to cart with quantity 2 to the product with the given id
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: 123, quantity: 2 })
});PUT – Update Cart
const response = await fetch("/api/cart", { // Update cart with quantity 3 to the item with the given key
method: "PUT",
body: JSON.stringify({ items: [{ key: "item-key", quantity: 3 }] })
});DELETE – Remove from Cart
const response = await fetch("/api/cart", { // Remove the item with the given key from the cart
method: "DELETE",
body: JSON.stringify({ items: [{ key: "item-key" }] })
});Checkout API
Endpoint: /api/checkout
GET – Get Checkout Data
const response = await fetch("/api/checkout"); // Get checkout from response
const data = await response.json();
// Returns: { shipping_rates: [], payment_methods: [] }PUT – Update Checkout
const response = await fetch("/api/checkout", { // Update checkout with the given billing address and shipping address
method: "PUT",
body: JSON.stringify({
billing_address: { first_name: "John", email: "[email protected]", ... },
shipping_address: { first_name: "John", ... }
})
});POST – Process Order
const response = await fetch("/api/checkout", { // Process order with the given payment method and payment data
method: "POST",
body: JSON.stringify({ payment_method: "stripe", payment_data: {} })
});
const orderData = await response.json();
// Returns: { id: 12345, status: "processing" }Authentication API
Endpoint: /api/login
POST – User Login
const response = await fetch("/api/login", { // Login with the given username and password
method: "POST",
body: JSON.stringify({ username: "[email protected]", password: "pass" })
});
const data = await response.json();
// Returns: { success: true, data: { token, email, username } }Admin API Routes
Products Management
| Method | Endpoint | Description |
|---|---|---|
|
|
List products with pagination |
|
|
Create new product |
|
|
Get product by ID |
|
|
Update product |
|
|
Delete product |
List Products
const response = await fetch("/api/admin/products?page=1&per_page=50"); // Get products with pagination
const { products, totalPages } = await response.json(); // Get products and total pages from responseCreate/Update/Delete Product
// Create
await fetch("/api/admin/products", {
method: "POST",
body: JSON.stringify({ name: "Product", regular_price: "29.99" })
});
// Update
await fetch(`/api/admin/products/${id}`, {
method: "PUT",
body: JSON.stringify({ name: "Updated" })
});
// Delete
await fetch(`/api/admin/products/${id}`, { method: "DELETE" });Categories Management
Similar endpoints available for categories:
GET /api/admin/categories– List categoriesPOST /api/admin/categories– Create categoryGET /api/admin/categories/[id]– Get categoryPUT /api/admin/categories/[id]– Update categoryDELETE /api/admin/categories/[id]– Delete category
Tags Management
Similar endpoints available for tags:
GET /api/admin/tags– List tagsPOST /api/admin/tags– Create tagGET /api/admin/tags/[id]– Get tagPUT /api/admin/tags/[id]– Update tagDELETE /api/admin/tags/[id]– Delete tag
Error Handling
All API endpoints may return error responses:
// Error response
{
"error": "Error message here"
}
// Status codes:
// 200 - Success
// 201 - Created
// 400 - Bad Request
// 401 - Unauthorized
// 404 - Not Found
// 500 - Internal Server Errortry {
const response = await fetch("/api/products");
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || "Request failed");
}
const data = await response.json();
// Use data
} catch (error) {
console.error("API Error:", error.message);
// Handle error
}Authentication
Most admin endpoints require authentication via cookies:
// Token is automatically sent with cookies
// Set token after login
document.cookie = "token=jwt_token_here; path=/";
// Include in requests (automatic with cookies)
const response = await fetch("/api/admin/products", {
credentials: "include" // Important for cookies
});Rate Limiting
Note: WooCommerce APIs may have rate limits. Implement caching and request batching when possible to avoid hitting limits.
Best Practices
- Handle Errors: Always wrap API calls in try-catch blocks
- Check Response Status: Verify response.ok before using data
- Use Credentials: Include
credentials: "include"for authenticated requests - Cache Responses: Cache product and category data when appropriate
- Batch Requests: Combine multiple requests when possible
Next Steps: Learn about State Management and Cart Management to use these APIs effectively.