JavaScript · API · Beginner
Pagination
Iterate through multi-page API responses to collect all results.
Quick topic start and explanations before exercises (exercises below):
Pagination patterns
#Pagination reference
#Exercises:
Fetch page 2
#Fetch page 2 of `/api/products/` using the `page` parameter. Print the number of results on this page and the name of the first product.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// fetch page 2 and print results count + first product name
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const params = new URLSearchParams({ page: 2 });
const response = await fetch(`${BASE_URL}/api/products/?${params}`);
const data = await response.json();
console.log(data.results.length);
console.log(data.results[0].name);
}
main();
Follow next to get all pages
#Write a loop that follows `data.next` until it's `null`. Count the total number of products collected across all pages and print it.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
let url = `${BASE_URL}/api/products/`;
let total = 0;
// loop: fetch url, add to total, set url = data.next
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
let url = `${BASE_URL}/api/products/`;
let total = 0;
while (url) {
const response = await fetch(url);
const data = await response.json();
total += data.results.length;
url = data.next;
}
console.log(total);
}
main();
Collect all products into an array
#Write a `getAllProducts()` function that paginates through all pages with `page_size=100` and returns a single flat array of all products. Print the total length.
const BASE_URL = 'https://apilearn.tukas.dev';
async function getAllProducts() {
// paginate with page_size=100, return flat array
}
async function main() {
const all = await getAllProducts();
console.log(all.length);
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function getAllProducts() {
let url = `${BASE_URL}/api/products/?page_size=100`;
const all = [];
while (url) {
const response = await fetch(url);
const data = await response.json();
all.push(...data.results);
url = data.next;
}
return all;
}
async function main() {
const all = await getAllProducts();
console.log(all.length);
}
main();
Find the most expensive product
#Load all products (paginate through all pages), then find the one with the highest price. Print its name and price.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// collect all products across pages
// find the most expensive one
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
let url = `${BASE_URL}/api/products/?page_size=100`;
const all = [];
while (url) {
const response = await fetch(url);
const data = await response.json();
all.push(...data.results);
url = data.next;
}
const mostExpensive = all.reduce((max, p) =>
parseFloat(p.price) > parseFloat(max.price) ? p : max
);
console.log(mostExpensive.name, mostExpensive.price);
}
main();
Count products per page
#Fetch all pages of `/api/products/` with the default page size. For each page, print `"Page N: X products"`. Print the total at the end.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
let url = `${BASE_URL}/api/products/`;
let page = 1;
let total = 0;
// loop pages and print info
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
let url = `${BASE_URL}/api/products/`;
let page = 1;
let total = 0;
while (url) {
const response = await fetch(url);
const data = await response.json();
console.log(`Page ${page}: ${data.results.length} products`);
total += data.results.length;
url = data.next;
page++;
}
console.log(`Total: ${total} products across ${page - 1} pages`);
}
main();