Search Sreeni's Insights

Filter by content type
technical March 15, 2018 9 min read

Why REST and what makes an API RESTful? - Part 1

Why REST replaced WS-* services, what makes an API RESTful and the six REST constraints, with resources, URIs, verbs, safety and idempotence.

Share:

Why REST and what makes an API RESTful? - Part 1

The web is certainly the most used part of the Internet and most of the Web infrastructure relies on the HTTP protocol. Almost every application we build today either exposes an API or consumes one, so the way we design our APIs directly decides how easy they are to consume, to scale and to change. In this series, I share the REST API design guidelines and best practices which we follow in our teams. In this article, we are going to see why REST, what REST is, its constraints and the three building blocks of every RESTful API: resource, URI and verb.

REST API Design Guidelines series:

  1. Why REST and what makes an API RESTful? (this article)
  2. How to design resources and URIs for a REST API?
  3. How to use verbs, representations and status codes in a REST API?
  4. How to handle errors and secure a REST API?
  5. How to improve REST API performance and handle concurrency?
  6. How to handle long running requests, versioning, testing and documentation in a REST API?

TL;DR Summary

  • WS-* based web services bring enormous XML payloads, service specific clients and infrastructure; REST simplifies building loosely coupled APIs over plain HTTP.
  • REST is an architectural style, not a standard or protocol.
  • REST is defined by six constraints: Client-Server, Statelessness, Cacheable, Layered System, Uniform Interface and Code on Demand (optional).
  • A resource is a noun, a URI uniquely identifies the resource and a verb is the action we perform on it.
  • GET, HEAD and OPTIONS are safe; GET, PUT, DELETE, HEAD and OPTIONS are idempotent; POST is neither.
  • Safety and idempotence help clients to make reliable requests over an unreliable network.

Why REST?

There are a number of protocols and standards built on top of HTTP, designed for building Web Services, and these standards are collectively called the WS-* stack. Web services are modular, distributed, dynamic applications that can be described, published, located or invoked over the network to perform any business operation.

Building web services with WS-* standards on plain HTTP brings lots of complexity like enormous XML payloads, implementation effort, service specific clients or infrastructure, etc. Sometimes, the web services are too complex, impossible to debug and won’t work unless your clients have the exact same infrastructure setup as the service does.

Representational State Transfer (REST) simplifies designing and consuming loosely coupled APIs over HTTP. REST is an architectural style for networked applications. It consists of several constraints to address separation of concerns, visibility, reliability, scalability, performance, etc.

The term “RESTful” is like the term “object-oriented”. So, we need to consider the following design principles while designing RESTful APIs, like typical software design,

  • Separation of concerns
  • Single responsibility
  • Use nouns for resources
  • Use plural names
  • Use the right verbs
  • Semantic versioning
  • Cache on demand
  • Secure by default

We will see each of these principles in detail in this series.

What is REST (Representational State Transfer)?

REST or RESTful API design (Representational State Transfer) is designed to take advantage of the existing HTTP protocol, and it is an architectural style, not a standard or protocol. REST is protocol agnostic.

Since data is not tied to methods and resources, REST can handle multiple types of calls, return different data formats and even change structurally with the correct implementation of hypermedia.

REST Constraints

REST is defined by the following constraints, and these are the design decisions to take while you design a RESTful API.

Client-Server

Both client and server should be separated so that both can evolve separately without any dependency on each other. A client should know only the contracts. Servers and clients may also be replaced and developed independently, as long as the contract between them is not changed.

Statelessness

Make all client-server interactions stateless. The state should be contained within the request itself instead of having a separate session store or another place. The server should not store anything about the latest HTTP request the client made; it should read each request as new. No session, no history. No client context shall be stored on the server between requests. The client is responsible for managing the state of the application.

Cacheable

Caching brings performance improvement for the client side, and a better scope of scalability for a server because the load is reduced. Well-managed caching partially or completely eliminates some client-server interactions, further improving scalability and performance. Each API response message must explicitly state whether it is cacheable or not.

Layered System

A layered client-server adds proxy and gateway components to the client-server style. These additional mediator components can be added in multiple layers to add features like load balancing and security checking to the system. The “layered system” constraint is less about proxies and gateways, and more about the fact that adding one between client and server is a nearly transparent operation. A client doesn’t know whether it’s talking directly to a server, or whether it’s talking to a proxy or gateway. Clients, servers, proxies and gateways all should work with the same contract.

