Cấp độ: intermediate40 phútminMiễn phíFreeProduct DeveloperProduct Developer

REST API với Node.jsREST API with Node.js

API quản lý danh sách taskA task list management API

Bạn sẽ học gìWhat you will learn

  • Khởi tạo Express appInitialize an Express app
  • Tạo CRUD endpointsCreate CRUD endpoints
  • Dùng Postman test APIUse Postman to test API

Bạn sẽ tạo gìWhat you will build

API quản lý danh sách taskA task list management API

Nội dung bài họcLesson content

REST API là gì?What is a REST API?

REST API (Representational State Transfer) là cách ứng dụng giao tiếp qua HTTP. API nhận request từ client, trả response (thường là JSON). Mỗi URL (endpoint) đại diện cho 1 tài nguyên: /tasks, /users, /products. HTTP methods: GET (đọc), POST (tạo), PUT (sửa), DELETE (xóa).A REST API (Representational State Transfer) is how applications communicate over HTTP. The API receives a request from a client, returns a response (usually JSON). Each URL (endpoint) represents a resource: /tasks, /users, /products. HTTP methods: GET (read), POST (create), PUT (update), DELETE (delete).

Khởi tạo Express appInitialize an Express app

Express là framework Node.js phổ biến nhất cho API. Cài đặt: npm install express. Tạo app: const app = express(). app.use(express.json()) cho phép nhận JSON body. app.listen(port) khởi động server. Mỗi endpoint là 1 route: app.get, app.post, app.put, app.delete.Express is the most popular Node.js framework for APIs. Install: npm install express. Create app: const app = express(). app.use(express.json()) enables JSON body parsing. app.listen(port) starts the server. Each endpoint is a route: app.get, app.post, app.put, app.delete.

javascript
                      
                        const express = require('express');
const app = express();
app.use(express.json());

let tasks = [];

// GET tất cả task
app.get('/tasks', (req, res) => {
  res.json({ success: true, data: tasks });
});

// POST tạo task mới
app.post('/tasks', (req, res) => {
  const task = { id: Date.now(), title: req.body.title, done: false };
  tasks.push(task);
  res.status(201).json({ success: true, data: task });
});

app.listen(3000, () => console.log('API chạy tại port 3000'));
                      
                    

CRUD: GET, POST, PUT, DELETECRUD: GET, POST, PUT, DELETE

CRUD = Create, Read, Update, Delete. POST = Create (tạo mới), GET = Read (đọc), PUT = Update (sửa), DELETE = Delete (xóa). Mỗi endpoint có URL + method. Ví dụ: GET /tasks (xem tất cả), POST /tasks (tạo mới), PUT /tasks/:id (sửa 1 task), DELETE /tasks/:id (xóa 1 task).CRUD = Create, Read, Update, Delete. POST = Create, GET = Read, PUT = Update, DELETE = Delete. Each endpoint has a URL + method. Example: GET /tasks (view all), POST /tasks (create new), PUT /tasks/:id (update 1 task), DELETE /tasks/:id (delete 1 task).

javascript
                      
                        // PUT: cập nhật task theo id
app.put('/tasks/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const task = tasks.find(t => t.id === id);
  if (!task) return res.status(404).json({ success: false, error: 'Không tìm thấy' });
  task.title = req.body.title || task.title;
  task.done = req.body.done !== undefined ? req.body.done : task.done;
  res.json({ success: true, data: task });
});

// DELETE: xóa task theo id
app.delete('/tasks/:id', (req, res) => {
  const id = parseInt(req.params.id);
  tasks = tasks.filter(t => t.id !== id);
  res.json({ success: true, message: 'Đã xóa' });
});
                      
                    

HTTP status codesHTTP status codes

Mỗi response cần status code phù hợp: 200 (OK/thành công), 201 (Created/đã tạo), 400 (Bad Request/lỗi client), 404 (Not Found/không tìm thấy), 500 (Internal Server Error/lỗi server). Status code đúng giúp client hiểu kết quả và xử lý lỗi.Each response needs an appropriate status code: 200 (OK/success), 201 (Created), 400 (Bad Request/client error), 404 (Not Found), 500 (Internal Server Error). Correct status codes help clients understand results and handle errors.

Bài tập thực hànhHands-on exercises

1Tạo Express API với endpoint GET /tasks trả về danh sách task (mảng rỗng ban đầu). Chạy trên port 3000.Create an Express API with endpoint GET /tasks returning a task list (empty array initially). Run on port 3000.

Gợi ýHint

app.get('/tasks', ...) → res.json({ data: [] })app.get('/tasks', ...) → res.json({ data: [] })

Lời giảiSolution
javascript
                      
                        const express = require('express');
const app = express();
app.use(express.json());

let tasks = [];

app.get('/tasks', (req, res) => {
  res.json({ success: true, data: tasks });
});

app.listen(3000, () => console.log('API chạy tại port 3000'));
                      
                    

2Thêm endpoint POST /tasks nhận { title } trong body, tạo task mới với id tự tăng, trả status 201.Add endpoint POST /tasks receiving { title } in body, create a new task with auto-increment id, return status 201.

Gợi ýHint

app.post('/tasks', ...) → tạo object task → push vào mảng → res.status(201).json(...)app.post('/tasks', ...) → create task object → push to array → res.status(201).json(...)

Lời giảiSolution
javascript
                      
                        app.post('/tasks', (req, res) => {
  const task = {
    id: Date.now(),
    title: req.body.title,
    done: false
  };
  tasks.push(task);
  res.status(201).json({ success: true, data: task });
});
                      
                    

Kiểm traQuiz

Chọn đáp án đúng cho mỗi câu. Nhấn để xem giải thích.Choose the correct answer for each question. Click to see explanation.

Câu 1: HTTP method nào dùng để tạo tài nguyên mới?Q1: Which HTTP method is used to create a new resource?

Câu 2: Status code 201 nghĩa là gì?Q2: What does status code 201 mean?

Câu 3: Express là gì?Q3: What is Express?

Câu 4: app.use(express.json()) làm gì?Q4: What does app.use(express.json()) do?

Code mẫuSample code

javascript
                const express = require('express');
const app = express();
app.use(express.json());

let tasks = [];

// GET tất cả / GET all
app.get('/tasks', (req, res) => {
  res.json({ success: true, data: tasks });
});

// POST tạo mới / POST create
app.post('/tasks', (req, res) => {
  const task = { id: Date.now(), ...req.body };
  tasks.push(task);
  res.status(201).json({ success: true, data: task });
});

app.listen(3000, () => console.log('API running on port 3000'));