REST Architectural Constraints

REST defines 6 architectural constraints which make any web service – a truly RESTful API i.e. Uniform interface, Client–server, Stateless, Cacheable, Layered system, Code on demand (optional).

REST stands for Representational State Transfer, a term coined by Roy Fielding in 2000. It is an architecture style for designing loosely coupled applications over the network, that is often used in the development of web services.

REST does not enforce any rule regarding how it should be implemented at the lower level, it just puts high-level design guidelines and leaves us to think of our own implementation.

In my last employment, I designed RESTful APIs for a major telecom company for two good years. In this post, I will be sharing my thoughts apart from standard design practices. You may not agree with me on a few points, and that’s perfectly OK. I will be happy to discuss anything with you with an open mind.

Let’s start with standard design-specific stuff to clarify what ‘Roy Fielding’ wants us to build. Then we will discuss my thoughts, which will be more towards finer points while you design your RESTful APIs.

Architectural Constraints

REST defines 6 architectural constraints that make any web service – a truly RESTful API.

  1. Uniform interface
  2. Client-server
  3. Stateless
  4. Cacheable
  5. Layered system
  6. Code on demand (optional)

1. Uniform interface

As the constraint name itself applies, you MUST decide APIs interface for resources inside the system which are exposed to API consumers and follow religiously. A resource in the system should have only one logical URI, and that should provide a way to fetch related or additional data. It’s always better to synonymize a resource with a web page.

Any single resource should not be too large and contain each and everything in its representation. Whenever relevant, a resource should contain links (HATEOAS) pointing to relative URIs to fetch related information.

Also, the resource representations across the system should follow specific guidelines such as naming conventions, link formats, or data format (XML or/and JSON).

All resources should be accessible through a common approach such as HTTP GET and similarly modified using a consistent approach.

Once a developer becomes familiar with one of your APIs, he should be able to follow a similar approach for other APIs.

2. Client-server

This constraint essentially means that client applications and server applications MUST be able to evolve separately without any dependency on each other. A client should know only resource URIs, and that’s all. Today, this is standard practice in web development, so nothing fancy is required from your side. Keep it simple.

Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered.

3. Stateless

Roy fielding got inspiration from HTTP, so it reflected in this constraint. Make all client-server interactions stateless. The server will not store anything about the latest HTTP request the client made. It will treat every request as new. No session, no history.

If the client application needs to be a stateful application for the end-user, where the user logs in once and does other authorized operations after that, then each request from the client should contain all the information necessary to service the request – including authentication and authorization details.

No client context shall be stored on the server between requests. The client is responsible for managing the state of the application.

4. Cacheable

In today’s world, the caching of data and responses is of utmost importance wherever they are applicable/possible. The webpage you are reading here is also a cached version of the HTML page. Caching brings performance improvement for the client side and better scope for scalability for a server because the load has been reduced.

In REST, caching shall be applied to resources when applicable, and then these resources MUST declare themselves cacheable. Caching can be implemented on the server or client side.

Well-managed caching partially or completely eliminates some client-server interactions, further improving scalability and performance.

5. Layered system

REST allows you to use a layered system architecture where you deploy the APIs on server A, and store data on server B and authenticate requests in Server C, for example. A client cannot ordinarily tell whether it is connected directly to the end server or an intermediary along the way.

6. Code on demand (optional)

Well, this constraint is optional. Most of the time, you will be sending the static representations of resources in the form of XML or JSON. But when you need to, you are free to return executable code to support a part of your application, e.g., clients may call your API to get a UI widget rendering code. It is permitted.

All the above constraints help you build a truly RESTful API, and you should follow them. Still, at times, you may find yourself violating one or two constraints. Do not worry; you are still making a RESTful API – but not “truly RESTful.”

Notice that all the above constraints are most closely related to WWW (the web). Using RESTful APIs, you can do the same thing with your web services that you do to web pages.

Happy Learning !!

Comments

Subscribe
Notify of
guest
45 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Oleksii

