🏠 Home / Hub

📡 JSON & AJAX Lesson 03 — Fetch POST / PUT / DELETE

← Back to JSON Menu  |  🏠 Hub

1. HTTP Methods — REST CRUD

MethodActionURL ExampleBody?
GETRead data/api/usersNo
POSTCreate new/api/usersYes
PUTUpdate (replace all)/api/users/1Yes
PATCHUpdate (partial)/api/users/1Yes
DELETEDelete/api/users/1No

2. POST Request — Create Data

async function createPost(title, body, userId) {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',   // ❗ မပါရင် server က JSON ဖတ်မရ
      'Authorization': 'Bearer your-token'  // Auth header (လိုရင်)
    },
    body: JSON.stringify({ title, body, userId })  // object → string
  });

  if (!response.ok) {
    throw new Error(`Server error: ${response.status}`);
  }

  const newPost = await response.json();
  console.log('Created:', newPost);
  console.log('New ID:', newPost.id);    // server က assign လုပ်ပေးတဲ့ ID
  return newPost;
}

createPost('My Title', 'My content...', 1);

3. PUT Request — Update Data

// PUT = entire object replace
async function updatePost(id, data) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });
  return response.json();
}

await updatePost(1, {
  title: 'Updated Title',
  body: 'Updated content',
  userId: 1
});

// PATCH = partial update
async function patchPost(id, fields) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(fields)  // only changed fields
  });
  return response.json();
}

await patchPost(1, { title: 'Only title changed' });  // body field untouched

4. DELETE Request

async function deletePost(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: 'DELETE'
  });

  if (response.ok) {
    console.log(`Post ${id} deleted`);
    return true;
  }
  return false;
}

await deletePost(1);

// With confirmation
async function deleteWithConfirm(id) {
  if (!confirm(`Delete post #${id}?`)) return;

  const ok = await deletePost(id);
  if (ok) {
    document.getElementById(`post-${id}`).remove();  // remove from DOM
  }
}

5. Complete API Service Pattern

// api.js — centralized API service
const BASE_URL = 'https://jsonplaceholder.typicode.com';

async function request(path, options = {}) {
  const defaults = {
    headers: { 'Content-Type': 'application/json' }
  };
  const config = { ...defaults, ...options };

  const res = await fetch(`${BASE_URL}${path}`, config);
  if (!res.ok) throw new Error(`API Error ${res.status}: ${res.statusText}`);
  return res.status === 204 ? null : res.json();  // 204 = no content
}

export const postApi = {
  getAll:   ()     => request('/posts'),
  getOne:   (id)   => request(`/posts/${id}`),
  create:   (data) => request('/posts', { method: 'POST', body: JSON.stringify(data) }),
  update:   (id, d)=> request(`/posts/${id}`, { method: 'PUT', body: JSON.stringify(d) }),
  patch:    (id, d)=> request(`/posts/${id}`, { method: 'PATCH', body: JSON.stringify(d) }),
  remove:   (id)   => request(`/posts/${id}`, { method: 'DELETE' })
};

// Usage (clean!)
const posts = await postApi.getAll();
const post  = await postApi.getOne(1);
const newP  = await postApi.create({ title: 'Test', body: '...', userId: 1 });
await postApi.remove(1);
💡 Service pattern = API calls ကို centralize ထားတာ — URL ပြောင်းရင် တစ်နေရာပဲ ပြင်ရ

← JSON 02  |  Next: JSON 04 → Async/Await →

📌 Study Checklist