Backend · API

API Design RESTful: 10 Quy Tắc Thiết Kế API Chuyên Nghiệp

API Design RESTful - 10 quy tắc thiết kế chuyên nghiệp

API là hợp đồng giữa frontend và backend, giữa service và service, giữa bạn và developer bên thứ 3. API design tệ → breaking changes liên tục, integration bugs, developer frustration. API design tốt → stable, predictable, self-documenting, dễ extend mà không break backward compatibility. Theo Postman State of APIs Report 2024, 73% developers nói API quality ảnh hưởng trực tiếp đến productivity — và 52% từng bỏ integration với service vì API documentation quá kém. Bài viết này tổng hợp 10 quy tắc từ kinh nghiệm thiết kế 200+ endpoints cho BanhCuonFlow platform, kết hợp industry best practices 2025.

REST vs GraphQL vs gRPC: Khi Nào Dùng Gì?

REST là lựa chọn mặc định cho hầu hết APIs: đơn giản, dùng HTTP methods chuẩn, caching dễ dàng qua HTTP headers, ecosystem rộng lớn. GraphQL phù hợp khi frontend cần flexibility cao — clients query đúng data cần, tránh over-fetching (lấy thừa) và under-fetching (lấy thiếu). Nhưng cần invest vào schema design và query complexity analysis. gRPC cho service-to-service communication trong microservices — HTTP/2, binary Protocol Buffers, latency thấp, strong typing. Xu hướng 2025: REST cho external APIs, gRPC cho internal services, GraphQL cho complex UI applications. BanhCuonFlow sử dụng REST cho tất cả 200+ endpoints — đơn giản, dễ document, dễ test.

10 Quy Tắc Thiết Kế API Production-Ready

① Nouns, Not Verbs

URL dùng noun (danh từ) mô tả resource: /api/tasks, /api/users/123. HTTP method là verb: GET (đọc), POST (tạo), PUT (update toàn bộ), PATCH (update 1 phần), DELETE (xóa). Ví dụ sai: GET /api/getTaskById?id=123 — redundant vì GET đã là "get". Đúng: GET /api/tasks/123. Nguyên tắc: developer đọc URL biết ngay đang thao tác với resource nào, HTTP method cho biết thao tác gì.

② Consistent Naming Convention

Chọn 1 convention và giữ nguyên toàn bộ API: kebab-case (/task-comments) cho URL paths, camelCase (createdAt, taskId) cho JSON properties. Luôn dùng plural nouns cho collections: /tasks không phải /task. BanhCuonFlow convention: kebab-case URLs, camelCase JSON body, lowercase với hyphens cho query params. Inconsistency = confusion cho consumers — nhất là khi có API gateway aggregating nhiều services.

③ Versioning Từ Ngày Đầu

Luôn version API ngay từ release đầu tiên: /api/v1/tasks. Khi cần breaking change → tạo /api/v2/tasks, giữ v1 deprecated tối thiểu 6-12 tháng (theo industry standard). 3 strategies phổ biến: URI versioning (/v1/) — đơn giản nhất, visible; Header versioning (Accept: application/vnd.bcf.v2+json) — clean URLs; Query param (?version=2) — dễ test. BanhCuonFlow dùng URI versioning vì clarity cho developers. Giới hạn 2-3 active versions để tránh maintenance overhead.

④ Pagination Cho Mọi Collection

Không bao giờ return toàn bộ records — 10,000 rows response = slow, memory heavy, UX tệ. Default: ?page=1&pageSize=20. Response metadata: totalCount, pageCount, currentPage, hasNextPage. BanhCuonFlow: max pageSize = 100, default = 20. Cho infinite scroll / real-time feeds: cursor-based pagination (?cursor=eyJpZCI...&limit=20) — performance tốt hơn offset pagination khi data thay đổi thường xuyên (không bị skip hoặc duplicate items).

⑤ Consistent Error Format

Mọi error response dùng cùng JSON structure: {"statusCode": 400, "message": "...", "errors": [...]}. HTTP status codes đúng ngữ nghĩa: 400 (bad request — input sai), 401 (unauthenticated — chưa login), 403 (forbidden — đã login nhưng không có quyền), 404 (not found), 409 (conflict — duplicate), 422 (validation error), 429 (rate limited), 500 (server error). KHÔNG dùng 200 OK cho errors — frontend phải check body để biết success hay fail = anti-pattern.

⑥ Filtering, Sorting, Searching

Filter: ?status=in-progress&priority=high. Sort: ?sortBy=createdAt&sortOrder=desc. Search: ?search=bug+login. Tách riêng từng concern, không gộp vào 1 parameter phức tạp. Whitelist allowed sort fields để tránh SQL injection qua dynamic sorting. BanhCuonFlow: mọi list endpoint hỗ trợ filter + sort + search + pagination — kết hợp linh hoạt.

⑦ Idempotency

GET, PUT, DELETE phải idempotent — gọi 1 lần hay 10 lần cho cùng kết quả. POST tạo resource mới mỗi lần → nguy hiểm khi network retry: user click "Create" 2 lần → 2 records trùng. Giải pháp: X-Idempotency-Key: uuid trong request header. Server check: key đã xử lý rồi → return cached response, chưa xử lý → xử lý và cache. Stripe, PayPal đều dùng pattern này cho payment APIs — critical cho financial transactions.

⑧ Rate Limiting

Protect API khỏi abuse và DDoS: 100 requests/phút/user cho general endpoints, 10 requests/phút cho expensive operations (reports, exports). Response headers thông báo client: X-RateLimit-Limit: 100, X-RateLimit-Remaining: 42, X-RateLimit-Reset: 1703980800. Vượt limit → 429 Too Many Requests + Retry-After header. Algorithms phổ biến: Token Bucket (burst-friendly), Sliding Window (smooth distribution). Rate limit per API key, per IP, hoặc per user — tùy use case.

⑨ OpenAPI Documentation

Mọi API phải có OpenAPI (Swagger) spec — là "single source of truth" cho API contract. Developer đọc docs, try endpoints interactive, generate client SDKs mà không cần hỏi backend team. Design-first approach: viết OpenAPI spec trước, review, rồi mới implement. Auto-generate docs trong CI/CD pipeline. BanhCuonFlow: Swagger UI tại /swagger cho mọi environment, bao gồm request/response examples cho mọi endpoint.

⑩ Nested Resources Đúng Mức

Max 2 levels nesting: /projects/123/tasks — rõ ràng, dễ hiểu. /projects/123/tasks/456/comments/789/reactions — quá sâu, URL dài, khó maintain, khó cache. Dùng flat endpoints kèm filter: /reactions?commentId=789. Nested resources nên thể hiện ownership relationship rõ ràng (task belongs to project), không phải mọi association.

Security-First API Design

Bảo mật phải được bake vào API design, không phải add-on sau cùng. Authentication: OAuth 2.0 + JWT tokens cho stateless auth, refresh token rotation cho security. Authorization: RBAC (Role-Based Access Control) cho mọi endpoint — check permissions trước khi xử lý business logic. Input validation: validate tất cả inputs server-side, không tin client. HTTPS only: reject HTTP requests, dùng HSTS headers. CORS: whitelist specific origins, không dùng Access-Control-Allow-Origin: * trong production. API Gateway (Kong, AWS API Gateway) centralize authentication, rate limiting, và monitoring cho tất cả services.

BanhCuonFlow API

200+ RESTful endpoints theo 10 quy tắc trên. Swagger docs, webhook integration, rate limiting, và API explorer built-in.