JavaScript · API · Початковий
Перший запит
Зробіть свій перший HTTP-запит за допомогою fetch і прочитайте JSON-відповідь.
Короткий вступ до теми та пояснення перед вправами (вправи нижче):
Читання відповіді
#Шпаргалка fetch та Response
#Вправи:
Отримати список товарів
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. fetch /api/products/
// 2. вивести count та results.length
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/products/`);
const data = await response.json();
console.log(data.count);
console.log(data.results.length);
}
main();
Отримати один товар
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// GET /api/products/1/
// вивести name, price, slug
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/products/1/`);
const product = await response.json();
console.log(product.name);
console.log(product.price);
console.log(product.slug);
}
main();
Перевірити response.status та response.ok
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// Fetch неіснуючого товару — перевірити status і ok
// Fetch реального товару — перевірити status і ok
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const r1 = await fetch(`${BASE_URL}/api/products/99999/`);
console.log(r1.status, r1.ok); // 404 false
const r2 = await fetch(`${BASE_URL}/api/products/1/`);
console.log(r2.status, r2.ok); // 200 true
}
main();
Отримати категорії
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// GET /api/categories/ і вивести count + назву кожної
}
main();
Рішення
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();
Назва першого товару зі списку
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// fetch products, взяти перший результат, вивести name, рядок price та parseFloat(price)
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/products/`);
const data = await response.json();
const first = data.results[0];
console.log(first.name);
console.log(first.price);
console.log(parseFloat(first.price));
}
main();