TL;DR

API design không phải chọn method và viết endpoint. Đó là contract giữa systems — một khi publish thì breaking change = phá client. Roadmap này tổng hợp 12 trụ cột: foundations, REST design, best practices, auth, security, docs, testing, performance, advanced patterns, DevOps, real-world rules, và learning path. Mọi rule đều tham chiếu chuẩn công nghiệp (Google AIP, Microsoft Azure, Swagger/OpenAPI).

Foundations: HTTP và kiến trúc client-server

API là interface cho phép system giao tiếp. Có 4 style chính:

  • REST — HTTP + JSON, ubiquitous, cacheable
  • GraphQL — client tự định shape query, giảm over-fetching
  • gRPC — HTTP/2 + Protobuf, low latency, cho microservice nội bộ
  • SOAP — XML + WSDL, phần lớn legacy enterprise

HTTP methods theo RFC 7231: GET idempotent và safe, POST không idempotent, PUT idempotent (replace toàn bộ), PATCH partial update, DELETE idempotent. Hiểu idempotency quyết định retry logic của client.

REST API Design: resource-oriented

REST xoay quanh resources, không phải actions. Rule cốt lõi:

  • Plural nouns: /users, /orders — không dùng /getUser
  • Hierarchical: /users/{id}/orders
  • HTTP verb = action: GET list, POST create, PUT/PATCH update, DELETE remove
  • Statelessness: mọi request tự chứa đủ context, server không lưu session giữa request

Status codes chuẩn cần nhớ: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable, 429 Too Many Requests, 500 Internal Error, 503 Service Unavailable. Dùng đúng code = client tự biết retry hay fail.

Structure & Best Practices

Sau khi có skeleton REST, đây là 6 rule để API không trở thành nightmare khi scale:

  1. Consistency — naming, casing, error shape đồng nhất toàn bộ endpoints
  2. Pagination?page=1&limit=10 (offset) hoặc cursor-based cho dataset lớn
  3. Filtering & sorting — query params: ?status=active&sort=-created_at
  4. Error handling — structured response với code, message, details; không leak stack trace
  5. Idempotency — cho POST, yêu cầu client gửi Idempotency-Key header để retry safe
  6. Rate limiting — ví dụ 100 req/min/key, trả X-RateLimit-Remaining + Retry-After

Authentication & Authorization

Authentication = anh là ai. Authorization = anh được làm gì. Hai thứ tách bạch.

  • API Keys — đơn giản, dùng cho server-to-server, không nên cho third-party
  • OAuth 2.0 (RFC 6749) — chuẩn cho third-party delegation, nhiều flow: Auth Code (web), PKCE (mobile/SPA), Client Credentials (service)
  • JWT (RFC 7519) — stateless token, self-contained claims; cẩn thận expiry ngắn + refresh token pattern

Authorization tách ra RBAC (role-based) hoặc ABAC (attribute-based). Kiểm tra permission trong handler, không chỉ middleware — middleware chỉ filter coarse-grained.

API Security

OWASP API Security Top 10 là checklist tối thiểu. Rút gọn:

  • HTTPS/TLS everywhere + HSTS
  • Input validation — schema-based (JSON Schema / OpenAPI), reject early
  • CORS — whitelist origins, không * cho endpoint có cookie
  • Rate limiting + throttling per key/IP để chặn abuse và DDoS
  • Sanitize output — không trả field nhạy cảm như password_hash, internal_id
  • Secrets management — vault/KMS, xoay định kỳ, không hardcode

Documentation: OpenAPI là chuẩn

Spec OpenAPI 3.x (tên cũ: Swagger) là de-facto standard. Lợi ích:

  • Auto-generate client SDK (TypeScript, Go, Python…)
  • Interactive docs (Swagger UI, Redoc)
  • Contract testing + mock server (Postman, Prism)
  • Versioning doc khớp với version API

Rule vàng: viết spec trước khi code (design-first). Spec là source of truth, code là implementation.

Testing

Bốn lớp bắt buộc:

  • Unit — business logic, mock I/O (Jest, Mocha, pytest)
  • Integration — full API flow với DB/queue test (Supertest, Testcontainers)
  • Contract — verify response khớp OpenAPI schema
  • Load — k6, Artillery, Locust; đo p95/p99 latency + error rate dưới traffic thực

Gắn vào CI/CD pipeline. Mọi PR merge main phải pass full suite.

Performance & Scalability

  • Caching — Redis cho session/hot data, CDN cho static response, Cache-Control + ETag headers
  • Database — index column query nhiều, N+1 query là kẻ giết hiệu năng số 1
  • Load balancing — Nginx, HAProxy, hoặc cloud LB; health check endpoint
  • Async processing — queue (RabbitMQ, Kafka, SQS) cho task nặng; return 202 Accepted + polling/webhook
  • Horizontal scaling — stateless design bắt buộc, session ra Redis

Advanced: khi REST không đủ

  • GraphQL — client query shape phức tạp (mobile, dashboard); tradeoff: caching khó, N+1 nếu không DataLoader
  • gRPC — service-to-service latency thấp, typed contract; browser cần gRPC-Web proxy
  • WebSockets / SSE — real-time (chat, live dashboard, price feed)
  • API Gateway — Kong, AWS API Gateway, Envoy; centralize auth, rate limit, logging, routing
  • Microservices — chỉ tách khi team > 1, domain rõ; sớm quá = distributed monolith

DevOps & Deployment

  • CI/CD — GitHub Actions, GitLab CI; build → test → scan → deploy
  • Docker — reproducible runtime, immutable image tag, không :latest trên prod
  • Kubernetes — khi có >5 service + cần self-healing; overkill cho 1-2 service
  • Monitoring — Prometheus metrics, Grafana dashboard, structured logs (JSON) vào ELK/Loki, distributed trace (OpenTelemetry)
  • Cloud — AWS, Azure, GCP; managed service (RDS, Cloud Run) giảm ops overhead

Real-World Best Practices

  1. Design first — spec OpenAPI trước khi code 1 dòng
  2. Backward compatibility — thêm field optional, không xoá; deprecate rồi mới remove sau N version
  3. Versioning — URI path (/v1/users) phổ biến nhất; header/media type chuẩn REST hơn nhưng khó debug
  4. Logging — request ID xuyên suốt, không log PII/secret
  5. Throttling có graceful degradation: trả 429 với Retry-After thay vì drop connection
  6. Predictable — client đoán được endpoint kế tiếp từ pattern hiện tại

Learning Path gợi ý

Beginner (tuần 1-4): HTTP & REST basics → build CRUD API với Express/FastAPI → test bằng Postman.

Intermediate (tháng 2-3): thêm JWT auth → viết OpenAPI spec → unit + integration test → deploy lên Render/Railway.

Advanced (tháng 4+): caching Redis → rate limit → API gateway → observability (Prometheus/Grafana) → Docker + K8s trên AWS/GCP. Song song: đọc Google API Design GuideMicrosoft Azure API Best Practices — đây là chuẩn công nghiệp.

What's next

API design là craft, không phải checklist. Mỗi rule trên đều có trade-off — context của team, scale, và domain quyết định chọn gì. Bắt đầu bằng REST + OpenAPI + OAuth2 cho 95% use case. Khi hit limit thực sự (mobile over-fetch, service-to-service latency, real-time) thì mới dùng GraphQL/gRPC/WebSocket.

Nguồn tham khảo: Swagger Best Practices, Google API Design Guide, Microsoft Azure Web API Design, source roadmap.