7.2. What Is REST?
Table of Contents
Understanding REST
REST is a way to design and build web APIs that is simple, predictable, and easy to use. You will use REST ideas all the time as a backend developer, especially when building HTTP APIs.
This chapter explains what REST is, what it is not, and the key ideas you need before you design any REST API.
REST as an Architectural Style
REST stands for Representational State Transfer. It is not a protocol and not a library. REST is an architectural style for designing networked applications, especially APIs over HTTP.
An architectural style is a set of rules and constraints that guide how you structure and connect different parts of a system. REST says:
- Use HTTP as it was designed.
- Model your data as resources.
- Manipulate resources using standard HTTP methods.
- Make your API stateless and cache friendly.
You can build a REST API in any language or framework, as long as you follow these ideas.
REST is an architectural style, not a standard or protocol.
If someone says "Our API is RESTful," they mean "We try to follow REST ideas."
REST and HTTP
REST works very naturally with HTTP, which you already saw in earlier chapters.
Key points about using HTTP in a RESTful way:
- URI identifies a resource
Example: GET /users/123identifies user with ID123GET /products/42identifies product with ID42- HTTP method describes what you want to do with that resource
Typical methods:GET,POST,PUT,PATCH,DELETE - HTTP status code describes the result of the operation
Examples:200 OK,201 Created,404 Not Found,400 Bad Request - HTTP headers and body carry metadata and data
Examples:Content-Type: application/jsonand JSON in the body.
REST does not change HTTP. It simply says: use HTTP as it was intended, instead of inventing your own "action" mechanisms.
Bad, non RESTful idea:
POST /doAction
{
"action": "createUser",
"data": { "name": "Alice" }
}Better, more RESTful approach:
POST /users
{
"name": "Alice"
}
Here the resource is /users and the HTTP method POST already means "create something."
The Core REST Constraints
REST is defined by a small set of constraints. If you respect them, your API is more likely to be simple, scalable, and cacheable.
The main REST constraints are:
- Client Server
- Stateless
- Cacheable
- Uniform Interface
- Layered System
- (Optional) Code on Demand
We will focus on the ones that matter most for web APIs you will build.
1. Client Server
The client and server are separate. They communicate over HTTP, but they do not need to know each other's internal details.
- The client does not care how the server stores data, which database it uses, or what programming language it is written in.
- The server does not care how the client shows data to the user, whether as a web page, mobile app, or CLI.
This separation:
- Makes it easier to change the frontend without changing the backend.
- Makes it easier to change the backend technology without changing clients, as long as the API stays the same.
Example:
- Today your frontend is a React web app.
- Tomorrow you add a mobile app that calls the same REST API.
- The backend does not change, only the clients.
2. Stateless
Stateless means that each request from a client to a server must contain all the information needed to understand and process the request. The server does not store client session data between requests.
In practice:
- The server does not remember "who you are" by default.
- The client includes everything the server needs in each request, for example:
- Authentication token in the
Authorizationheader - Parameters in the path or query string
- Request body with the necessary data
Non stateless approach:
- Client:
POST /loginwith credentials
Server: "OK, you are user 123" and stores session in memory. - Client:
GET /profilewithout any ID or token
Server: Uses in memory session to know that this is user 123.
More stateless approach:
- Client:
POST /loginwith credentials
Server: returns a token that represents the user. - Client:
GET /profilewith headerAuthorization: Bearer <token>
Server: Reads token, identifies user, and returns profile. No in memory session is required.
RESTful APIs are stateless. Every request must contain all information required to handle it.
Stateless design helps with:
- Scalability. Any server instance can handle any request, because it does not depend on local session memory.
- Reliability. If one server goes down, another can continue without losing user state.
Note: Many real systems still use sessions, but REST encourages you to minimize server side state.
3. Cacheable
REST encourages you to use caching to improve performance.
- Responses should say whether they are cacheable, and for how long, using HTTP headers.
- A cached response can be reused for later, identical requests.
Typical examples:
GET /products/42might be cacheable for 60 seconds, since product data does not change every millisecond.GET /weather?city=Londonmight be cacheable for 10 minutes.
Examples of HTTP headers that affect caching:
Cache-Control: max-age=60, public
ETag: "abc123"
Last-Modified: Tue, 27 Aug 2024 10:00:00 GMTIf you follow REST and use proper HTTP caching headers, you get better performance with less server load.
4. Uniform Interface
The uniform interface is the core idea of REST. It means:
- Use a single, consistent way to identify and interact with resources.
- Use HTTP methods consistently.
- Use standard status codes.
- Use consistent representations and links.
This has several sub-ideas.
Resource based
In REST you think in terms of resources, not actions.
A resource is anything that can be identified and manipulated. Examples:
- User
- Product
- Order
- Blog post
- Comment
Each resource has a URI:
/users/users/123/products/products/42/reviews
You focus on nouns, not verbs in the URL.
Not RESTful style:
POST /createUserPOST /deleteUserPOST /updateUser
More RESTful style:
POST /usersto createDELETE /users/123to deletePUT /users/123orPATCH /users/123to update
Manipulation of resources through representations
Clients do not work with the resource directly. They work with a representation of the resource, usually JSON.
For example, the resource might be "user 123 in the database," but the representation you send in the HTTP response is JSON:
{
"id": 123,
"name": "Alice",
"email": "alice@example.com"
}The client sends representations in requests to create or update resources.
Example:
PUT /users/123
Content-Type: application/json
{
"name": "Alice Johnson",
"email": "alice@example.com"
}The server updates the underlying resource using this representation.
Self descriptive messages
Each HTTP request and response should be self descriptive. That means you can understand it without extra hidden context.
- HTTP method shows the intent.
- URI shows the resource.
- Headers clarify metadata, such as content type or authentication.
- Body contains the data.
Example response:
HTTP/1.1 201 Created
Content-Type: application/json
Location: /users/123
{
"id": 123,
"name": "Alice",
"email": "alice@example.com"
}From this message, you can see:
- The operation succeeded and created something (
201 Created). - The new resource is at
/users/123(Location header). - The representation is JSON (Content-Type).
- The content of the resource is shown in the body.
HATEOAS (Hypermedia as the Engine of Application State)
This is the strictest part of REST and many practical APIs do not fully implement it.
HATEOAS means the API provides links inside responses to show what you can do next.
Example:
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"_links": {
"self": { "href": "/users/123" },
"orders": { "href": "/users/123/orders" },
"update": { "href": "/users/123", "method": "PATCH" }
}
}The idea:
- The client does not need to hardcode paths for every action.
- The client can follow links provided by the server.
In real life, many APIs are called "RESTful" but ignore HATEOAS. That is common, and usually acceptable, but keep in mind that strict REST includes this concept.
5. Layered System
A REST API can use layers between the client and the actual server, such as:
- Load balancers
- Caches
- Reverse proxies
- Gateways
Clients do not need to know if they talk to the real server or an intermediary.
This is important for:
- Scaling your backend.
- Adding caching layers.
- Adding API gateways and security layers.
Example:
Client → API Gateway → Backend Services → Database
From the client's point of view, it still calls https://api.example.com/users, and does not care how many layers exist behind that URL.
6. Code on Demand (Optional)
REST allows, but does not require, the server to send executable code to the client.
Example:
- Server sends JavaScript to a web browser that runs on the client side.
In modern web APIs, this is usually not relevant, especially for mobile or backend to backend APIs. You can safely ignore this constraint for most backend REST API work.
REST vs "RESTful" APIs
Many APIs call themselves REST APIs or RESTful APIs even if they only follow some of the REST ideas.
Typical properties of an API that people call "RESTful":
- Uses HTTP.
- Uses resource based URLs with nouns.
- Uses HTTP methods (
GET,POST,PUT,PATCH,DELETE) logically. - Returns JSON.
- Uses proper HTTP status codes.
Many of these APIs:
- Are not fully stateless, or
- Do not use HATEOAS, or
- Have URLs with verbs or custom patterns at times.
You do not need to be a "REST police officer." Your goal as a backend developer is:
- Understand the original REST ideas.
- Apply them in a practical, consistent way.
- Make your API clear and predictable for clients.
Examples of RESTful Interactions
To make the ideas concrete, here are some common API interactions and how they look in a RESTful style.
Example: Users Resource
Assume we have a User resource.
| Action | HTTP Method | URL | Request Body | Response Status |
|---|---|---|---|---|
| List users | GET | /users | None | 200 OK |
| Create a new user | POST | /users | JSON with user data | 201 Created |
| Get one user | GET | /users/123 | None | 200 OK or 404 |
| Replace a user | PUT | /users/123 | Full JSON representation | 200 OK or 204 |
| Update part of user | PATCH | /users/123 | Partial JSON representation | 200 OK or 204 |
| Delete a user | DELETE | /users/123 | None | 204 No Content |
Example requests and responses:
1. List users
GET /users HTTP/1.1
Host: api.example.com
Accept: application/jsonHTTP/1.1 200 OK
Content-Type: application/json
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]2. Create user
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"name": "Charlie"
}HTTP/1.1 201 Created
Content-Type: application/json
Location: /users/3
{
"id": 3,
"name": "Charlie"
}3. Get user
GET /users/3 HTTP/1.1
Host: api.example.com
Accept: application/jsonHTTP/1.1 200 OK
Content-Type: application/json
{
"id": 3,
"name": "Charlie"
}4. Delete user
DELETE /users/3 HTTP/1.1
Host: api.example.comHTTP/1.1 204 No ContentThese examples show how REST uses HTTP methods and status codes to express intent and results, without inventing custom actions.
REST Compared to Other Styles
You may hear about other API styles. REST is not the only one.
Some examples:
- RPC (Remote Procedure Call)
Focuses on calling functions or procedures, often with verb oriented endpoints.
Example:POST /CreateUser,POST /SendEmail. - GraphQL
A query language for APIs. The client asks exactly for the data it needs.
Usually uses a single endpoint likePOST /graphql. - gRPC
Uses Protocol Buffers and HTTP/2. Very efficient for service to service communication.
REST is simple, human readable, and works very well with HTTP. This is why it is the most common style for public web APIs and for many backend systems.
Benefits of REST for Backend Developers
Using REST ideas in your backend gives you:
- Simplicity
URLs map to resources, methods map to actions. Easy to reason about. - Predictability
API clients can guess endpoints and behavior more easily. - Scalability
Stateless constraint and layered system make scaling simpler. - Interoperability
Any HTTP capable client can use your API, from web browsers to IoT devices. - Reuse of HTTP features
You get caching, status codes, headers, security mechanisms, and tools "for free."
If you use HTTP, you should usually design your API in a RESTful way to benefit from HTTP's features and conventions.
What You Need to Remember Now
For now, you do not need to memorize every theoretical detail of REST. Instead, remember these practical points:
- Think in resources (nouns) and use meaningful URIs.
- Use appropriate HTTP methods for each operation.
- Make each request self contained and avoid hidden server state.
- Use correct HTTP status codes.
- Make responses self descriptive, with clear headers and JSON bodies.
- Design your API so it can be cached when appropriate.
In the next chapters, you will apply these ideas to design resources, endpoints, and HTTP methods for real REST APIs.
Views: 10
KAHIBARO