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();