JavaScript · API · Середній
Профіль користувача
Читайте і оновлюйте профіль за допомогою GET, PATCH і PUT-запитів.
Короткий вступ до теми та пояснення перед вправами (вправи нижче):
Читання та оновлення профілю
#Довідник ендпоінта профілю
#Вправи:
Прочитати профіль
#Авторизуйтесь та надішліть GET `/api/users/profile/`. Виведіть `username` і `email`.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// GET /api/users/profile/ і вивести username і email
}
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 profile = await fetch(`${BASE_URL}/api/users/profile/`, {
headers: { 'Authorization': `Token ${token}` },
}).then(r => r.json());
console.log(profile.username);
console.log(profile.email);
}
main();
Оновити ім'я через PATCH
#Прочитайте поточний профіль, потім оновіть `first_name` через PATCH. Виведіть нове `first_name` і підтвердіть, що `email` не змінився.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. авторизуватись
// 2. прочитати профіль
// 3. PATCH first_name
// 4. вивести нове first_name і підтвердити що email не змінився
}
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 PROFILE_URL = `${BASE_URL}/api/users/profile/`;
const before = await fetch(PROFILE_URL, { headers }).then(r => r.json());
console.log('Before:', before.first_name);
const after = await fetch(PROFILE_URL, {
method: 'PATCH', headers,
body: JSON.stringify({ first_name: 'Updated' }),
}).then(r => r.json());
console.log('After:', after.first_name);
console.log('Email unchanged:', after.email === before.email);
}
main();
Оновити кілька полів одночасно
#За допомогою одного PATCH-запиту оновіть `first_name`, `last_name` та `phone_number`. Виведіть всі три оновлені значення.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// PATCH 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 updated = await fetch(`${BASE_URL}/api/users/profile/`, {
method: 'PATCH', headers,
body: JSON.stringify({
first_name: 'Test',
last_name: 'User',
phone_number: '+1112223333',
}),
}).then(r => r.json());
console.log(updated.first_name);
console.log(updated.last_name);
console.log(updated.phone_number);
}
main();
Повна заміна через PUT
#Прочитайте поточний профіль, потім надішліть PUT з усіма полями, але змініть `email`. Виведіть оновлений email для підтвердження.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// PUT потребує всіх полів — спочатку прочитайте!
}
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 PROFILE_URL = `${BASE_URL}/api/users/profile/`;
const current = await fetch(PROFILE_URL, { headers }).then(r => r.json());
const updated = await fetch(PROFILE_URL, {
method: 'PUT', headers,
body: JSON.stringify({
username: current.username,
email: '[email protected]',
first_name: current.first_name || '',
last_name: current.last_name || '',
phone_number: current.phone_number || '',
}),
}).then(r => r.json());
console.log(updated.email);
}
main();
Функція updateProfile()
#Напишіть async-функцію `updateProfile(headers, fields)`, яка PATCHить профіль і повертає результат. Викличте її двічі з різними полями.
const BASE_URL = 'https://apilearn.tukas.dev';
async function updateProfile(headers, fields) {
// PATCH /api/users/profile/ із fields, повернути результат
}
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',
};
// викликати updateProfile двічі з різними полями
}
main();
Рішення
const BASE_URL = 'https://apilearn.tukas.dev';
async function updateProfile(headers, fields) {
return fetch(`${BASE_URL}/api/users/profile/`, {
method: 'PATCH',
headers,
body: JSON.stringify(fields),
}).then(r => r.json());
}
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 r1 = await updateProfile(headers, { first_name: 'Test' });
console.log(r1.first_name);
const r2 = await updateProfile(headers, { phone_number: '+9998887777' });
console.log(r2.phone_number);
}
main();