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.
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).
// 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.