JavaScript · API · Середній

Профіль користувача

5 завдань

Читайте і оновлюйте профіль за допомогою GET, PATCH і PUT-запитів.

GET, PATCH та PUT — коли використовувати кожен

#
Всі три методи використовують один ендпоінт `/api/users/profile/`, всі потребують Authorization: ``` GET /api/users/profile/ Прочитати поточний профіль PATCH /api/users/profile/ Часткове оновлення — змінюються лише надіслані поля PUT /api/users/profile/ Повна заміна — необхідні всі поля ``` Поля профілю: ```javascript { id: 1, username: "alice42", email: "[email protected]", first_name: "Alice", last_name: "Smith", phone_number: "+1234567890", image: null } ``` **PATCH** — точкове оновлення. Надсилайте лише те, що хочете змінити: ```javascript // Змінюється лише first_name — все інше залишається без змін await fetch(`${BASE_URL}/api/users/profile/`, { method: 'PATCH', headers, body: JSON.stringify({ first_name: 'Alicia' }), }).then(r => r.json()); ``` **PUT** — повна заміна. Необхідно надіслати всі поля, або пропущені будуть очищені: ```javascript // Необхідно включити всі поля await fetch(`${BASE_URL}/api/users/profile/`, { method: 'PUT', headers, body: JSON.stringify({ username: 'alice42', email: '[email protected]', first_name: 'Alicia', last_name: 'Smith', phone_number: '+1234567890', }), }); ``` Використовуйте PATCH для більшості оновлень — це безпечніше, бо не торкається полів, які ви не надіслали.

Читання та оновлення профілю

#
Читаємо профіль, оновлюємо одне поле через PATCH, перевіряємо, потім замінюємо всі поля через PUT: ```javascript 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 profile = await fetch(PROFILE_URL, { headers }).then(r => r.json()); console.log("Ім'я:", profile.first_name); console.log('Email:', profile.email); // PATCH — змінюємо лише first_name const patched = await fetch(PROFILE_URL, { method: 'PATCH', headers, body: JSON.stringify({ first_name: 'Alicia' }), }).then(r => r.json()); console.log("Нове ім'я:", patched.first_name); // Alicia console.log('Email не змінився:', patched.email); // той самий // PUT — замінюємо всі поля const updated = await fetch(PROFILE_URL, { method: 'PUT', headers, body: JSON.stringify({ username: profile.username, email: '[email protected]', first_name: 'Alicia', last_name: profile.last_name || '', phone_number: profile.phone_number || '', }), }).then(r => r.json()); console.log('Email після PUT:', updated.email); } main(); ``` Багаторазовий помічник оновлення: ```javascript async function updateProfile(headers, fields) { return fetch(`${BASE_URL}/api/users/profile/`, { method: 'PATCH', headers, body: JSON.stringify(fields), }).then(r => r.json()); } const result = await updateProfile(headers, { first_name: 'Bob', phone_number: '+9998887777' }); console.log(result.first_name); ```

Довідник ендпоінта профілю

#
**Ендпоінт** ``` GET /api/users/profile/ Прочитати профіль → 200 + об'єкт профілю PATCH /api/users/profile/ Часткове оновлення → 200 + оновлений профіль PUT /api/users/profile/ Повна заміна → 200 + оновлений профіль ``` **Поля профілю** ``` id number Незмінний id користувача username string Ім'я для входу (унікальне) email string first_name string last_name string phone_number string Формат: +1234567890 image string URL або null ``` **PATCH vs PUT** ``` PATCH Надсилати лише змінені поля Безпечно — інші поля не зачіпаються PUT Надсилати всі поля Відсутні поля будуть очищені ``` **Безпечний паттерн PUT — спочатку прочитати, потім надіслати всі** ```javascript const current = await fetch(PROFILE_URL, { headers }).then(r => r.json()); await fetch(PROFILE_URL, { method: 'PUT', headers, body: JSON.stringify({ ...current, email: '[email protected]' }), }); ```
01

Прочитати профіль

#

Авторизуйтесь та надішліть 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();
02

Оновити ім'я через 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();
03

Оновити кілька полів одночасно

#

За допомогою одного 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();
04

Повна заміна через 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();
05

Функція 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();