JavaScript · API · Початковий
Параметри запиту
Фільтруйте, шукайте, сортуйте та переходьте по сторінках результатів API за допомогою URLSearchParams.
Короткий вступ до теми та пояснення перед вправами (вправи нижче):
Фільтрація, сортування та пошук — паттерни
#Довідник параметрів запиту
#Вправи:
Фільтрація за категорією
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// URLSearchParams для фільтрації category='bedroom'
// вивести count та назву першого товару
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const params = new URLSearchParams({ category: 'bedroom' });
const response = await fetch(`${BASE_URL}/api/products/?${params}`);
const data = await response.json();
console.log(data.count);
console.log(data.results[0].name);
}
main();
Сортування за ціною
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// ordering=price, page_size=5
// вивести назву і ціну кожного
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const params = new URLSearchParams({ ordering: 'price', page_size: 5 });
const response = await fetch(`${BASE_URL}/api/products/?${params}`);
const data = await response.json();
for (const p of data.results) {
console.log(p.name, p.price);
}
}
main();
Пошук товарів
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// search=oak, вивести count та кожну назву
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const params = new URLSearchParams({ search: 'oak' });
const response = await fetch(`${BASE_URL}/api/products/?${params}`);
const data = await response.json();
console.log(`${data.count} результатів`);
for (const p of data.results) {
console.log(p.name);
}
}
main();
Комбінація категорії та сортування
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// category=dining-room, ordering=-price
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const params = new URLSearchParams({ category: 'dining-room', ordering: '-price' });
const response = await fetch(`${BASE_URL}/api/products/?${params}`);
const data = await response.json();
for (const p of data.results) {
console.log(p.name, p.price);
}
}
main();
Багаторазова функція getProducts()
#const BASE_URL = 'https://apilearn.tukas.dev';
async function getProducts(params = {}) {
// побудувати URL з params, повернути масив results
}
async function main() {
const all = await getProducts();
console.log('all:', all.length);
const bedroom = await getProducts({ category: 'bedroom' });
console.log('bedroom:', bedroom.length);
const found = await getProducts({ search: 'wood', ordering: 'price' });
console.log('wood asc:', found.length);
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function getProducts(params = {}) {
const qs = new URLSearchParams(params);
const response = await fetch(`${BASE_URL}/api/products/?${qs}`);
const data = await response.json();
return data.results;
}
async function main() {
const all = await getProducts();
console.log('all:', all.length);
const bedroom = await getProducts({ category: 'bedroom' });
console.log('bedroom:', bedroom.length);
const found = await getProducts({ search: 'wood', ordering: 'price' });
console.log('wood asc:', found.length);
}
main();