The main point of the Client-Server section is that it separates concerns and thus allows the development of clients and servers independently. However, to reach this separation, all we need is a contract between parts in our system. And the parts don’t necessarily have to be separated on clients and servers. For example, if we have contracts in the pub/sub model, publishers and subscribers can evolve independently as well. Or even in a duplex RPC, every part can evolve independently as long as the interface between them is not altered.

Maybe, I didn’t understand something, but it seems to me that the topic of the Client-Server constraint is not covered.

Ardi

I like this statement so much, it will be tattooed on my mind all the time:

“Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered.”

Thanks for creating this complete guide as well, super useful!

Zane

How can caching be implemented on the server or client side when no session info is allowed to be stored on the server?

Zane Karl

Hi Admin, Could you elaborate a little? Are you implying that what is cached by the Server is not session info? I mean of course the client and server are different things, but the only worthwhile information I can see being cached by the server is session info about the client making the request. My confusion comes from the discussions about REST Servers being simultaneously “Stateless” and “Cacheable”, because, the way I read it, Servers cannot store client session info, by “Stateless”ness, but Servers can store Client session info, by “Cache”ability. Could you right whatever misunderstanding I have here please?

Mike Patton

Hey Zane,
One example is that you can store the data being returned from the API, which is agnostic of who requests it. Something such as the NFL schedule. Or stats for the Payton Manning’s last game.

Most often, this is useful for very common requests and request parameters. In this way, your API doesn’t have to go back into the DB, or even worse calculate, these numbers over and over again as 1000 calls are coming in. It simply serves up the same data from cache that was served up less than a second ago.

Hope that helps!

Nitin

Key thing to remember is that – Every Resource has a unique URL, now if user A request it or user B, one can cache the resource and return the same representation irrespective of who is calling.

ray vahab

can I get a Rest API for my WP site that does booking airlines and hotels?
A developer said that I can not get API on WP platform

Brett

You could just add your own PHP scripts to your WP site and design your own Rest API that way.

Harsha N Hegde

In “Uniform Interface” section, there is an absolute statement: ” It’s always better to synonymize a resource with a web page.”
Say, I have a webpage on a shopping website showing my past purchases on the right and purchase recommendations in the middle and my profile info at the top . Does the statement above mean that my resource should get me all three items?
The general practice in RESTFul design is to designate each resource by a noun. But we got three nouns here – order history, recommendations & profile. Thoughts?

Paul

“All above constraints help you build a truly RESTful API and you should follow them. Still, at times you may find yourself violating one or two constraints. Do not worry, you are still making a RESTful API – but not “truly RESTful”

This is completely not true. The only constraint which is optional is code on demand all the other constraints are required otherwise it is not REST.

“Notice that all the above constraints are most closely related to WWW (the web).”
This is misleading. REST is describing the web. Before REST the architecture of the web was more or less non-existent. REST was designed to map closely to what was already there BUT enable future improvement as long as it didn’t break any of the constraints of REST.

Volpe Gentile

Sorry, but imho Paul is right. How about “not truly (or ‘not true’) (a) car”? It’s close to a car, though it has two wheels? Or it is a REST or it is not REST. “Not truly” does not tell us anything useful – we can’t even quantify how close to REST.
Which term? The only term, when talking about REST compliance, can be “not RESTful”.

As for the Web vs Http vs Rest, I am going to take a rest from totalizing REST.

As for the rest, I enjoyed learning from your article. Thanks.

Nitin

Ideally yes, but look at it practically. Non of the applications built today has its application state driven solely by hypermedia. Even if you manage to write a good HATEOAS API, your front-end is still not built to function only based on the REST responses.
today, only browsers are the only client which achieves to manage such flexibility but it also depends on HTML syntaxes to decide on key constructs

buddhika

This made a very useful foundation for me to start exploring web services. Thank you so much.

Abdul

Its good article on REST, could you explain all phases in detail one client request to REST endpoint.

Thanks in advance

Sivan

Thanks for a such precise explanation. A quick read with a a very quick win. A must read for Api developers.

