Skip to content
youhoc
  • Pages
    • Home
    • Modern App Guidelines
    • Linux
      • Day 1: Linux Distributions & Navigation
      • Day 2: User Management
      • Day 3: File Permission & Ownership
      • Day 4: Package Management
      • Day 5: Services Management
    • Javascript
      • JS The Weird Part
        • Execution Context
        • Types & Operators
        • Objects & Functions
        • Error Handling & Strict Mode
        • Typescript, ES6, Tra
      • Modern JS
        • JS in the Browser
        • Data Storage JSON
        • Modern JS
        • Advanced Objects & Methods
        • Webpack & Babel
        • Async
      • jQuery
        • In-depth Analysis of jQuery
      • React-ready JS
        • Arrow Function
        • Template Literals
        • Logical AND, OR, Ternary, Nullish Operators
        • Destructuring & Rest Operator
        • Array Method
        • Immutability and Spread Operator
        • Promises, Async/Await, Callback
    • PHP
      • gruntJS
      • composer
      • MySQL
    • Docker
      • Container Basics
      • Container Networking
      • Container Image
      • Container Volume & Persistent Data
      • Dockerfile
      • Docker Compose
      • Docker Registry
    • Node.js
      • Installing & Exploring
      • Loading Modules
      • npm - Get Command Input
      • Web Server
        • Express Web Server
        • Template Engine & MVC
      • File System & Input Arguments
      • 6. Deploy to Heroku & Github
      • Authentication
      • 7. Databases
      • 8. Rest API
      • Errors
      • Sequelize
        • Sequelize Transactions: Đảm Bảo Tính Toàn Vẹn Dữ Liệu
        • 7 loại Data Types phổ biến Trong Sequelize
        • Phân Trang (Pagination) Trong Express.js Với Sequelize/MySQL
      • File Upload với Multer, Express.js
      • icon picker
        Hướng dẫn Cơ bản về Rest API
    • ReactJS
      • React from Andrew
        • Summary from Next
        • 1. Basics
        • 2. React Components
        • 3. Webpack
        • 4. Styling with SCSS
        • 5. React Router
        • 6. React Hook
      • Modern React From The Beginning
        • Intro to JSX
        • Vite Build Tools
        • Basic Component Creation
        • Component State
        • Props & Component Composition
        • useState with Inputs & Form Submission
        • useEffect, useRef & Local Storage
        • Async / Await and Http Request in React
        • React Router: Declarative Mode
        • ContextAPI
        • React Router: Framework Mode
          • File-routing & HTML Layouts
          • Server-side Data Query
          • Links & Navigation
          • Loaders
    • Typescript
      • Type User vs UserProp
    • Payload CMS
    • Authentication

Hướng dẫn Cơ bản về Rest API

1. REST API là gì?

REST (Representational State Transfer) là một kiến trúc thiết kế API cho phép các ứng dụng client (Mobile App, Web App, Desktop App) giao tiếp với server thông qua HTTP protocol.
Đặc điểm chính:
Stateless: Server không lưu trạng thái của client, mỗi request độc lập
Client-Server: Tách biệt client và server, chỉ giao tiếp qua API
Data-only: API chỉ trả về dữ liệu (JSON, XML), KHÔNG trả về HTML/UI
Resource-based: Mọi thứ đều là “resource” (users, posts, products…)
Ví dụ:

2. Phân loại API Clients

App Backend API

Mục đích: Phục vụ ứng dụng của chính mình (Mobile App, SPA, Web App)
Đặc điểm:
Private API - chỉ app của bạn sử dụng
Có authentication chặt chẽ (JWT, OAuth)
Tùy chỉnh theo nhu cầu app
Có thể thay đổi structure nếu cần
Ví dụ:

Service API (Public/Third-party API)

Mục đích: Cung cấp dịch vụ cho bên thứ 3, nhiều apps khác nhau
Đặc điểm:
Public hoặc Paid API
Cần API key/token để access
Phải đảm bảo backward compatibility
Documentation rất quan trọng
Rate limiting (giới hạn số requests)
Ví dụ:
So sánh:
App Backend API
Service API
Ai dùng?
Chỉ app của bạn
Nhiều apps khác nhau
Authentication
JWT, Session
API Key, OAuth
Documentation
Nội bộ
Public, chi tiết
Versioning
Flexible
Strict (v1, v2…)
Breaking changes
OK nếu update app
Tuyệt đối tránh
There are no rows in this table

3. Các loại dữ liệu API trả về

3.1. JSON (JavaScript Object Notation)

Ưu điểm:
✅ Chuẩn chung hiện nay (99% APIs dùng JSON)
✅ Dễ đọc, dễ parse
✅ Lightweight, nhẹ hơn XML
✅ Native support trong JavaScript
✅ Hỗ trợ tốt mọi ngôn ngữ lập trình
Nhược điểm:
❌ Không có schema validation built-in (cần dùng JSON Schema)
❌ Không support comments
Ví dụ:

3.2. XML (eXtensible Markup Language)

Ưu điểm:
✅ Có schema validation (XSD)
✅ Hỗ trợ namespaces
✅ Phù hợp với enterprise systems cũ
✅ Support comments
Nhược điểm:
❌ Verbose, nặng hơn JSON
❌ Khó đọc hơn
❌ Parse chậm hơn
❌ Ít được dùng trong modern APIs
Ví dụ:
Khi nào dùng XML:
Legacy systems (SOAP APIs)
Banking, Insurance, Government systems
Cần strict validation

