REST API Design

RESTful API design principles and HTTP methods.

HTTP Methods

GET - Retrieve data
GET /api/users // Get all users
GET /api/users/123 // Get user by ID

POST - Create resource
POST /api/users
{ "name": "John", "email": "[email protected]" }

PUT - Update entire resource
PUT /api/users/123
{ "name": "John", "email": "[email protected]" }

PATCH - Partial update
PATCH /api/users/123
{ "email": "[email protected]" }

DELETE - Remove resource
DELETE /api/users/123

HTTP Status Codes

2xx Success
200 OK // Request succeeded
201 Created // Resource created
204 No Content // Success, no body

4xx Client Errors
400 Bad Request // Invalid syntax
401 Unauthorized // Authentication required
403 Forbidden // No permission
404 Not Found // Resource does not exist
422 Unprocessable Entity // Validation error

5xx Server Errors
500 Internal Server Error
502 Bad Gateway
503 Service Unavailable

URL Naming Best Practices

Use nouns, not verbs
Good: GET /users
Bad: /getUsers

Use plural nouns
Good: /users
Bad: /user

Nested resources
/users/123/posts // User posts
/users/123/posts/456 // Specific post

Filtering and sorting
/users?status=active
/users?sort=name&order=asc

Pagination
/users?page=2&limit=20
/users?offset=40&limit=20

Response Format

Success response
{
  "status": "success",
  "data": {
    "id": 123,
    "name": "John"
  }
}

Error response
{
  "status": "error",
  "message": "User not found",
  "code": "USER_NOT_FOUND"
}

Pagination metadata
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 150
  }
}