Back to Backend & APIs

Module 3: RESTful API Design

Design and implement REST APIs following industry best practices and standards.

What is REST?

REST (Representational State Transfer) is an architectural style for designing networked applications. Think of it as a set of rules for how clients and servers communicate. It's like a universal language that makes APIs predictable and easy to use.

🎯 REST Principles:

  • Client-Server: Separation of concerns
  • Stateless: Each request contains all needed info
  • Cacheable: Responses can be cached
  • Uniform Interface: Consistent API design
  • Layered System: Client doesn't know if connected to end server
  • Code on Demand: Optional - server can send executable code

HTTP Methods

GET - Read Resources

Retrieve data without modifying it. Safe and idempotent.

GET /api/users // Get all users

GET /api/users/123 // Get user by ID

GET /api/users?role>admin // Filter users

POST - Create Resources

Create new resources. Not idempotent.

POST /api/users

Body: { "name": "Alice", "email": "alice@example.com" }

Response: 201 Created

PUT - Update/Replace Resources

Replace entire resource. Idempotent.

PUT /api/users/123

Body: { "name": "Alice Updated", "email": "new@example.com" }

PATCH - Partial Update

Update specific fields. Idempotent.

PATCH /api/users/123

Body: { "email": "newemail@example.com" }

DELETE - Remove Resources

Delete resources. Idempotent.

DELETE /api/users/123

Response: 204 No Content

Resource Naming Conventions

Best Practices:

✓ Use nouns, not verbs

GET /api/users (not /api/getUsers)

✓ Use plural nouns

GET /api/users (not /api/user)

✓ Use lowercase and hyphens

GET /api/user-profiles (not /api/UserProfiles)

✓ Nested resources for relationships

GET /api/users/123/posts

GET /api/users/123/posts/456

✓ Use query params for filtering

GET /api/users?role>admin&status>active

GET /api/posts?page>2&limit>10

✗ Avoid deep nesting

Bad: /api/users/123/posts/456/comments/789/likes

Good: /api/comments/789/likes

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 data
  • 401 Unauthorized: Not authenticated
  • 403 Forbidden: No permission
  • 404 Not Found: Resource missing
  • 409 Conflict: Duplicate resource
  • 422 Unprocessable: Validation failed

5xx Server Errors

  • 500 Internal Error: Server crashed
  • 502 Bad Gateway: Invalid response
  • 503 Service Unavailable: Server down

3xx Redirection

  • 301 Moved Permanently: Resource moved
  • 304 Not Modified: Use cached version

Response Format

Consistent Response Structure:

// Success response

{

"success": true,

"data": {

"id": 123,

"name": "Alice",

"email": "alice@example.com"

},

"message": "User retrieved successfully"

}

// Error response

{

"success": false,

"error": {

"code": "USER_NOT_FOUND",

"message": "User with ID 123 not found",

"details": []

}

}

// Paginated response

{

"success": true,

"data": [/* items */],

"pagination": {

"page": 1,

"limit": 10,

"total": 100,

"totalPages": 10

}

}

API Versioning

1. URL Versioning (Recommended)

GET /api/v1/users

GET /api/v2/users

2. Header Versioning

GET /api/users

Accept: application/vnd.myapi.v1+json

3. Query Parameter

GET /api/users?version>1

HATEOAS (Hypermedia)

Include links to related resources in responses.

{

"id": 123,

"name": "Alice",

"email": "alice@example.com",

"_links": {

"self": { "href": "/api/users/123" },

"posts": { "href": "/api/users/123/posts" },

"followers": { "href": "/api/users/123/followers" }

}

}

REST API Best Practices

1. Use HTTPS

Always use HTTPS to encrypt data in transit.

2. Rate Limiting

Protect your API from abuse with rate limits.

X-RateLimit-Limit: 1000

X-RateLimit-Remaining: 999

X-RateLimit-Reset: 1640995200

3. Pagination

Always paginate large collections.

GET /api/users?page>1&limit>20

4. Filtering & Sorting

GET /api/users?role>admin&sort>name&order>asc

5. Field Selection

Let clients request specific fields.

GET /api/users?fields>name,email

6. Caching

Use ETags and Cache-Control headers.

Cache-Control: max-age>3600

ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

📚 Module Summary

You've mastered RESTful API design:

  • ✓ REST principles and constraints
  • ✓ HTTP methods and status codes
  • ✓ Resource naming conventions
  • ✓ Response format standards
  • ✓ API versioning strategies
  • ✓ Best practices (pagination, filtering, caching)

Next: Learn GraphQL as an alternative to REST!