RESTful API Design
REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful APIs use HTTP methods to perform operations on resources, making them intuitive and scalable.
REST Principles
REST CORE PRINCIPLES
====================
1. Client-Server Architecture
Client and server are separated and independent.
2. Stateless
Each request contains all information needed.
Server stores no client context between requests.
3. Cacheable
Responses must define themselves as cacheable or not.
4. Uniform Interface
Standard way to communicate (HTTP methods, URIs).
5. Layered System
Client cannot tell if connected directly to server.
HTTP Methods
+---------+--------------+-------------------+----------+
| Method | URI | Operation | Safe |
+---------+--------------+-------------------+----------+
| GET | /users | List all users | Yes |
| GET | /users/123 | Get user 123 | Yes |
| POST | /users | Create new user | No |
| PUT | /users/123 | Update user 123 | No |
| DELETE | /users/123 | Delete user 123 | No |
| PATCH | /users/123 | Partial update | No |
+---------+--------------+-------------------+----------+
Resource Naming Conventions
GOOD URL DESIGN:
================
/users (collection)
/users/123 (specific resource)
/users/123/orders (nested resource)
/users/123/orders/456 (specific nested)
BAD URL DESIGN:
===============
/getUser?id=123
/deleteUser/123
/user_list.php
/api/v1/users/get/all
Rules:
- Use nouns, not verbs
- Use plural for collections
- Use hierarchical relationships
- Keep it simple and predictable
Response Status Codes
+-------+----------------------------+------------------+
| Code | Meaning | When to Use |
+-------+----------------------------+------------------+
| 200 | OK | Successful GET |
| 201 | Created | Successful POST |
| 204 | No Content | Successful DELETE|
| 400 | Bad Request | Invalid input |
| 401 | Unauthorized | Not authenticated|
| 403 | Forbidden | Not authorized |
| 404 | Not Found | Resource missing |
| 409 | Conflict | Duplicate data |
| 500 | Internal Server Error | Server failure |
+-------+----------------------------+------------------+
Key Takeaways
- REST uses standard HTTP methods for CRUD operations
- Use resource-based URLs with nouns, not verbs
- Return appropriate HTTP status codes
- Keep APIs stateless and cacheable