DevToolBoxฟรี
บล็อก

REST API Design Best Practices: คู่มือฉบับสมบูรณ์

12 นาทีโดย DevToolBox

การออกแบบ REST API ที่ดีไม่ใช่แค่การส่ง JSON กลับ API ที่ออกแบบมาอย่างดีต้องคาดเดาได้ สม่ำเสมอ ปลอดภัย และใช้งานง่าย คู่มือนี้ครอบคลุมแนวปฏิบัติที่ดีที่สุดในการออกแบบ REST API

1. ใช้คำนามสำหรับ Resource URI

REST API จำลองทรัพยากร ไม่ใช่การกระทำ

# Good - nouns representing resources
GET    /api/v1/users          # list users
GET    /api/v1/users/123      # get user 123
POST   /api/v1/users          # create a user
PUT    /api/v1/users/123      # replace user 123
PATCH  /api/v1/users/123      # partially update user 123
DELETE /api/v1/users/123      # delete user 123

# Bad - verbs describing actions
GET    /api/v1/getUsers
POST   /api/v1/createUser
POST   /api/v1/deleteUser/123
GET    /api/v1/getUserById?id=123
# Nested resources (one level deep)
GET    /api/v1/users/123/orders       # orders for user 123
GET    /api/v1/users/123/orders/456   # order 456 for user 123
POST   /api/v1/users/123/orders       # create order for user 123

# For actions that don't map to CRUD, use sub-resources
POST   /api/v1/users/123/activate     # activate user (action)
POST   /api/v1/orders/456/cancel      # cancel order (action)
POST   /api/v1/emails/789/resend      # resend email

2. ใช้ HTTP Method อย่างถูกต้อง

แต่ละ HTTP method มีความหมายเฉพาะ

MethodPurposeIdempotentRequest Body
GETRead a resourceYesNo
POSTCreate a resourceNoYes
PUTFull replacementYesYes
PATCHPartial updateNo*Yes
DELETERemove a resourceYesNo

3. ใช้ชื่อทรัพยากรพหูพจน์

ใช้คำนามพหูพจน์สำหรับ collection เสมอ

# Good - consistent plural nouns
/api/v1/users
/api/v1/users/123
/api/v1/products
/api/v1/products/456/reviews

# Bad - mixing singular and plural
/api/v1/user          # singular
/api/v1/user/123
/api/v1/productList   # avoid "list" suffix

4. ใช้ HTTP Status Code อย่างถูกต้อง

Status code บอกไคลเอนต์ว่าเกิดอะไรขึ้น

CodeWhen to Use
200 OKSuccessful GET, PUT, PATCH, or DELETE
201 CreatedSuccessful POST that creates a resource
204 No ContentSuccessful DELETE with no response body
400 Bad RequestMalformed request syntax or invalid data
401 UnauthorizedMissing or invalid authentication
403 ForbiddenAuthenticated but not authorized
404 Not FoundResource does not exist
409 ConflictConflicting state (e.g., duplicate email)
422 UnprocessableValidation errors in request body
429 Too Many RequestsRate limit exceeded
500 Internal ErrorUnexpected server error

5. กำหนดเวอร์ชัน API

การกำหนดเวอร์ชัน API ปกป้องผู้ใช้เดิมเมื่อมี breaking changes

# Strategy 1: URI versioning (most common)
GET /api/v1/users
GET /api/v2/users

# Strategy 2: Header versioning
GET /api/users
Accept: application/vnd.myapi.v2+json

# Strategy 3: Query parameter versioning
GET /api/users?version=2
StrategyProsCons
URI pathSimple, visible, cacheableURI pollution
HeaderClean URIsHarder to test, less visible
Query paramEasy to addCache-unfriendly, easy to forget

6. การแบ่งหน้า การกรอง และการเรียงลำดับ

ทุก endpoint ที่ส่งคืน collection ควรรองรับ pagination

# Offset-based pagination (simplest)
GET /api/v1/users?page=2&limit=25
GET /api/v1/users?offset=25&limit=25

# Cursor-based pagination (better for large datasets)
GET /api/v1/users?cursor=eyJpZCI6MTAwfQ&limit=25

# Response with pagination metadata
{
  "data": [...],
  "pagination": {
    "total": 1250,
    "page": 2,
    "limit": 25,
    "totalPages": 50,
    "hasNext": true,
    "hasPrev": true
  }
}

# Filtering and sorting
GET /api/v1/products?category=electronics&minPrice=100&maxPrice=500
GET /api/v1/products?sort=price&order=asc
GET /api/v1/products?sort=-created_at  # prefix with - for descending
GET /api/v1/users?fields=id,name,email  # sparse fieldsets

7. รูปแบบ Error Response

รูปแบบ error ที่สม่ำเสมอช่วยให้ไคลเอนต์จัดการข้อผิดพลาดได้

// Consistent error response format
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address",
        "value": "not-an-email"
      },
      {
        "field": "age",
        "message": "Must be at least 18",
        "value": 15
      }
    ],
    "requestId": "req_abc123",
    "timestamp": "2026-01-15T10:30:00Z",
    "docs": "https://api.example.com/docs/errors#VALIDATION_ERROR"
  }
}

