Thiết Kế API trong System Design

Tổng Quan

API design là quá trình thiết kế giao diện lập trình ứng dụng cho phép các components và services tương tác với nhau hiệu quả và nhất quán.

Nguyên Tắc RESTful

HTTP Methods

GET    /api/v1/users          # Get all users
GET    /api/v1/users/123      # Get specific user
POST   /api/v1/users          # Create new user
PUT    /api/v1/users/123      # Update user
DELETE /api/v1/users/123      # Delete user

Status Codes

Success: 200 OK, 201 Created, 204 No Content
Client Error: 400 Bad Request, 401 Unauthorized, 404 Not Found
Server Error: 500 Internal Server Error, 503 Service Unavailable

Request/Response Format

JSON Response Structure

// Success Response
{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2024-01-15T10:30:00Z"
}

// Error Response
{
  "error": "Validation failed",
  "code": "VALIDATION_ERROR",
  "details": [
    {
      "field": "email",
      "message": "Email already exists"
    }
  ]
}

API Patterns

Pagination

{
  "data": [ /* items */ ],
  "pagination": {
    "current_page": 2,
    "per_page": 20,
    "total_count": 1000,
    "has_next": true
  }
}

Filtering & Sorting

GET /api/v1/users?status=active&sort=created_at&order=desc

Security

Authentication

# JWT Token verification
def verify_token(token):
    payload = jwt.decode(token, secret_key, algorithms=['HS256'])
    return payload['user_id']

Rate Limiting

# Rate limiting implementation
def is_allowed(user_id, limit=100, window=3600):
    key = f"rate_limit:{user_id}"
    current = redis.get(key) or 0
    if int(current) >= limit:
        return False
    redis.incr(key)
    redis.expire(key, window)
    return True

Versioning

# URL versioning (recommended)
GET /api/v1/users
GET /api/v2/users

Best Practices

Naming Conventions

✅ Good: /api/v1/users (plural nouns)
❌ Bad: /api/v1/user (singular)

Error Handling

class APIError(Exception):
    def __init__(self, message, code, status_code=400):
        self.message = message
        self.code = code
        self.status_code = status_code

Documentation

  • OpenAPI/Swagger specifications
  • Interactive API explorers
  • Code examples và cURL commands
  • Authentication guides

Next Steps

Nội dung này sẽ được mở rộng thêm với: - GraphQL API design - gRPC service definitions
- WebSocket patterns - API gateway configurations