JavaScript · API · Intermediate
Shopping Cart
Add, update, and remove cart items using authenticated fetch requests.
Quick topic start and explanations before exercises (exercises below):
Adding, updating, and removing cart items
#Cart API reference
#Exercises:
View the cart
#Authenticate and send GET to `/api/cart/`. Print the number of items in the cart and `total_price`.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. get token
// 2. GET /api/cart/ and print items count and total_price
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = { 'Authorization': `Token ${token}` };
const cart = await fetch(`${BASE_URL}/api/cart/`, { headers }).then(r => r.json());
console.log(cart.items.length);
console.log(cart.total_price);
}
main();
Add a product to the cart
#Find any product from `/api/products/` and add it to the cart with quantity 1. Print the cart item `id` from the response.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. get token
// 2. get a product slug from /api/products/
// 3. POST to /api/cart/items/ and print the item id
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const slug = await fetch(`${BASE_URL}/api/products/`).then(r => r.json())
.then(d => d.results[0].slug);
const item = await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST',
headers,
body: JSON.stringify({ product_slug: slug, quantity: 1 }),
}).then(r => r.json());
console.log(item.id);
}
main();
Update item quantity
#Add a product to the cart, then update its quantity to 3 with PATCH. Print the updated quantity from the response.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. authenticate
// 2. add a product
// 3. PATCH quantity to 3
// 4. print updated quantity
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const slug = await fetch(`${BASE_URL}/api/products/`).then(r => r.json())
.then(d => d.results[0].slug);
const item = await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST',
headers,
body: JSON.stringify({ product_slug: slug, quantity: 1 }),
}).then(r => r.json());
const updated = await fetch(`${BASE_URL}/api/cart/items/${item.id}/`, {
method: 'PATCH',
headers,
body: JSON.stringify({ quantity: 3 }),
}).then(r => r.json());
console.log(updated.quantity);
}
main();
Remove one item
#Add a product to the cart, then delete it with DELETE `/api/cart/items/{id}/`. Verify the cart is empty by fetching it again and printing the item count.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// add product, delete it, verify cart is empty
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const slug = await fetch(`${BASE_URL}/api/products/`).then(r => r.json())
.then(d => d.results[0].slug);
const item = await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: slug, quantity: 1 }),
}).then(r => r.json());
await fetch(`${BASE_URL}/api/cart/items/${item.id}/`, { method: 'DELETE', headers });
const cart = await fetch(`${BASE_URL}/api/cart/`, { headers }).then(r => r.json());
console.log(cart.items.length); // 0
}
main();
Add two products then clear the cart
#Add two different products to the cart. Print `total_price`. Then clear the entire cart with DELETE `/api/cart/items/` and verify it's empty.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// add 2 products, print total_price, clear cart, verify empty
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const products = await fetch(`${BASE_URL}/api/products/`).then(r => r.json())
.then(d => d.results);
for (const p of products.slice(0, 2)) {
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: p.slug, quantity: 1 }),
});
}
const cart = await fetch(`${BASE_URL}/api/cart/`, { headers }).then(r => r.json());
console.log('Total:', cart.total_price);
await fetch(`${BASE_URL}/api/cart/items/`, { method: 'DELETE', headers });
const empty = await fetch(`${BASE_URL}/api/cart/`, { headers }).then(r => r.json());
console.log('After clear:', empty.items.length);
}
main();