Uniform Interface

A resource in the API should have only one logical URI, and that should provide a way to fetch related or additional data. Client and server should communicate on shared contracts. A contract consists of the URI, method and media type for both request and response. It is an important key constraint to decouple the client from the server or vice versa. It has the following sub constraints,

  • Identification of resources - A resource should conceptually be separate from its internal representation, and it should be neither too large nor too small. By default, it should send a JSON response, and it should also support other media types depending on consumer requirements.
  • Manipulation of resources through representations - The server should expose the metadata to read, update or delete a resource.
  • Self-descriptive messages - The contract must include enough information about the request and response for the consumer to understand it in isolation. Basically, each message should have a media type to tell the receiver how to parse the response, and a meaningful URI to trigger the right business process with the right verb.
  • Hypermedia as the Engine of Application State (HATEOAS) - Hypermedia is a generalization of hypertext (links). It drives how to consume and use the API. Whenever relevant, a resource should contain links pointing to relative URIs to fetch related information.

Code on Demand (optional)

The server can extend the client functionality by sending scripts which can be executed by the client. It is a hardly used constraint and it is completely optional.

What is Resource?

In REST, resources are defined as nouns, and actions or methods as verbs. A resource can be any object associated with data and relationships to other resources (i.e. people, author, book, etc.).

Resources can be grouped as a collection. Each collection is homogeneous, so it will contain only one type of resource, and it is unordered. Resources can also exist outside any collection, and these are called singleton resources. Collections are themselves resources as well.

We can identify resources from problem domains, business processes or supportive functions. We will see this in detail in the next article.

Example:

In the mutual fund domain, Unit, Fund, Group and Universe are resources.

What is URI?

A Uniform Resource Identifier (URI) is a string of characters that unambiguously identifies a specific resource. It enables the interaction with representations of the resource over the World Wide Web (WWW).

Example:

https://api.example.com/funds/HI14
https://api.example.com/news/7655

What is Verb?

A verb is an action or method (ex: read, create, update or delete) which can be performed on a resource. The action can be reading the state of a resource, creating a resource, etc. One of the REST principles is that the client should interact with resources through a fixed set of verbs.

In REST, HTTP verbs are mapped to specific CRUD (Create, Read, Update and Delete) operations.

GET, HEAD and OPTIONS verbs are related to queries and these will not make any change at the server side, so these verbs are considered as safe. All other verbs are considered as unsafe since all of them make some changes at the server end.

Idempotence is another quality factor of a verb. The idea comes from maths, and an idempotent operation in maths is one that has the same effect when we calculate it one or more times for the same set of inputs. PUT and DELETE operations are idempotent. For example, when we delete a resource, it’s gone. If we DELETE it again, it’s still gone.

The following table shows the mapping between verbs and actions.

VerbActionIs Safe?Is Idempotent?
GETRead the current state of a resourceYesYes
POSTCreate a resourceNoNo
PUTReplace the state of a resource at the given URINoYes
PATCHUpdate specific attributes of a resource at the given URINoYes*
DELETERemove or clear a resource at the given URI. After clearing the resource, the given URI is no longer validNoYes
HEADRead metadata about a resource at the given URI without sharing the stateYesYes
OPTIONSReturn options or requirements associated with a resource, or the capabilities of the serverYesYes

Note: *The HTTP specification does not guarantee that PATCH is idempotent. It is idempotent only when you design the patch document that way (for example, “set title to X” instead of “add 1 to count”).

Why safety and idempotence are important?

Safety and idempotence help a client to make reliable API requests over an unreliable network. When you make a GET request and never get a response, just retry based on the accepted retry attempts. It’s safe: even if your earlier requests went through, it didn’t have any real effect on the server. But POST is neither safe nor idempotent, so making two identical POST requests will probably result in two resources containing the same information.

So, the rule of thumb is simple: clients can retry safe and idempotent requests freely, but they must be careful while retrying POST, and the server should validate the resource uniqueness for POST.

Wrap up

In this article, we have looked at why we need REST, what REST is, the REST constraints, and the resource, URI and verb concepts along with safety and idempotence. I really appreciate that you took the time to read this article. In the next article, I will walk you through how to identify resources, how to define the right granularity for a resource and how to design URIs for them.

Related Posts