0

[Java Backend Zero to Hello] BÀI 6.1: RESTFUL API DESIGN

Java Backend Zero to Hello

📚 Bài viết thuộc series Java Backend Zero to Hello 📌 Phần: Phase 6: REST API & Best Practices | Bài 60/86


BÀI 6.1: RESTFUL API DESIGN

Mục tiêu

  • Hiểu nguyên tắc REST
  • Thiết kế URI chuẩn
  • Sử dụng HTTP method đúng
  • Trả về status code phù hợp

1. REST LÀ GÌ?

REST (Representational State Transfer) là kiểu thiết kế API dựa trên:

  • Resource - Tài nguyên (User, Product, Order)
  • Representation - Biểu diễn (JSON, XML)
  • State Transfer - Chuyển trạng thái qua HTTP

6 nguyên tắc REST

  1. Client-Server - Tách biệt
  2. Stateless - Mỗi request độc lập
  3. Cacheable - Có thể cache
  4. Uniform Interface - Giao diện thống nhất
  5. Layered System - Hệ thống phân lớp
  6. Code on Demand (tùy chọn)

2. THIẾT KẾ URI

2.1 Quy tắc

  • ✅ Dùng danh từ, không dùng động từ
  • ✅ Dùng số ít cho resource đơn, số nhiều cho collection
  • ✅ Dùng kebab-case hoặc snake_case
  • ✅ Phân cấp rõ ràng

2.2 Ví dụ tốt

GET    /api/users              # Danh sách users
GET    /api/users/123          # User cụ thể
POST   /api/users              # Tạo user
PUT    /api/users/123          # Cập nhật toàn bộ
PATCH  /api/users/123          # Cập nhật một phần
DELETE /api/users/123          # Xóa user

GET    /api/users/123/orders   # Orders của user
POST   /api/users/123/orders   # Tạo order cho user

2.3 Ví dụ xấu

❌ /api/getUsers
❌ /api/user/create
❌ /api/users/delete/123
❌ /api/users/123/getOrders

3. HTTP METHODS

Method Mục đích Idempotent Safe
GET Đọc ✅ ✅
POST Tạo mới ❌ ❌
PUT Cập nhật toàn bộ ✅ ❌
PATCH Cập nhật một phần ❌ ❌
DELETE Xóa ✅ ❌
HEAD Giống GET, không body ✅ ✅
OPTIONS Mô tả options ✅ ✅

Idempotent

Gọi nhiều lần cho cùng kết quả.


4. HTTP STATUS CODE

4.1 2xx - Thành công

Code Ý nghĩa
200 OK
201 Created
204 No Content

4.2 3xx - Redirect

Code Ý nghĩa
301 Moved Permanently
304 Not Modified

4.3 4xx - Client Error

Code Ý nghĩa
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
405 Method Not Allowed
409 Conflict
422 Unprocessable Entity
429 Too Many Requests

4.4 5xx - Server Error

Code Ý nghĩa
500 Internal Server Error
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout

5. RESPONSE BODY

5.1 Resource đơn

{
  "id": 123,
  "name": "An",
  "email": "an@example.com",
  "createdAt": "2024-01-15T10:30:00Z"
}

5.2 Collection

{
  "data": [
    { "id": 1, "name": "An" },
    { "id": 2, "name": "Bình" }
  ],
  "pagination": {
    "page": 1,
    "size": 10,
    "total": 100,
    "totalPages": 10
  }
}

5.3 Error

{
  "code": "USER_NOT_FOUND",
  "message": "Không tìm thấy user",
  "details": {
    "userId": 123
  },
  "timestamp": "2024-01-15T10:30:00Z",
  "path": "/api/users/123"
}

6. HEADERS QUAN TRỌNG

6.1 Request

Authorization: Bearer <token>
Content-Type: application/json
Accept: application/json
Accept-Language: vi-VN
X-Request-ID: abc-123

6.2 Response

Content-Type: application/json
Cache-Control: max-age=3600
ETag: "abc123"
Location: /api/users/123
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99

7. VERSIONING

7.1 URI Versioning (phổ biến nhất)

/api/v1/users
/api/v2/users

7.2 Header Versioning

X-API-Version: 1

7.3 Media Type Versioning

Accept: application/vnd.myapp.v1+json

8. FILTERING, SORTING, PAGINATION

8.1 Filtering

GET /api/users?status=active&role=admin

8.2 Sorting

GET /api/users?sort=name,asc
GET /api/users?sort=name,asc&sort=createdAt,desc

8.3 Pagination

GET /api/users?page=1&size=20
GET /api/users?limit=20&offset=0

8.4 Search

GET /api/users?q=an
GET /api/users?search=name:an,age:25

9. HATEOAS

Trả về links để client biết các action tiếp theo.

{
  "id": 123,
  "name": "An",
  "email": "an@example.com",
  "_links": {
    "self": { "href": "/api/users/123" },
    "orders": { "href": "/api/users/123/orders" },
    "update": { "href": "/api/users/123", "method": "PUT" },
    "delete": { "href": "/api/users/123", "method": "DELETE" }
  }
}

10. RATE LIMITING

Giới hạn số request trong khoảng thời gian.

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

Response khi vượt limit:

HTTP/1.1 429 Too Many Requests
Retry-After: 60

11. VÍ DỤ THIẾT KẾ

11.1 User API

GET    /api/v1/users              # List users
GET    /api/v1/users/{id}         # Get user
POST   /api/v1/users              # Create user
PUT    /api/v1/users/{id}         # Update user
DELETE /api/v1/users/{id}         # Delete user

POST   /api/v1/users/{id}/avatar  # Upload avatar
GET    /api/v1/users/{id}/orders  # User's orders

11.2 Product API

GET    /api/v1/products
GET    /api/v1/products/{id}
POST   /api/v1/products
PUT    /api/v1/products/{id}
DELETE /api/v1/products/{id}

GET    /api/v1/products?category=electronics&minPrice=100&maxPrice=1000
GET    /api/v1/products?sort=price,asc&page=1&size=20

11.3 Order API

GET    /api/v1/orders
GET    /api/v1/orders/{id}
POST   /api/v1/orders
PATCH  /api/v1/orders/{id}/status
DELETE /api/v1/orders/{id}

POST   /api/v1/orders/{id}/cancel
POST   /api/v1/orders/{id}/refund

12. BÀI TẬP THỰC HÀNH

Bài 1: Thiết kế API

Thiết kế REST API cho hệ thống blog với: users, posts, comments, tags.

Bài 2: Status Code

Áp dụng status code phù hợp cho từng trường hợp.

Bài 3: Pagination

Implement API trả về danh sách có phân trang, sort, filter.


13. TÓM TẮT

Khái niệm Mô tả
Resource Tài nguyên
URI Định danh resource
HTTP Method Hành động
Status Code Kết quả
Idempotent Gọi nhiều lần = 1 lần
Versioning Quản lý phiên bản
HATEOAS Links trong response
Rate Limiting Giới hạn request

Bài tiếp theo: 6.2 API Documentation


🧭 Điều Hướng Series

⬅️ Bài trước: PHASE 6: REST API & BEST PRACTICES - Tổng Quan & Mục Tiêu

📋 Lộ trình tổng quan: Xem Toàn Bộ Series

➡️ Bài tiếp theo: BÀI 6.2: API DOCUMENTATION (OPENAPI/SWAGGER)


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí