Single Intermediate 14 Maret 2024 8 min

REST API Best Practices

Essential best practices for designing and implementing REST APIs

REST API Best Practices

REST API adalah standar komunikasi antara client dan server. Berikut best practices yang harus kamu ketahui.

1. Gunakan HTTP Methods dengan Benar

  • GET - Retrieve data
  • POST - Create new resource
  • PUT/PATCH - Update resource
  • DELETE - Remove resource
GET /api/users
POST /api/users
PUT /api/users/123
DELETE /api/users/123

2. Gunakan Noun, Bukan Verb

# Good
GET /api/users
GET /api/orders

# Bad
GET /api/getUsers
GET /api/createOrder

3. Versioning API

Selalu version API-mu:

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

4. Gunakan Proper HTTP Status Codes

  • 200 OK
  • 201 Created
  • 400 Bad Request
  • 401 Unauthorized
  • 404 Not Found
  • 500 Internal Server Error

5. Gunakan Pagination

Untuk endpoint yang return banyak data:

GET /api/users?page=1&limit=10
GET /api/users?role=admin&sort=created_at&q=john

7. Error Response yang Consistent

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Email is required",
    "details": [
      {
        "field": "email",
        "message": "Email format is invalid"
      }
    ]
  }
}

8. Gunakan HTTPS

Selalu gunakan HTTPS untuk production.

9. Rate Limiting

Implement rate limiting untuk mencegah abuse:

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

10. Documentation

Selalu dokumentasikan API-mu menggunakan OpenAPI/Swagger.