JavaScript · API · Середній
Замовлення
Оформлюйте замовлення з кошика і переглядайте історію замовлень.
Короткий вступ до теми та пояснення перед вправами (вправи нижче):
Оформлення та отримання замовлень
#Довідник ендпоінтів замовлень
#Вправи:
Оформити замовлення
#Додайте хоча б один товар до кошика, потім надішліть POST до `/api/orders/` з номером телефону. Виведіть `id` і `status` замовлення.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. авторизуватись
// 2. додати товар до кошика
// 3. POST /api/orders/ і вивести id + status
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const slug = await fetch(`${BASE_URL}/api/products/`).then(r => r.json())
.then(d => d.results[0].slug);
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: slug, quantity: 1 }),
});
const order = await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
}).then(r => r.json());
console.log(order.id);
console.log(order.status);
}
main();
Список замовлень
#Отримайте історію замовлень через GET `/api/orders/`. Виведіть загальну кількість та `id` і `status` кожного замовлення.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// GET /api/orders/ і вивести кількість + id і status кожного замовлення
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = { 'Authorization': `Token ${token}` };
const data = await fetch(`${BASE_URL}/api/orders/`, { headers }).then(r => r.json());
console.log(`${data.count} orders`);
for (const order of data.results) {
console.log(`#${order.id} — ${order.status}`);
}
}
main();
Деталі замовлення
#Оформіть замовлення, потім отримайте його деталі через GET `/api/orders/{id}/`. Виведіть `name`, `quantity` та `price` для кожної позиції.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// оформити замовлення потім отримати його деталі
// вивести name, quantity, price кожної позиції
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const products = await fetch(`${BASE_URL}/api/products/`).then(r => r.json());
for (const p of products.results.slice(0, 2)) {
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: p.slug, quantity: 1 }),
});
}
const order = await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
}).then(r => r.json());
const detail = await fetch(`${BASE_URL}/api/orders/${order.id}/`, { headers }).then(r => r.json());
for (const item of detail.items) {
console.log(item.name, item.quantity, item.price);
}
}
main();
Повний потік замовлення
#В одному скрипті: авторизуйтесь, додайте 3 товари до кошика, оформіть замовлення, переконайтесь що воно є у списку замовлень. Виведіть id замовлення та кількість позицій.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// повний потік: авторизація → 3 товари → замовлення → підтвердити у списку
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const products = await fetch(`${BASE_URL}/api/products/`).then(r => r.json());
for (const p of products.results.slice(0, 3)) {
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: p.slug, quantity: 1 }),
});
}
const order = await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
}).then(r => r.json());
const history = await fetch(`${BASE_URL}/api/orders/`, { headers }).then(r => r.json());
const ids = history.results.map(o => o.id);
console.log(`Order ${order.id} in list: ${ids.includes(order.id)}`);
console.log(`Items: ${order.items.length}`);
}
main();
Підрахувати загальні витрати
#Оформіть два окремих замовлення (додайте товари → замовлення → ще товари → замовлення). Потім отримайте всі замовлення і підрахуйте загальні витрати по всіх позиціях. Виведіть суму.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// оформити 2 замовлення, потім підсумувати ціни всіх позицій
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const products = await fetch(`${BASE_URL}/api/products/`).then(r => r.json());
// First order
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: products.results[0].slug, quantity: 1 }),
});
await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
});
// Second order
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: products.results[1].slug, quantity: 2 }),
});
await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
});
const allOrders = await fetch(`${BASE_URL}/api/orders/`, { headers }).then(r => r.json());
const totalSpend = allOrders.results.reduce((sum, order) =>
sum + order.items.reduce((s, item) =>
s + parseFloat(item.price) * item.quantity, 0
), 0
);
console.log(`Total spend: ${totalSpend.toFixed(2)}`);
}
main();