JavaScript · API · Beginner

Working with Categories

5 tasks

Fetch and explore product categories, then use them to filter the product list.

The categories endpoint

#
/api/categories/ returns the same paginated shape as /api/products/: ```javascript const BASE_URL = 'https://apilearn.tukas.dev'; async function main() { const response = await fetch(`${BASE_URL}/api/categories/`); const data = await response.json(); // data is {count, next, previous, results} console.log(data.count); // 13 console.log(data.results.length); // 13 (all fit on one page) console.log(data.results[0]); // {id: 6, name: "All Products", slug: "all"} } main(); ``` Each category object: ```javascript { id: 7, name: "Kitchen", slug: "kitchen" } ``` Available category slugs: ``` kitchen bedroom living-room dining-room office bathroom kids-room outdoor decor hardware storage lighting ``` Use the `slug` when filtering products by category: ```javascript // Correct -- slug is lowercase, URL-safe const params = new URLSearchParams({ category: 'kitchen' }); // Wrong -- slug must match exactly const params = new URLSearchParams({ category: 'Kitchen' }); ``` Full example -- fetch categories, then filter products: ```javascript const BASE_URL = 'https://apilearn.tukas.dev'; async function main() { const catResponse = await fetch(`${BASE_URL}/api/categories/`); const catData = await catResponse.json(); const firstSlug = catData.results[0].slug; const params = new URLSearchParams({ category: firstSlug }); const prodResponse = await fetch(`${BASE_URL}/api/products/?${params}`); const prodData = await prodResponse.json(); console.log(`${prodData.count} products in "${catData.results[0].name}"`); } main(); ```

Practical patterns with categories

#
List all category names and their product counts: ```javascript const BASE_URL = 'https://apilearn.tukas.dev'; async function listCategoriesWithCounts() { const catResponse = await fetch(`${BASE_URL}/api/categories/`); const catData = await catResponse.json(); for (const cat of catData.results) { const params = new URLSearchParams({ category: cat.slug, page_size: 1 }); const prodResponse = await fetch(`${BASE_URL}/api/products/?${params}`); const data = await prodResponse.json(); console.log(`${cat.name}: ${data.count} products`); } } listCategoriesWithCounts(); ``` Find a category by name and list its products: ```javascript const BASE_URL = 'https://apilearn.tukas.dev'; async function getProductsByCategory(categoryName) { const catResponse = await fetch(`${BASE_URL}/api/categories/`); const catData = await catResponse.json(); const cat = catData.results.find( c => c.name.toLowerCase() === categoryName.toLowerCase() ); if (!cat) { console.log(`Category "${categoryName}" not found`); return []; } const params = new URLSearchParams({ category: cat.slug }); const prodResponse = await fetch(`${BASE_URL}/api/products/?${params}`); const prodData = await prodResponse.json(); console.log(`Found ${prodData.count} products in "${cat.name}"`); return prodData.results; } async function main() { const products = await getProductsByCategory('bedroom'); console.log(products[0].name); } main(); ``` Build a map of slug to name for quick lookup: ```javascript const BASE_URL = 'https://apilearn.tukas.dev'; async function main() { const response = await fetch(`${BASE_URL}/api/categories/`); const data = await response.json(); const categoryMap = Object.fromEntries(data.results.map(c => [c.slug, c.name])); // { kitchen: "Kitchen", bedroom: "Bedroom", ... } console.log(categoryMap['bedroom']); // "Bedroom" } main(); ```

Category endpoints reference

#
**Endpoints** ``` GET /api/categories/ List all categories (paginated) GET /api/products/?category= Filter products by category slug ``` **Category object** ```javascript { id: 7, name: "Kitchen", slug: "kitchen" } ``` **Response shape (same as /api/products/)** ```javascript { count: 13, // total categories next: null, // null -- all 13 fit on one page previous: null, results: [...] // array of category objects } ``` **Common patterns** ```javascript // All categories const response = await fetch(`${BASE_URL}/api/categories/`); const data = await response.json(); const cats = data.results; // Total count console.log(data.count); // 13 // Find by slug const cat = cats.find(c => c.slug === 'bedroom'); // Find by name (case-insensitive) const cat = cats.find(c => c.name.toLowerCase() === 'bedroom'); // Products in a category const params = new URLSearchParams({ category: cat.slug }); const prodResponse = await fetch(`${BASE_URL}/api/products/?${params}`); const products = await prodResponse.json(); ```
01

List all categories

#

Fetch `/api/categories/` and print the total number of categories (`count`) and the `name` of each one.

const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  // fetch /api/categories/ and print count + names
}

main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  const response = await fetch(`${BASE_URL}/api/categories/`);
  const data = await response.json();
  console.log(data.count);
  for (const cat of data.results) {
    console.log(cat.name);
  }
}

main();
02

Find a category by name

#

Fetch all categories, then find the one named "Bedroom" using `.find()` on `data.results`. Print its `id`, `name`, and `slug`.

const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  // find the "Bedroom" category and print id, name, slug
}

main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  const response = await fetch(`${BASE_URL}/api/categories/`);
  const data = await response.json();
  const bedroom = data.results.find(c => c.name === 'Bedroom');
  console.log(bedroom.id);
  console.log(bedroom.name);
  console.log(bedroom.slug);
}

main();
03

Products in a category

#

Fetch all categories, pick the first one from `results`, then fetch its products using `category=<slug>`. Print the category name and how many products it has.

const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  // 1. get categories (use data.results)
  // 2. use first category slug to filter products
  // 3. print category name and product count
}

main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  const catResponse = await fetch(`${BASE_URL}/api/categories/`);
  const catData = await catResponse.json();
  const first = catData.results[0];

  const params = new URLSearchParams({ category: first.slug });
  const prodResponse = await fetch(`${BASE_URL}/api/products/?${params}`);
  const prodData = await prodResponse.json();

  console.log(first.name);
  console.log(prodData.count);
}

main();
04

Count products per category

#

For each category in `data.results`, fetch the product count and print `"CategoryName: N products"`. Use `page_size=1` to avoid loading unnecessary data.

const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  // for each category in data.results: fetch count and print "Name: N products"
}

main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  const catResponse = await fetch(`${BASE_URL}/api/categories/`);
  const catData = await catResponse.json();

  for (const cat of catData.results) {
    const params = new URLSearchParams({ category: cat.slug, page_size: 1 });
    const prodResponse = await fetch(`${BASE_URL}/api/products/?${params}`);
    const data = await prodResponse.json();
    console.log(`${cat.name}: ${data.count} products`);
  }
}

main();
05

Build a category slug to name map

#

Fetch all categories and build a plain object that maps each `slug` to its `name`. Print the map, then look up the name for slug `"bedroom"`.

const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  // build { slug: name } map from data.results
  // print the map and look up 'bedroom'
}

main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';

async function main() {
  const response = await fetch(`${BASE_URL}/api/categories/`);
  const data = await response.json();
  const categoryMap = Object.fromEntries(data.results.map(c => [c.slug, c.name]));
  console.log(categoryMap);
  console.log(categoryMap['bedroom']);
}

main();