經過前 14 天的基礎理論,我們終於要來實作第一個簡單的 API 了!今天我們會透過 Node.js 與 Express ,建立一個簡單的 RESTful API,體驗 API 是如何運作的。
首先,我們需要建立一個 Node.js 專案並安裝 Express:
# 建立資料夾
mkdir my-first-api
cd my-first-api
# 初始化 Node.js 專案
npm init -y
# 安裝 Express
npm install express
接著,建立一個 index.js 檔案作為主程式。
在 index.js 中輸入以下程式碼:
const express = require('express');
const app = express();
const port = 3000;
// 中介層:讓 Express 能解析 JSON
app.use(express.json());
// 建立一個簡單的 GET API
app.get('/', (req, res) => {
res.send('Hello API!');
});
// 模擬一個 Todo 列表的 API
const todos = [
{ id: 1, task: '學習 API 基礎', done: true },
{ id: 2, task: '撰寫第一個 API', done: false }
];
// 取得所有 Todo
app.get('/api/todos', (req, res) => {
res.json(todos);
});
// 啟動伺服器
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
node index.js
範例回應:
[
{ "id": 1, "task": "學習 API 基礎", "done": true },
{ "id": 2, "task": "撰寫第一個 API", "done": false }
]
今天我們完成了第一個 API: