What is REST?

REST is an acronym for REpresentational State Transfer and an architectural style (a named set of constraints) for distributed hypermedia systems (a system of linked documents spread over a network). Roy Fielding first presented it in 2000 in his famous dissertation. Since then, it has become one of the most widely used approaches …

REST is an acronym for REpresentational State Transfer and an architectural style (a named set of constraints) for distributed hypermedia systems (a system of linked documents spread over a network). Roy Fielding first presented it in 2000 in his famous dissertation. Since then, it has become one of the most widely used approaches for building web-based APIs (Application Programming Interfaces).

A web API that follows them is a REST API, also called a RESTful API. REST does not require HTTP, but almost every REST API uses HTTP, and so does this article.

REST -> An architectural style, a set of six constraints

REST API -> A web API that follows the REST constraints.

REST != HTTP -> REST and HTTP are not the same

The following example shows one REST interaction. The client asks for order 1001, and the server returns a representation of the current state of the order.

GET /orders/1001 HTTP/1.1              # method + resource identifier
Accept: application/json               # the client asks for the JSON media type

HTTP/1.1 200 OK                        # the result of the request
Content-Type: application/json         # the media type of the representation
Cache-Control: max-age=60              # the response is cacheable for 60 seconds

{
  "id": 1001,
  "status": "shipped",
  "total": 49.9,
  "links": {
    "self": "/orders/1001",
    "customer": "/customers/7"
  }
}

1. What Does REST Stand For?

REST stands for Representational State Transfer. In Fielding’s words, REST components perform actions on a resource by using a representation to capture the current or intended state of that resource and transferring that representation between components. A component is a program that takes part in the interaction, such as the client and the server.

Each word in the name carries one part of the idea.

  • Representational means the components exchange representations of a resource, not the resource itself. In the example, the database row of order 1001 holds the resource state and the JSON document is its representation.
  • State means the state of the resource at one moment, for example the status shipped and the total 49.90.
  • Transfer means the representation moves between components inside a request or a response, in either direction.

2. Is REST a Protocol or a Standard?

REST is neither. There is no REST specification with a version number, and no body certifies an API as RESTful. REST is an architectural style, and it ignores the details of component implementation and protocol syntax in order to focus on the roles of components, the constraints upon their interaction with other components, and their interpretation of significant data elements.

For example, HTTP is a protocol, with exact rules for the bytes on the wire. In the dissertation, HTTP is the only protocol mentioned specifically for the transfer of resource representations, and Fielding used REST to guide the design of HTTP 1.1.

This is important to understand that an API that uses HTTP is not RESTful by default. An HTTP API with URLs such as /getOrder?id=1001 and /updateOrder is valid HTTP, but it breaks the uniform interface constraint.

3. Resources, Identifiers and Representations

Fielding calls the resource, the resource identifier and the representation the data elements of REST. Unlike the distributed object style, where all data is hidden inside the processing components, the nature and state of the data elements is a key aspect of REST. A REST API is designed around the three of them.

3.1. What Is a Resource?

The key abstraction of information in REST is a resource. Any information that we can name can be a resource. For example, a REST resource can be a document or image, a temporal service, a collection of other resources, or a non-virtual object (e.g., a person).

Fielding’s example is an academic paper. The “authors’ preferred version” of the paper is a mapping whose value changes over time, whereas “the paper published in the proceedings of conference X” is static. Both are resources, and they are two distinct resources even when they point at the same file for a while.

In practice, resources come in two shapes. A collection resource holds a set of items, for example /orders. A singleton resource is one item, for example /orders/1001. A filtered collection such as /orders?status=shipped is a resource of its own. The REST resource naming page explains how to pick the names.

3.2. What Is a Resource Identifier?

REST uses resource identifiers to identify each resource involved in the interactions between the client and the server components. On the web it is a URI.

The naming authority that assigned the resource identifier is responsible for maintaining the semantic validity of the mapping over time. For example, for a web API, it is the team that owns the server. An identifier names a thing, and the control data says what to do with it.

3.3. Resource Representation

A representation is a sequence of bytes, plus representation metadata to describe those bytes. The bytes are the document, and the metadata says how to read it. The data format of a representation is called a media type, for example application/json.

One resource can have several representations at the same time, for example JSON for a mobile app, XML for an older partner system and HTML for a browser. When that happens, content negotiation selects the best one for a given message. In HTTP, the client lists the formats it accepts in the Accept header, and the server names the one it picked in the Content-Type header. The details are on the content negotiation page.

3.4. Resource Methods

Depending on the control data in the representation, a given representation may indicate the current state of the requested resource, the desired state for the requested resource, or the value of some other resource, such as an error condition.

To change a resource, the client sends a representation of the desired state. Fielding calls the operation remote authoring, where the author sends a representation to the server, which establishes a value for that resource that later requests can retrieve.

For example, in HTTP, the methods below carry the control data.

  • GET retrieves the current representation and changes nothing.
  • PUT sends the desired state of the resource at the identifier, and the server stores it there.
  • POST sends a representation to a resource, most often a collection, and the server creates a new resource and assigns its identifier.
  • PATCH sends a partial change to the desired state.
  • DELETE asks the server to remove the resource.

The dissertation does not say which HTTP method to use for which change. The constraint is only that each method has the same semantics for every resource, so a client that knows what a method does.

4. The Six Guiding Principles of REST

The dissertation derives REST by starting from an empty set of constraints and adding one at a time. Each one buys a property the web needs and costs something in return, and he names both. The first five are required. The sixth, code on demand, is optional.

The six guiding principles or constraints of the RESTful architecture are:

4.1. Uniform Interface

By applying the principle of generality to the components interface, we can simplify the overall system architecture and improve the visibility of interactions. Multiple architectural constraints help in obtaining a uniform interface and guiding the behavior of components.

The following four constraints can achieve a uniform REST interface:

  • Identification of resources – The interface must uniquely identify each resource involved in the interaction between the client and the server.
  • Manipulation of resources through representations – The resources should have uniform representations in the server response. API consumers should use these representations to modify the resource state in the server.
  • Self-descriptive messages – Each resource representation should carry enough information to describe how to process the message. It should also provide information on the additional actions that the client can perform on the resource.
  • Hypermedia as the engine of application state – The client should have only the initial URI of the application. The client application should dynamically drive all other resources and interactions with the use of hyperlinks.

In simpler words, REST defines a consistent and uniform interface for interactions between clients and servers. For example, the HTTP-based REST APIs make use of the standard HTTP methods (GET, POST, PUT, DELETE, etc.) and the URIs (Uniform Resource Identifiers) to identify resources.

4.2. Client-Server

The client-server design pattern enforces the separation of concerns, which helps the client and the server components evolve independently.

By separating the user interface concerns (client) from the data storage concerns (server), we improve the portability of the user interface across multiple platforms and improve scalability by simplifying the server components. While the client and the server evolve, we have to make sure that the interface/contract between the client and the server does not break.

Fielding calls it the most significant gain for the web, because a team can rewrite a mobile app or create new ways to interact with backend without touching the server.

4.3. Stateless

Statelessness mandates that each request from the client to the server must contain all of the information necessary to understand and complete the request. The server cannot take advantage of any previously stored context information on the server.

The client keeps the session state, such as the current page and the access token, and includes it every time it sends a request to the server.

GET /orders?page=3 HTTP/1.1            # the page number is in the request, not in a server session
Authorization: Bearer eyJhbGciOi...     # the credentials are in the request too
Accept: application/json

Statelessness improves visibility, because a monitoring tool can understand a request on its own. It improves reliability, because a crashed server held nothing that another server cannot serve. It improves scalability, because the server can free its resources after each request.

The cost is the repeated data in every request, and Fielding adds a second one. With the session on the client, correct behavior depends on every client version doing the right thing. More on the statelessness page.

4.4. Cacheable

The cacheable constraint requires that a response should implicitly or explicitly label itself as cacheable or non-cacheable. In HTTP, the label is the Cache-Control header. If the response is cacheable, the client application gets the right to reuse the response data later for equivalent requests and a specified period.

Caching can remove some interactions completely, which improves efficiency, scalability and the latency the user sees. As the dissertation puts it, the most efficient network request is one that does not use the network.

The risk is stale data, because a cache that serves an old copy gives the client a different answer than the server would have given. So the server decides the lifetime of every response. The headers are on the caching page.

4.5. Layered System

