Designing RESTful Endpoints

🔗 REST API Lesson 3 Beginner

URL design is the public contract of your API. Good endpoint design makes your API intuitive, predictable, and easy to consume. Poor design creates confusion and forces breaking changes.

1 URL Design Best Practices
  • Use nouns, not verbs: Resources are things, not actions. /users not /getUsers.
  • Use plural nouns: /products not /product.
  • Lowercase with hyphens: /blog-posts not /blogPosts or /BlogPosts.
  • Hierarchical nesting: Represent relationships: /users/42/orders.
  • Keep it shallow: No more than 3 levels deep. Beyond that, use query params.
  • No trailing slashes: /users not /users/.
  • Version your API: /api/v1/users.
2 Good vs Bad URL Examples
REST — URL Design Comparison
--- BAD ---
GET  /getAllUsers
POST /createUser
GET  /user?id=42
POST /user/delete/42
GET  /api/users/get-user-orders-by-user-id

--- GOOD ---
GET    /api/v1/users             # List all users
POST   /api/v1/users             # Create user
GET    /api/v1/users/42          # Get user 42
PUT    /api/v1/users/42          # Replace user 42
PATCH  /api/v1/users/42          # Update user 42
DELETE /api/v1/users/42          # Delete user 42
GET    /api/v1/users/42/orders   # User 42's orders
GET    /api/v1/orders/7/items    # Order 7's items

--- ACTIONS (use sparingly) ---
POST /api/v1/users/42/activate
POST /api/v1/orders/7/cancel
POST /api/v1/auth/refresh-token
3 Resource Relationships
REST — Nested Resource Patterns
# E-commerce API endpoints
GET    /api/v1/products                    # All products
GET    /api/v1/products?category=laptops   # Filter by category
GET    /api/v1/products/101                # Product detail
GET    /api/v1/products/101/reviews        # Product reviews
POST   /api/v1/products/101/reviews        # Add a review

GET    /api/v1/users/5/cart                # User cart
POST   /api/v1/users/5/cart/items          # Add to cart
DELETE /api/v1/users/5/cart/items/3        # Remove cart item
POST   /api/v1/users/5/cart/checkout       # Checkout (action)
4 Code Challenge
Challenge: Design the full set of RESTful endpoints for a blog platform that has users, posts, comments, and tags. Write out all the routes needed using correct HTTP verbs, nouns, and nesting.