iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
Modern Web

Modern Web:從基礎、框架到前端學習系列 第 20

Day 20:RESTful API 設計與整合

  • 分享至 

  • xImage
  •  

學習目標

  1. 了解RESTful API 的設計原則(資源導向、HTTP 方法、狀態碼)。
  2. 學會使用Fetch APIAxio來呼叫後端 API。
  3. 實作前端與後端的資料互動(GET / POST / PUT / DELETE)。
  4. 熟悉 JSON 格式在 API 傳遞中的角色。

重點整理

1. RESTful API 基本原則

  • 資源導向 (Resource Oriented):以名詞為資源(如 /users, /products)。
  • HTTP 方法 (Methods)
    • GET → 讀取資料
    • POST → 新增資料
    • PUT / PATCH → 修改資料
    • DELETE → 刪除資料

例子:

GET    /api/users       → 取得所有用戶
GET    /api/users/1     → 取得 ID=1 的用戶
POST   /api/users       → 新增用戶
PUT    /api/users/1     → 更新 ID=1 的用戶
DELETE /api/users/1     → 刪除 ID=1 的用戶

2. HTTP 狀態碼 (常見)

  • 200 OK → 請求成功
  • 201 Created → 新增成功
  • 400 Bad Request → 請求錯誤
  • 401 Unauthorized → 未授權
  • 404 Not Found → 資源不存在
  • 500 Internal Server Error → 伺服器錯誤

3. Fetch API 使用

// GET 請求
fetch('https://jsonplaceholder.typicode.com/posts')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

// POST 請求
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    title: '新文章',
    body: '這是一篇練習文章',
    userId: 1
  })
})
  .then(res => res.json())
  .then(data => console.log('新增成功:', data))
  .catch(err => console.error(err));

4. Axios 簡單範例(更好用)

// 使用 Axios 發送 GET 請求
axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

// 使用 Axios 發送 POST 請求
axios.post('https://jsonplaceholder.typicode.com/posts', {
  title: '新文章',
  body: '這是一篇練習文章',
  userId: 1
})
  .then(res => console.log('新增成功:', res.data))
  .catch(err => console.error(err));

今日小專案:API 練習器

建立一個簡單的文章清單 App,功能包含:

  1. 顯示所有文章(GET)
  2. 新增文章(POST)
  3. 刪除文章(DELETE)

專案結構:

api-practice/
  ├── index.html
  ├── style.css
  └── script.js

index.html

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <title>API 練習器</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>文章清單</h1>
  <ul id="postList"></ul>

  <h2>新增文章</h2>
  <input type="text" id="title" placeholder="標題">
  <input type="text" id="body" placeholder="內容">
  <button id="addPost">新增文章</button>

  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script src="script.js"></script>
</body>
</html>

script.js

const postList = document.getElementById('postList');
const addBtn = document.getElementById('addPost');
const titleInput = document.getElementById('title');
const bodyInput = document.getElementById('body');

// API 來源
const API_URL = 'https://jsonplaceholder.typicode.com/posts';

// 顯示所有文章
function fetchPosts() {
  axios.get(API_URL)
    .then(res => {
      postList.innerHTML = '';
      res.data.slice(0, 5).forEach(post => { // 只顯示前5篇
        const li = document.createElement('li');
        li.innerHTML = `
          <strong>${post.title}</strong> - ${post.body}
          <button onclick="deletePost(${post.id})">刪除</button>
        `;
        postList.appendChild(li);
      });
    })
    .catch(err => console.error(err));
}

// 新增文章
addBtn.addEventListener('click', () => {
  const newPost = {
    title: titleInput.value,
    body: bodyInput.value,
    userId: 1
  };

  axios.post(API_URL, newPost)
    .then(res => {
      alert('新增成功!');
      fetchPosts();
    })
    .catch(err => console.error(err));
});

// 刪除文章
function deletePost(id) {
  axios.delete(`${API_URL}/${id}`)
    .then(() => {
      alert(`刪除成功 (ID=${id})`);
      fetchPosts();
    })
    .catch(err => console.error(err));
}

// 初始化
fetchPosts();

今日成果

  • 熟悉 RESTful API 的設計與操作
  • 學會用Fetch API / Axios發送請求
  • 完成一個可「顯示 / 新增 / 刪除」文章的小型應用

📌 思考延伸:

  • 如果要修改文章(PUT / PATCH),要怎麼設計?
  • 如果 API 要驗證登入,該怎麼傳送 Token?

上一篇
Day19:API 資料渲染與錯誤處理
系列文
Modern Web:從基礎、框架到前端學習20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言