// Simple error (non-validation)
{
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "User with id 999 not found",
    "requestId": "req_def456"
  }
}

8. การยืนยันตัวตนและความปลอดภัย

ความปลอดภัยของ API เป็นสิ่งที่ต่อรองไม่ได้

# Bearer token authentication (JWT)
GET /api/v1/users
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...

# API key authentication
GET /api/v1/users
X-API-Key: sk_live_abc123def456

# OAuth 2.0 token request
POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET
&scope=read:users write:users
  • Always use HTTPS in production
  • Never put secrets in query parameters (they appear in server logs)
  • Use short-lived access tokens (15-60 min) with refresh tokens
  • Implement CORS properly for browser-based clients
  • Validate and sanitize all input to prevent injection attacks
  • Use rate limiting to prevent brute-force attacks

9. Rate Limiting

Rate limiting ปกป้อง API ของคุณจากการใช้งานในทางที่ผิด

# Rate limit response headers (standard)
HTTP/1.1 200 OK
X-RateLimit-Limit: 1000        # max requests per window
X-RateLimit-Remaining: 742     # requests remaining
X-RateLimit-Reset: 1706810400  # Unix timestamp when limit resets
Retry-After: 60                # seconds until next request (on 429)

# Rate limit exceeded response
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 60

{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests. Limit: 1000/hour",
    "retryAfter": 60
  }
}

10. HATEOAS และลิงก์

HATEOAS เพิ่มความสามารถในการค้นพบให้กับ API

// HATEOAS response example
{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "status": "active",
  "_links": {
    "self": { "href": "/api/v1/users/123" },
    "orders": { "href": "/api/v1/users/123/orders" },
    "deactivate": {
      "href": "/api/v1/users/123/deactivate",
      "method": "POST"
    }
  }
}

// Paginated collection with HATEOAS links
{
  "data": [...],
  "_links": {
    "self": { "href": "/api/v1/users?page=2&limit=25" },
    "first": { "href": "/api/v1/users?page=1&limit=25" },
    "prev": { "href": "/api/v1/users?page=1&limit=25" },
    "next": { "href": "/api/v1/users?page=3&limit=25" },
    "last": { "href": "/api/v1/users?page=50&limit=25" }
  }
}

คำถามที่พบบ่อย

PUT หรือ PATCH สำหรับการอัปเดต?

PUT สำหรับการแทนที่ทั้งหมด PATCH สำหรับการอัปเดตบางส่วน

URI ควรเป็นตัวพิมพ์เล็ก?

ใช่ ใช้ kebab-case ตัวพิมพ์เล็ก

จัดการ resource ซ้อนกันอย่างไร?

จำกัดการซ้อนไว้ที่ระดับเดียว

วิธีการยืนยันตัวตนที่ดีที่สุด?

OAuth 2.0 กับ JWT สำหรับแอปที่เน้นผู้ใช้

GraphQL หรือ REST?

REST ง่ายกว่าและ caching ดีกว่า GraphQL สำหรับข้อมูลที่ซับซ้อน

TL;DR

  • Use nouns (not verbs) for resource URIs
  • Use the correct HTTP method for each operation
  • Always use plural resource names
  • Return appropriate HTTP status codes
  • Version your API from day one (URI path is simplest)
  • Support pagination, filtering, and sorting for collections
  • Use a consistent error response format
  • Always use HTTPS and proper authentication
  • Implement rate limiting with standard headers
  • Consider HATEOAS for API discoverability

การปฏิบัติตามแนวทางเหล่านี้ตั้งแต่เริ่มต้นช่วยประหยัดเวลา refactoring

𝕏 Twitterin LinkedIn
บทความนี้มีประโยชน์ไหม?

อัปเดตข่าวสาร

รับเคล็ดลับการพัฒนาและเครื่องมือใหม่ทุกสัปดาห์

ไม่มีสแปม ยกเลิกได้ตลอดเวลา

ลองเครื่องมือที่เกี่ยวข้อง

{ }JSON Formatter4xxHTTP Status Code ReferenceJWTJWT Decoder

บทความที่เกี่ยวข้อง

REST API Best Practices: คู่มือฉบับสมบูรณ์ 2026

เรียนรู้แนวทางปฏิบัติที่ดีที่สุดในการออกแบบ REST API: การตั้งชื่อ, จัดการ error, authentication และความปลอดภัย

HTTP Status Codes: คู่มืออ้างอิงฉบับสมบูรณ์สำหรับนักพัฒนา

คู่มือรหัสสถานะ HTTP: 1xx ถึง 5xx พร้อมคำอธิบายเชิงปฏิบัติ แนวปฏิบัติ API และเคล็ดลับการ debug

API Authentication: OAuth 2.0 vs JWT vs API Key

เปรียบเทียบวิธีการยืนยันตัวตน API: OAuth 2.0, JWT Bearer token และ API key