REST
Understand REST architectural principles, resource-oriented modeling, representations, HTTP verbs, status codes, statelessness, cacheability, and scalable client-server design.
Lesson goal
By the end of this lesson, you will understand REST principles, resource modeling, HTTP verbs, statelessness, and caching.
REST is an architectural style for building APIs over HTTP. It lets clients interact with server-side resources using standard HTTP methods like GET, POST, PUT, and DELETE.
The Client-Server Model
REST strictly enforces a client-server separation of concerns:
- The Client acts on resources by issuing self-contained HTTP requests.
- The Server manages resource state, enforces business rules, and returns representations of those resources in HTTP responses.
Because the client only interacts with the server through standardized representations, the client does not need to know anything about the server's internal database, storage format, or server-side architecture.
The Core Building Blocks
A REST interaction consists of four related parts:
| Part | Role | Example |
|---|---|---|
| Resource | The conceptual entity or object being worked with. | User #42, Order #1098, Article |
| HTTP Method (Verb) | Describes the intended operation on the resource. | GET, POST, PUT, PATCH, DELETE |
| Representation | The format and payload in which resource state is transferred. | JSON document, XML, form data |
| HTTP Status Code | Standardized number communicating the outcome of the request. | 200 OK, 201 Created, 404 Not Found |
The client sends an HTTP request specifying the target resource URI and the desired operation method. The server processes the request and returns an HTTP response containing a status code and an updated representation of the resource.
Resources and Representations
A fundamental principle of REST is the separation between a resource and its representation:
- Resource — the data/entity managed by the server, e.g. a user account in a database.
- Representation — the format used to send that resource over the network, e.g. JSON, XML, or HTML.
┌────────────────────────────────────────────────────────┐
│ Resource (Concept) │
│ e.g., User #42 │
└───────────────────────────┬────────────────────────────┘
│
┌───────────────┴───────────────┐
▼ ▼
┌───────────────────────┐ ┌───────────────────────┐
│ JSON Representation │ │ XML Representation │
│ {"id": 42, "name": │ │ <user id="42"> │
│ "Alice"} │ │ <name>Alice</name> │
│ │ │ </user> │
└───────────────────────┘ └───────────────────────┘Content negotiation
This separation allows a single resource to be accessed in multiple formats depending on client needs. Using standard HTTP headers, the client requests its preferred representation:
GET /api/v1/users/42 HTTP/1.1
Host: api.example.com
Accept: application/jsonThe server inspects the Accept header and returns the appropriate format along with a Content-Type response header:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 42,
"name": "Alice",
"email": "[email protected]"
}The Four Qualities of a RESTful Interface
A truly RESTful interface satisfies four uniform qualities:
┌─────────────────────────────────────────────────────────────────────────────┐
│ Four Qualities of a RESTful Interface │
├────────────────────────────────┬────────────────────────────────────────────┤
│ Quality │ Implementation in HTTP │
├────────────────────────────────┼────────────────────────────────────────────┤
│ 1. Identify Resources │ Uniform Resource Identifiers (URIs) │
│ 2. Change with Representations │ HTTP Verbs, Headers, and Request Bodies │
│ 3. Self-Descriptive Errors │ Standard HTTP Status Codes │
│ 4. HATEOAS │ Hypermedia links within representations │
└────────────────────────────────┴────────────────────────────────────────────┘1. Identify resources (URI in HTTP)
Every resource is identified by a stable, unique URI (Uniform Resource Identifier). The URI should represent the resource itself (a noun), using the same URI regardless of the operation being performed.
Avoid putting action verbs in the endpoint path:
| ❌ Non-RESTful (RPC style) | ✅ RESTful (Uniform Resource URI) |
|---|---|
/api/getUser?id=42 | GET /api/v1/users/42 |
/api/createUser | POST /api/v1/users |
/api/updateUser?id=42 | PUT /api/v1/users/42 or PATCH /api/v1/users/42 |
/api/deleteUser?id=42 | DELETE /api/v1/users/42 |
2. Change with representations (Verbs in HTTP)
Clients manipulate server resources by sending representations accompanied by standard HTTP verbs, headers, and bodies:
GET: Retrieve the current representation of a resource without modifying server state.POST: Submit a new representation to create a subordinate resource.PUT: Replace an existing resource completely with the supplied representation.PATCH: Apply partial modifications to an existing resource.DELETE: Remove the specified resource.
3. Self-descriptive error messages (Status codes in HTTP)
RESTful APIs use standard HTTP status codes rather than inventing custom error protocols:
1xx(Informational):100 Continue,101 Switching Protocols.2xx(Success):200 OK,201 Created,204 No Content.3xx(Redirection):301 Moved Permanently,302 Found,304 Not Modified.4xx(Client Error):400 Bad Request,401 Unauthorized,403 Forbidden,404 Not Found,409 Conflict.5xx(Server Error):500 Internal Server Error,502 Bad Gateway,503 Service Unavailable.
4. HATEOAS (HTML interface for HTTP)
HATEOAS means Hypermedia As The Engine Of Application State. The idea is simple: the server tells the client what actions are available by including links in the response. It's similar to a website: you don't need to know every URL beforehand—you follow the links provided by the page.
{
"id": 42,
"name": "Alice",
"status": "active",
"_links": {
"self": { "href": "/api/v1/users/42" },
"orders": { "href": "/api/v1/users/42/orders" },
"deactivate": { "href": "/api/v1/users/42/deactivate", "method": "POST" }
}
}By including links, the client does not need to hardcode transition URLs across application versions.
Statelessness and Cacheability
Two core architectural constraints give REST its power in distributed systems:
1. Stateless communication
Each request must contain everything the server needs to process it (including authentication credentials, parameters, and payloads). The server does not remember previous requests.
Request 1: [Token: ABC] GET /api/users/42
Request 2: [Token: ABC] GET /api/orders Each request is handled independently. The server stores no client session context between requests.
Why statelessness matters:
- Scaling: Any server can handle any request.
- Reliability: If one server fails, another can handle the next request.
- Simplicity: Requests are easier to debug and monitor.
2. Cacheable responses
REST responses should indicate whether they can be cached.
HTTP headers like Cache-Control, ETag, and Last-Modified help clients and proxies cache responses, which reduces server load and improves response time.
Code Example: A Complete REST Interaction
// 1. Identify Resource URI & 2. Express Verb (POST)
const response = await fetch("https://api.example.com/v1/users", {
method: "POST",
headers: {
// 3. Define Representation format and metadata
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer token_xyz",
},
body: JSON.stringify({
name: "Alice",
email: "[email protected]",
}),
});
// 4. Verify HTTP Status Code
if (response.status === 201) {
const newUser = await response.json();
console.log("Created user representation:", newUser);
} else {
console.error(`Request failed with status ${response.status}`);
}Key Takeaways
- REST is an architectural style for building APIs over HTTP, where clients interact with server-side resources.
- Resource vs. Representation: A resource is the actual entity; a representation is how it is sent, usually as JSON.
- Four REST principles:
- Identify resources: Use URLs to name resources, usually as nouns.
- Use HTTP methods:
GET,POST,PUT,PATCH,DELETEdescribe the operation. - Use standard status codes:
2xxfor success,4xxfor client errors,5xxfor server errors. - HATEOAS: Responses can include links that tell the client what actions are available.
- Stateless: Each request contains everything the server needs. The server does not remember previous requests.
- Cacheable: Responses can define caching rules to reduce server load and improve performance.