Stuart Wilson

As I’m new to API’s this really gave me the explanation I needed to the meaning of REST. Thank you.

Ravi

RESTApi is over http, it could accessed by browser. How to restrict access to users? How authentication happens and how authenticated information is passed over API for subsequent calls.

Eric Johnson

@Ravi I have found JSON Web Tokens (JWTs) great for authentication/authorization when implementing RESTful API. https://jwt.io/

Akber Ali

you can use OAuth, API Key (public /private) or other authentication system.

Pradeep Godse

Do we have any restrictions on the size of data posting to api. Is there any limit. Can you please let me know.

arun

As already mentioned, HTTP itself doesn’t impose any hard-coded limit on request length; but browsers have limits ranging on the 2kb – 8kb (255 bytes if we count very old browsers).

Is there a response error defined that the server can/should return if it receives a GET request exceeds this length?

That’s the one nobody has answered.

HTTP 1.1 defines Status Code 414 Request-URI Too Long for the cases where a server-defined limit is reached. You can see further details on RFC 2616.

For the case of client-defined limits, there is no sense on the server returning something, because the server won’t receive the request at all.

Browser Address bar document.location
or anchor tag
——————————————
Chrome 32779 >64k
Android 8192 >64k
Firefox >64k >64k
Safari >64k >64k
IE11 2047 5120
Edge 16 2047 10240

Hope this helps.

SwethaRani Kobbanna

Excellent, Excellent Tutorial. Cannot get a better view of RESTful than this. It is simple and easily understandable. Good to start for beginners to make a hit in the RESTful world.

Prem Kumar

Hello Team,

I have a question regarding limitation of Parameters processing between Request and Response.
Can we send 100 or more as request parameters. If yes how does the system perform and what challenges we will be facing in terms of resource consumption. If no, how does the caching help in this regard

Raju

In the contraint cachaeble it is written “Caching can be implemented on server or client side”. If chaching is done on Server side, does it not break the Stateless contraint?

What I understand from stateless is the server should forget what request came after it sends the response. So if server caches, then it would remember the previous requests.. so it is no more stateless..

Please help me understand. I am trying to understand the concept. I am an SAP ABAP developer who is trying to learn OData which uses RESTful architecture.

Regards,
Raju.
http://www.sapyard.com

Anonymous

This really isn’t explained very well. Your original explanation says nothing about “state-transition information”, it just says that in order to be stateless, the server shouldn’t remember anything about prior requests, well obviously caching does just that, it causes the server to “remember” the state of a client’s previous request.

This really needs a deeper explanation, with concrete examples of what violates the stateless constraint, and why caching does not violate the constraint.

Nitin

Statelessness – Really means when 2 requests arrive at the server, the server doesn’t know if this request is a continuation of prior request or not. Every request is a fresh request for the server to handle. It doesn’t need to remember – ah , this client called for second time, let me give him something extra.

Caching – a capability not dependent on statelessness. Rather, a stateful application is hard to cache as it needs to remember what to return based on user interaction.

This 2 principles gives the web the scale what we witness today otherwise it is impossible to scale a system which is stateful and which also supports caching for all its resources.

应琪瑜

stateless is the state of application, cachable is the cache of client quest and server response, they are at diffrent field, so you may can not compare between them.

Ankur

What exactly is a resource? Can the endpoint url considered as a resource ?

John

Very nice explanation.
I just have one question about Stateless. The second paragraph of “Stateless” section which is “If client application need to be a stateful application …”

My question, each time the client sends a request, the server will go to the database and check if this user authenticated and authorized?

Thanks in advance.

Suresh

Hi, a question about ‘cacheable’, is it just about declaring whether is it cacheable or not or supporting the cache on both ends ? This point is little fuzzy in the article apparently. Thanks in advance!

Suresh

Rajan

Nice explanation.

Shronika Brihan

You are doing a Wonderful Job Lokesh !! 😀

Sundar Patil

Great explanation….
I really understood ground up…