The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior. In a layered system, each component cannot see beyond the immediate layer they are interacting with.

Between the client, which Fielding calls the user agent, and the origin server that holds the resources, there can be a proxy that the client chose, a gateway (a reverse proxy) that the server side put in place, and shared caches. The client cannot tell which of them answered.

The cost is latency, because every layer handles the data once more, and a shared cache in one of the layers wins back part of that time.

A layman’s example of a layered system is the MVC pattern. The MVC pattern allows for a clear separation of concerns, making it easier to develop, maintain, and scale the application.

4.6. Code on Demand (Optional)

Code on demand lets a server extend the client by sending code, in the form of applets or scripts, for the client to run, the way a web page sends JavaScript to a browser. The downloaded code simplifies clients by reducing the number of features required to be pre-implemented. Servers can provide part of the features delivered to the client in the form of code, and the client only needs to execute the code.

The constraint is optional because downloaded code reduces visibility, and a system that spans many organizations cannot assume every client will run the code.

5. Hypermedia

Hypermedia is information that carries its own controls. Hypermedia provides a uniform means of accessing services through the embedding of action controls within the resource representation. Fielding says that an API without hypermedia is not REST, and hypermedia is what the top level adds.

“Hypertext” is the older word for the same idea with text only; “hypermedia” widens it to images, forms and any other media.

In simple words, a hypermedia document does not only tell you what something is, it also tells you what you can do next, and the “what you can do next” is carried as links and forms inside the document itself. Every addressable unit of information carries an address, either explicitly (e.g., link and id attributes) or implicitly (e.g., derived from the media type definition and representation structure).

Hypertext (or hypermedia) means the simultaneous presentation of information and controls such that the information becomes the affordance through which the user (or automaton) obtains choices and selects actions.

Remember that hypertext does not need to be HTML (or XML or JSON) on a browser. Machines can follow links when they understand the data format and relationship types.

— Roy Fielding

Consider the following REST resource that represents a blog post with links to related resources in an HTTP-based REST API. This has the necessary information about the blog post, as well as the hypermedia links to the related resources such as author and comments. Clients can follow these links to discover additional information or perform actions.

{
  "id": 123,
  "title": "What is REST",
  "content": "REST is an architectural style for building web services...",
  "published_at": "2023-11-04T14:30:00Z",
  "author": {
    "id": 456,
    "name": "John Doe",
    "profile_url": "https://example.com/authors/456"
  },
  "comments": {
    "count": 5,
    "comments_url": "https://example.com/posts/123/comments"
  },
  "self": {
    "link": "https://example.com/posts/123"
  }
}

Further, resource representations shall be self-descriptive i.e. the client does not need to know if a resource is an employee or a device. It should act based on the media type associated with the resource. So, in practice, we will create lots of custom media types – usually one media type associated with one resource.

Every media type defines a default processing model. For example, HTML defines a rendering process for hypertext and the browser behavior around each element.

Media Types have no relation to the resource methods GET/PUT/POST/DELETE/… other than the fact that some media type elements will define a process model that goes like “anchor elements with an href attribute create a hypertext link that, when selected, invokes a retrieval request (GET) on the URI corresponding to the CDATA-encoded href attribute.”

6. REST and HTTP are Not the Same

Many people prefer to compare HTTP with REST. REST and HTTP are not the same.

REST != HTTP

Though REST also intends to make the web (internet) more streamlined and standard, Roy Fielding advocates using REST principles more strictly. And that’s where people try to start comparing REST with the web.

Roy Fielding, in his dissertation, has not mentioned any implementation direction – including any protocol preference or even HTTP. As long as we are honoring the six guiding principles of REST, we can call our interface RESTful.

7. Summary

In simple words, in the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs).

The resources are acted upon by using a set of simple, well-defined operations. Also, the resources have to be decoupled from their representation so that clients can access the content in various formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others.

The clients and servers exchange representations of resources by using a standardized interface and protocol. Typically, HTTP is the most used protocol, but REST does not mandate it.

Metadata about the resource is made available and used to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. And most importantly, every interaction with the server must be stateless.

All these principles help RESTful applications to be simple, lightweight, and fast.

Happy Learning !!

References:

Comments

Subscribe
28 Comments
Most Voted
Newest Oldest