JavaScript · API · Intermediate

Shopping Cart

5 tasks

Add, update, and remove cart items using authenticated fetch requests.

Cart API overview

#
The cart API manages the shopping cart tied to your account. All cart endpoints require the `Authorization` header. Two groups of endpoints: Cart overview: ``` GET /api/cart/ View cart (total price, item list) ``` Cart items: ``` POST /api/cart/items/ Add a product PATCH /api/cart/items/{id}/ Update quantity of one item DELETE /api/cart/items/{id}/ Remove one item DELETE /api/cart/items/ Clear all items ``` GET /api/cart/ response shape: ```javascript { items: [ { id: 42, // cart item id (not product id) product: { id: 7, name: "Oak Chair", price: "149.99", ... }, quantity: 1, products_price: "149.99" } ], total_price: "149.99", total_quantity: 1 } ``` Each item has its own `id` — you need this to update or delete it. To add a product you need its `slug`, not its `id`.

Adding, updating, and removing cart items

#
Complete cart workflow with fetch: ```javascript const BASE_URL = 'https://apilearn.tukas.dev'; async function getToken() { 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()); return token; } async function main() { const token = await getToken(); const headers = { 'Authorization': `Token ${token}`, 'Content-Type': 'application/json', }; // View the cart const cart = await fetch(`${BASE_URL}/api/cart/`, { headers }).then(r => r.json()); console.log('Items in cart:', cart.items.length); // Get a product slug const product = await fetch(`${BASE_URL}/api/products/1/`).then(r => r.json()); const slug = product.slug; // Add to cart const item = await fetch(`${BASE_URL}/api/cart/items/`, { method: 'POST', headers, body: JSON.stringify({ product_slug: slug, quantity: 2 }), }).then(r => r.json()); console.log('Cart item id:', item.id); // Update quantity const updated = await fetch(`${BASE_URL}/api/cart/items/${item.id}/`, { method: 'PATCH', headers, body: JSON.stringify({ quantity: 5 }), }).then(r => r.json()); console.log('New quantity:', updated.quantity); // Delete one item await fetch(`${BASE_URL}/api/cart/items/${item.id}/`, { method: 'DELETE', headers, }); // Clear all items 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('Items after clear:', empty.items.length); // 0 } main(); ```

Cart API reference

#
**Endpoints (all require Authorization)** ``` GET /api/cart/ View cart POST /api/cart/items/ Add item body: { product_slug: string, quantity: number } returns: 201 + cart item object PATCH /api/cart/items/{id}/ Update quantity body: { quantity: number } returns: 200 + updated item DELETE /api/cart/items/{id}/ Remove one item → 204 DELETE /api/cart/items/ Clear all items → 204 ``` **Cart response shape** ```javascript { items: [...], total_price: "149.99", total_quantity: 1 } ``` **Cart item object** ```javascript { id: 42, product: {...}, quantity: 2, products_price: "299.98" } ``` **Key distinction** ``` product.slug — used when adding to cart (POST body) item.id — used when updating/deleting (URL param) ``` **DELETE returns 204 — no body** ```javascript // Don't call .json() on a 204 response await fetch(url, { method: 'DELETE', headers }); // Just check response.ok if needed ```
01

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();
02

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();
03

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();
04

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();
05

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();