iT邦幫忙

2025 iThome 鐵人賽

DAY 17
0
自我挑戰組

API 全攻略系列 第 17

Day 17: API 的 CRUD 設計(建立、讀取、更新、刪除)

  • 分享至 

  • xImage
  •  

前言

在前幾天的文章中,我們已經能透過 API 讀取資料,今天要把功能補齊,做出一個完整的 CRUD API

  • Create(建立資料)
  • Read(讀取資料)
  • Update(更新資料)
  • Delete(刪除資料)
    這些操作構成了大部分 API 的核心。

CRUD 對應的 HTTP 方法

在 RESTful API 中,通常這樣對應:

操作 HTTP 方法 範例路由
建立 Create POST POST /api/todos
讀取 Read GET GET /api/todosGET /api/todos/:id
更新 Update PUT / PATCH PUT /api/todos/:id
刪除 Delete DELETE DELETE /api/todos/:id

範例程式碼

在 index.js 中加入以下程式碼:

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

// 模擬資料庫
let todos = [
  { id: 1, task: '學習 API 基礎', done: true },
  { id: 2, task: '撰寫第一個 API', done: false }
];

// ===== Create 建立資料 =====
app.post('/api/todos', (req, res) => {
  const { task } = req.body;
  if (!task) {
    return res.status(400).json({ error: 'Task is required' });
  }
  const newTodo = {
    id: todos.length + 1,
    task,
    done: false
  };
  todos.push(newTodo);
  res.status(201).json(newTodo);
});

// ===== Read 讀取資料 =====
// 取得所有
app.get('/api/todos', (req, res) => {
  res.json(todos);
});

// 取得單一
app.get('/api/todos/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const todo = todos.find(t => t.id === id);
  if (!todo) {
    return res.status(404).json({ error: 'Todo not found' });
  }
  res.json(todo);
});

// ===== Update 更新資料 =====
app.put('/api/todos/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const { task, done } = req.body;
  const todo = todos.find(t => t.id === id);
  if (!todo) {
    return res.status(404).json({ error: 'Todo not found' });
  }
  if (task !== undefined) todo.task = task;
  if (done !== undefined) todo.done = done;
  res.json(todo);
});

// ===== Delete 刪除資料 =====
app.delete('/api/todos/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const index = todos.findIndex(t => t.id === id);
  if (index === -1) {
    return res.status(404).json({ error: 'Todo not found' });
  }
  const deleted = todos.splice(index, 1);
  res.json(deleted[0]);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});


測試方式

1. 啟動伺服器:

node index.js

2. 測試 API(可以用 Postman 或 curl):

  • 建立新 Todo
POST http://localhost:3000/api/todos
Body: { "task": "寫 Day 17 文章" }
  • 讀取所有 Todo
GET http://localhost:3000/api/todos
  • 讀取單一 Todo
GET http://localhost:3000/api/todos/1
  • 更新 Todo
PUT http://localhost:3000/api/todos/2
Body: { "done": true }
  • 刪除 Todo
DELETE http://localhost:3000/api/todos/1

小結

今天我們完成了一個 完整的 CRUD API

  • POST 建立資料
  • GET 讀取資料
  • PUT 更新資料
  • DELETE 刪除資料
    這就是大部分 API 的核心模式。

上一篇
Day 16: API 路由與參數設計
系列文
API 全攻略17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言