Python · API · Beginner
Working with Categories
Fetch and explore product categories, then use them to filter the product list.
Quick topic start and explanations before exercises (exercises below):
Practical patterns with categories
#Category endpoints reference
#Exercises:
List all categories
#Fetch the category list and print the name of every category, one per line.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Fetch all categories and print each name
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/categories/')
for cat in response.json()['results']:
print(cat['name'])
Build a slug-to-name mapping
#Fetch all categories and build a dict that maps each slug to its display name. Print the dict.
import requests
BASE_URL = 'https://apilearn.tukas.dev'
# Build {slug: name} dict and print it
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/categories/')
categories = response.json()['results']
slug_to_name = {cat['slug']: cat['name'] for cat in categories}
print(slug_to_name)
Fetch a single category
#Fetch the "outdoor" category by its slug and print its id, name, and slug.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Fetch the outdoor category and print id, name, slug
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/categories/outdoor/')
cat = response.json()
print(cat['id'])
print(cat['name'])
print(cat['slug'])
Count products per category
#For each category, print its name and the total number of products it contains. Format each line as: "Category name: N products".
import requests BASE_URL = 'https://apilearn.tukas.dev' # For each category, fetch the product count and print it
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
categories = requests.get(f'{BASE_URL}/api/categories/').json()['results']
for cat in categories:
count = requests.get(
f'{BASE_URL}/api/products/',
params={'category': cat['slug'], 'page_size': 1},
).json()['count']
print(f"{cat['name']}: {count} products")
Find the largest category
#Find the category that contains the most products and print its name and product count.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Find the category with the most products
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
categories = requests.get(f'{BASE_URL}/api/categories/').json()['results']
counts = []
for cat in categories:
count = requests.get(
f'{BASE_URL}/api/products/',
params={'category': cat['slug'], 'page_size': 1},
).json()['count']
counts.append((count, cat['name']))
best_count, best_name = max(counts)
print(f'{best_name}: {best_count} products')