REST Fundamentals
REST (Representational State Transfer) is an architectural style for building web APIs. It's the most common approach for creating HTTP-based services that allow clients to interact with your application. In this lesson, you'll learn the core principles of REST and how to design good APIs.
What is REST?
REST is a set of architectural constraints for building web services:
- Client-Server: Separation between client and server
- Stateless: Each request contains all needed information
- Cacheable: Responses can be cached
- Uniform Interface: Consistent way to interact with resources
- Layered System: Client doesn't know if it's connected directly to the server
A RESTful API uses HTTP methods to perform operations on resources, identified by URLs.
Resources and URLs
In REST, everything is a resource. Resources are identified by URLs:
/users - Collection of users
/users/123 - Specific user with ID 123
/users/123/orders - Orders belonging to user 123
/orders/456 - Specific order
HTTP Methods
REST APIs use HTTP methods to indicate the action to perform:
| Method | Purpose | Idempotent | Request Body |
|---|---|---|---|
| GET | Retrieve resource(s) | Yes | No |
| POST | Create new resource | No | Yes |
| PUT | Replace entire resource | Yes | Yes |
| PATCH | Partial update | Yes | Yes |
| DELETE | Remove resource | Yes | No |
Idempotency
An operation is idempotent if performing it multiple times has the same effect as performing it once:
GET /users/123 - Always returns same user
DELETE /users/123 - First call deletes, subsequent calls do nothing
POST /users - Each call creates a NEW user (not idempotent)
HTTP Status Codes
Status codes tell clients what happened with their request:
2xx - Success
200 OK // Request succeeded
201 Created // Resource created successfully
204 No Content // Success, no body to return
3xx - Redirection
301 Moved Permanently // Resource moved
304 Not Modified // Cached version is still valid
4xx - Client Errors
400 Bad Request // Invalid request data
401 Unauthorized // Authentication required
403 Forbidden // Not allowed (even if authenticated)
404 Not Found // Resource doesn't exist
405 Method Not Allowed // Wrong HTTP method
409 Conflict // Conflict with current state
422 Unprocessable // Validation errors
5xx - Server Errors
500 Internal Server Error // Generic server error
502 Bad Gateway // Upstream server error
503 Service Unavailable // Server temporarily unavailable
Request and Response Structure
Request
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGc...
{
"name": "Alice",
"email": "alice@example.com"
}
Components:
- Method: POST
- URL: /api/users
- Headers: Content-Type, Authorization
- Body: JSON data
Response
HTTP/1.1 201 Created
Content-Type: application/json
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"createdAt": "2024-01-15T10:30:00Z"
}
Components:
- Status Code: 201 Created
- Headers: Content-Type
- Body: JSON with created resource
Designing a REST API
1. Identify Resources
What are the main entities in your application?
// E-commerce example
const resources = [
'users', // User accounts
'products', // Product catalog
'orders', // Customer orders
'reviews', // Product reviews
'categories', // Product categories
];
2. Define Endpoints
Map HTTP methods to operations:
// Users resource
GET /users // List all users
GET /users/:id // Get one user
POST /users // Create user
PUT /users/:id // Update user
DELETE /users/:id // Delete user
// Nested resources
GET /users/:id/orders // User's orders
POST /users/:id/orders // Create order for user
3. Define Request/Response Formats
// POST /users
// Request:
{
"name": "Alice",
"email": "alice@example.com"
}
// Response (201 Created):
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"createdAt": "2024-01-15T10:30:00Z"
}
Query Parameters
Use query parameters for filtering, sorting, and pagination:
GET /products?category=electronics # Filter by category
GET /products?minPrice=100&maxPrice=500 # Price range
GET /products?sort=price&order=asc # Sorting
GET /products?page=2&limit=20 # Pagination
GET /products?search=laptop # Search
API Response Formats
Success Response
{
"data": {
"id": 123,
"name": "Alice"
}
}
Error Response
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Email is required",
"details": [
{ "field": "email", "message": "Email is required" }
]
}
}
Collection Response
{
"data": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
],
"meta": {
"total": 100,
"page": 1,
"limit": 20,
"pages": 5
}
}
API Versioning
Always version your API to allow for changes without breaking clients:
/api/v1/users
/api/v2/users
# Or using headers
Accept: application/vnd.myapi.v1+json
Best Practices
1. Use Consistent Naming
// Good - consistent plural nouns
/users
/products
/orders
// Bad - mixed styles
/user
/getProducts
/order-list
2. Handle Errors Gracefully
// Always return helpful error messages
{
"error": {
"code": "USER_NOT_FOUND",
"message": "User with ID 123 was not found",
"status": 404
}
}
3. Use Appropriate Status Codes
// Don't just use 200 for everything!
res.status(201).json(createdUser); // Created
res.status(204).end(); // Deleted (no content)
res.status(400).json({ error: 'Invalid data' });
res.status(404).json({ error: 'Not found' });
4. Document Your API
Use tools like:
- OpenAPI/Swagger
- Postman Collections
- API Blueprint
Common API Patterns
HATEOAS (Hypermedia)
Include links to related resources:
{
"id": 123,
"name": "Alice",
"links": {
"self": "/users/123",
"orders": "/users/123/orders",
"profile": "/users/123/profile"
}
}
Bulk Operations
// Create multiple resources
POST /users/bulk
[
{ "name": "Alice" },
{ "name": "Bob" }
]
// Delete multiple resources
DELETE /users?ids=1,2,3
Key Takeaways
- REST uses HTTP methods for CRUD operations
- Resources are identified by URLs (nouns, not verbs)
- Use appropriate HTTP status codes
- Stateless - each request contains all needed information
- Use query parameters for filtering, sorting, pagination
- Return consistent response formats
- Version your API
- Document your API thoroughly
Summary
You've learned the fundamentals of REST API design, including how to structure URLs, use HTTP methods correctly, and return appropriate status codes. These principles will guide you in building well-designed APIs that are easy for clients to use and understand.
Next, you'll put these principles into practice by building CRUD endpoints.