3.3. HTML

Ưu điểm:
✅ Render trực tiếp trên browser
✅ SEO-friendly
Nhược điểm:
❌ KHÔNG phải REST API! (REST API chỉ trả data)
❌ Không phù hợp cho Mobile Apps
❌ Client không thể custom UI
Ví dụ (KHÔNG phải REST):
Lưu ý: Nếu API trả HTML → Đó là Server-Side Rendering, KHÔNG phải REST API!

3.4. Plain Text

Ưu điểm:
✅ Đơn giản nhất
✅ Nhẹ nhất
Nhược điểm:
❌ Không có structure
❌ Khó parse
❌ Không phù hợp cho complex data
Ví dụ:
Khi nào dùng Plain Text:
Health check endpoints: GET /healthOK
Simple status: GET /api/statusrunning
Log streaming

Chuẩn chung hiện nay: JSON

JSON là chuẩn de facto cho REST APIs vì:
Universal support
Balance giữa human-readable và machine-readable
Lightweight
Easy to parse
Content-Type headers:

4. Các loại HTTP Methods

GET - Lấy dữ liệu

Đặc điểm:
Không có body
Idempotent (gọi nhiều lần, kết quả giống nhau)
Cacheable
Safe (không thay đổi data)

POST - Tạo mới resource

Đặc điểm:
Có body (JSON data)
NOT idempotent (gọi nhiều lần → tạo nhiều records)
NOT cacheable
Response thường là 201 Created

PUT - Thay thế toàn bộ resource

Đặc điểm:
Phải gửi TOÀN BỘ data
Idempotent
Nếu resource không tồn tại → tạo mới

PATCH - Update một phần resource

Đặc điểm:
Chỉ gửi fields cần update
Idempotent
Phổ biến hơn PUT trong thực tế

PUT vs PATCH:

DELETE - Xóa resource

Đặc điểm:
Thường không có body
Idempotent (xóa 1 lần = xóa 100 lần)
Response: 204 No Content hoặc 200 OK

OPTIONS - Kiểm tra methods được phép

OPTIONS method cho phép client hỏi server về:
Methods nào được phép (GET, POST, PUT…)?
Headers nào được accept?
CORS policy như thế nào?
Chính xác! Bạn hiểu đúng rồi. Để làm rõ hơn:
Lưu ý: OPTIONS Request là do Browser tự động gửi
Browser quyết định khi nào cần gửi OPTIONS preflight request dựa trên:
Developer KHÔNG VIẾT CODE gửi OPTIONS - browser làm tự động!

OPTIONS to CORS Headers - Developer phải cấu hình

Developer phải cấu hình trên server để response OPTIONS request và các requests thật:
Flow hoàn chỉnh
Tóm tắt
Việc
Ai làm?
Khi nào?
Gửi OPTIONS request
Browser (tự động)
Cross-origin + (custom headers hoặc methods khác GET/POST)
Cấu hình CORS headers
Developer (phải code)
Setup server để response đúng CORS headers
Kiểm tra CORS policy
Browser (tự động)
Mỗi cross-origin request
Block/Allow request
Browser (tự động)
Dựa trên CORS headers từ server
There are no rows in this table
Developer chỉ cần:
✅ Cấu hình CORS trên server (cors middleware hoặc manual)
❌ KHÔNG cần viết code gửi OPTIONS - browser tự làm
❌ KHÔNG cần viết code kiểm tra CORS - browser tự làm
Ví dụ đơn giản nhất:

5. Cách đặt tên Endpoints (Best Practices)

✅ Đúng chuẩn REST
❌ Sai chuẩn REST

URL Structure Best Practices

6. Nguyên tắc của REST API (REST Principles)

1. Uniform Interface (Giao diện thống nhất)

Ý nghĩa: API endpoints phải rõ ràng, nhất quán, dễ dự đoán
Áp dụng:
Request/Response structure cũng phải consistent:

2. Stateless Interactions (Tương tác không trạng thái)

Ý nghĩa: Server KHÔNG lưu trạng thái của client, mỗi request phải chứa đủ thông tin
Ví dụ:
Lợi ích Stateless:
Scalable: Có thể thêm nhiều servers, request đến server nào cũng OK
Reliable: Server crash không mất session
Cacheable: Dễ cache responses
Implement:

3. Cacheable (Có thể cache)

Ý nghĩa: Server nên set cache headers để client/proxy có thể cache responses
Áp dụng:
Cache strategies:

4. Client-Server Separation

Ý nghĩa: Client và Server độc lập, giao tiếp chỉ qua API
Lợi ích:
Client và Server develop độc lập
Có thể swap Client (Web → Mobile) mà không đổi Server
Có thể swap Server implementation mà không đổi Client
Ví dụ:

5. Layered System (Hệ thống phân lớp)

Ý nghĩa: Client không cần biết có bao nhiêu layers giữa client và server
Ví dụ architecture:
Forward requests:


7. Response Status Code

Error Response Format

Complete Example

REST API là nền tảng của modern web development - hiểu rõ principles và best practices sẽ giúp bạn xây dựng APIs scalable, maintainable, và developer-friendly!

Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.