Skip to content

REST API Design

A well-designed REST API makes your application intuitive, scalable, and easy to maintain. This guide covers essential patterns and conventions.

REST Principles

REST (Representational State Transfer) relies on these core ideas:

  • Resources — Everything is a resource identified by a URL
  • HTTP Methods — Use standard verbs to perform actions
  • Stateless — Each request contains all necessary information
  • Uniform Interface — Consistent URL and response patterns

HTTP Methods

MethodPurposeExample
GETRead resource(s)GET /api/users
POSTCreate a resourcePOST /api/users
PUTReplace a resourcePUT /api/users/1
PATCHPartial updatePATCH /api/users/1
DELETERemove a resourceDELETE /api/users/1

URL Design

Good URL patterns are predictable and hierarchical:

# Collection
GET    /api/articles          # List all articles
POST   /api/articles          # Create an article

# Single resource
GET    /api/articles/42       # Get article #42
PUT    /api/articles/42       # Update article #42
DELETE /api/articles/42       # Delete article #42

# Nested resources
GET    /api/articles/42/comments    # Comments on article #42

Response Structure

Use a consistent JSON envelope for all responses:

{
  "status": "success",
  "data": {
    "id": 42,
    "title": "REST API Design",
    "author": "diqitech",
    "createdAt": "2024-01-15T10:30:00Z"
  }
}

For errors:

{
  "status": "error",
  "message": "Resource not found",
  "code": "NOT_FOUND"
}

Status Codes

Use appropriate HTTP status codes:

  • 200 — Success
  • 201 — Created
  • 400 — Bad request (validation error)
  • 401 — Unauthorized
  • 404 — Not found
  • 500 — Internal server error

Pagination

For large collections, implement cursor-based or offset pagination:

GET /api/articles?page=2&limit=20
{
  "status": "success",
  "data": [...],
  "meta": {
    "page": 2,
    "limit": 20,
    "total": 156,
    "totalPages": 8
  }
}

Best Practices

  1. Use plural nouns for resource names (/users, not /user)
  2. Version your API (/api/v1/users)
  3. Filter via query params (?status=active&sort=-createdAt)
  4. Rate limit your endpoints to prevent abuse
  5. Document everything with OpenAPI/Swagger