• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

REST API Tutorial

  • REST
  • JSON
  • Dark Mode

What is REST

REST is acronym for REpresentational State Transfer. It is architectural style for distributed hypermedia systems and was first presented by Roy Fielding in 2000 in his famous dissertation.

Like any other architectural style, REST also does have it’s own 6 guiding constraints which must be satisfied if an interface needs to be referred as RESTful. These principles are listed below.

Guiding Principles of REST

  1. Client–server – By separating the user interface concerns from the data storage concerns, we improve the portability of the user interface across multiple platforms and improve scalability by simplifying the server components.
  2. Stateless – Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.
  3. Cacheable – Cache constraints require that the data within a response to a request be implicitly or explicitly labeled as cacheable or non-cacheable. If a response is cacheable, then a client cache is given the right to reuse that response data for later, equivalent requests.
  4. Uniform interface – By applying the software engineering principle of generality to the component interface, the overall system architecture is simplified and the visibility of interactions is improved. In order to obtain a uniform interface, multiple architectural constraints are needed to guide the behavior of components. REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.
  5. Layered system – The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior such that each component cannot “see” beyond the immediate layer with which they are interacting.
  6. Code on demand (optional) – REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts. This simplifies clients by reducing the number of features required to be pre-implemented.

Resource

The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service, a collection of other resources, a non-virtual object (e.g. a person), and so on. REST uses a resource identifier to identify the particular resource involved in an interaction between components.

The state of the resource at any particular timestamp is known as resource representation. A representation consists of data, metadata describing the data and hypermedia links which can help the clients in transition to the next desired state.

The data format of a representation is known as a media type. The media type identifies a specification that defines how a representation is to be processed. A truly RESTful API looks like hypertext. 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).

According to Roy Fielding:

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.

Further, resource representations shall be self-descriptive: the client does not need to know if a resource is employee or device. It should act on the basis of media-type associated with the resource. So in practice, you will end up creating lots of custom media-types – normally 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. It has 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.”

Resource Methods

Another important thing associated with REST is resource methods to be used to perform the desired transition. A large number of people wrongly relate resource methods to HTTP GET/PUT/POST/DELETE methods.

Roy Fielding has never mentioned any recommendation around which method to be used in which condition. All he emphasizes is that it should be uniform interface. If you decide HTTP POST will be used for updating a resource – rather than most people recommend HTTP PUT – it’s alright and application interface will be RESTful.

Ideally, everything that is needed to change the resource state shall be part of API response for that resource – including methods and in what state they will leave the representation.

A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand).
[Failure here implies that out-of-band information is driving interaction instead of hypertext.]

Another thing which will help you while building RESTful APIs is that query based API results should be represented by a list of links with summary information, not by arrays of original resource representations because the query is not a substitute for identification of resources.

REST and HTTP are not same !!

A lot of people prefer to compare HTTP with REST. REST and HTTP are not same.

REST != HTTP

Though, because REST also intends to make the web (internet) more streamline and standard, he advocates using REST principles more strictly. And that’s from where people try to start comparing REST with web (HTTP). Roy fielding, in his dissertation, nowhere mentioned any implementation directive – including any protocol preference and HTTP. Till the time, you are honoring the 6 guiding principles of REST, you can call your interface RESTful.

In simplest 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. The clients and servers exchange representations of resources by using a standardized interface and protocol – typically HTTP.

Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. And most importantly, every interaction with a resource is stateless.

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

References:

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

Was this article helpful?

Reader Interactions

Comments

  1. Ravan says

    May 31, 2020 at 8:56 pm

    Can we say “If an API is following 6 guiding Principles of REST then it’s a RESTful API”?

    Reply
    • Admin says

      June 3, 2020 at 7:03 am

      Yes

      Reply
      • Jay says

        December 30, 2020 at 8:52 pm

        The original sentence, “Till the time, you are honoring the 6 guiding principles of REST, you can call your interface RESTful” threw me. I interpret it to mean “Unless you honor the six guiding principles of REST, you cannot call your interface RESTful.” Rowan’s text is equally clear.

        Why not change the webpage text to make it clearer?

        Reply
        • Admin says

          January 4, 2021 at 5:17 am

          Unfortunately, there is no defined word for APIs that partially follow these principles.

          Reply
    • Person says

      August 29, 2020 at 6:21 pm

      Or a RESTed API.

      And if it’s migrating from being an API that isn’t RESTed to one that is, you can say it’s under arREST 😉

      Reply
  2. Dave Young says

    March 2, 2020 at 3:38 pm

    Regarding the 6th guiding principle – coding on demand, does this include single page application in which code is downloaded from a server to the UI when invoked?

    Reply
    • Admin says

      March 4, 2020 at 8:33 am

      REST principles are not affected by SPA design.

      Reply
  3. Jason Packer says

    February 25, 2020 at 5:28 pm

    My previous firm used camel case notation.

    Reply
    • Chandrajeet Choudhary says

      March 1, 2020 at 2:46 pm

      I suggest never use camel case notation. You should use all lowercase separated with hyphens. It helps in SEO.

      Reply
      • Luis says

        March 6, 2020 at 1:20 am

        But is it important the SEO in an API?
        Maybe using lowercase seperated with hyphens is better to read.

        Reply
        • Tiamo says

          October 25, 2020 at 10:50 am

          Not at all. The API url’s should never get any eyes from the end-user, so they aren’t important for SEO.

          Reply
  4. Admin says

    February 12, 2020 at 4:37 pm

    I will suggest using all lowercase seperated with hyphens.

    Reply
  5. Alexander says

    February 11, 2020 at 3:33 pm

    “Another thing which will help you while building RESTful APIs is that query based API results should be represented by a list of links with summary information, not by arrays of original resource representations because the query is not a substitute for identification of resources.”

    I struggle to comprehend this without an example. Let us say, our API is supposed to retrieve data, such as employee data from database server in JSON format to be consumed by client app. What is “a list of links with summary information” that we can expect as the result of the API.
    Currently I am using PHP + Laravel. Maybe someone can explain or give an example of the above statement, preferably using Laravel routing statement.

    Reply
    • Admin says

      February 11, 2020 at 5:17 pm

      The article suggests using URIs and respective response structures as below.

      If we will provide full device information in search query results, the client may start using these URIs to get and utilize individual device information – Which is wrong.

      For example, '/devices?id=1' should never be alternative to '/devices/1'.

      <devices size="3">
      	<device id="1"> 
          	<link rel="self" href="/devices/1"/>
          	<name>apple-srx_201</name> 
          	<serialNumber>1111</serialNumber> 
              <connectionStatus>up</connectionStatus> 
          </device> 
          <device id="2"> 
          	<link rel="self" href="/devices/2"/>
          	<name>apple-srx_202</name> 
          	<serialNumber>2222</serialNumber> 
              <connectionStatus>down</connectionStatus> 
          </device> 
          <device id="3"> 
          	<link rel="self" href="/devices/3"/>
          	<name>apple-srx_203</name> 
          	<serialNumber>3333</serialNumber> 
              <connectionStatus>up</connectionStatus> 
          </device> 
      </devices> 
      
      <device id="1"> 
          <link rel="self" href="/devices/1"/>
          <deviceFamily>apple-es</deviceFamily> 
          <OSVersion>10.3R2.11</OSVersion> 
          <platform>SRX100B</platform> 
          <serialNumber>32423457</serialNumber> 
          <connectionStatus>up</connectionStatus> 
          <ipAddr>192.168.21.9</ipAddr> 
          <name>apple-srx_200</name> 
          <status>active</status>
      </device> 
      
      Reply
      • Alexander says

        February 12, 2020 at 2:36 pm

        Thanks for your reply. I have read other articles by you, especially : https://restfulapi.net/rest-api-design-tutorial-with-example/.
        When you discuss two resource types there, i.e collection and single, and explain why we should provide different responses to these resource types , I understand your suggestion above. Hence I also get what HATEOAS means.
        Thanks again.

        Reply
  6. Anto says

    January 1, 2020 at 4:33 pm

    > So in practice, you will end up creating lots of custom media-types – normally one media-type associated with one resource.

    Put in this way, IMHO, I think the sentence is misleading. Reading the phrase what I understand is that for each resource I MUST create a custom media type, for example application/vnd.book+json, application/vnd.author+json and application/vnd.user+json if my application handles book, author and user resources. Albeit this is not forbidden by the REST principles I think that a more appropriate sentence would be:

    > So in practice, you CAN end up creating lots of custom media-types – POTENTIALLY one media-type associated with one resource.

    Reply
  7. 应琪瑜 says

    December 20, 2019 at 9:07 am

    chatpter HATEOAS will explain your confussion

    Reply
  8. Sunny says

    June 13, 2019 at 4:06 pm

    In the article you said “In simplest words, in the REST architectural style, data and functionality are considered resources…”, can you give an example of a functionality as a resource?

    Reply
    • Gaurav says

      July 9, 2019 at 3:11 am

      PHP Laravel works on restful api features…
      There each request send and received through only with these 6 features….

      Reply
      • Rob Talada says

        August 12, 2019 at 4:48 am

        No, Laravel simulate PUT with POST and just sends a hidden field along containing “_PUT” with the form data identifying the POST as intending to PUT. It will not accept a real HTTP put.

        Reply
    • Piyush Metkar says

      September 12, 2019 at 8:33 pm

      Consider the example of Google Maps API. You provide the source and destination and the API will give you the list of waypoints(route) to your destination.

      Reply
    • Iris says

      October 8, 2019 at 8:02 pm

      He gave the following examples in another topic (https://restfulapi.net/resource-naming/):

      http://api.example.com/cart-management/users/{id}/cart/checkout
      http://api.example.com/song-management/users/{id}/playlist/play

      I think these are examples of functionality

      Reply
  9. Snehal Masne says

    April 13, 2018 at 4:12 pm

    What needs to be done to make the REST architectural style clear on the notion that hypertext is a constraint? In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period. Is there some broken manual somewhere that needs to be fixed?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Search Tutorials

Learn REST

  • What is REST?
  • REST Constraints
  • REST Resource Naming Guide

Guides

  • Caching
  • Compression
  • Content Negotiation
  • HATEOAS
  • Idempotence
  • Security Essentials
  • Versioning
  • Statelessness in REST APIs

Tech – How To

  • REST API Design Tutorial
  • Create REST APIs with JAX-RS

FAQs

  • PUT vs POST
  • N+1 Problem
  • ‘q’ Parameter

Resources

  • What is an API?
  • Comparing SOAP vs REST APIs
  • HTTP Methods
  • Richardson Maturity Model
  • HTTP Response Codes
    • 200 (OK)
    • 201 (Created)
    • 202 (Accepted)
    • 204 (No Content)
    • 301 (Moved Permanently)

Footer

References

  • The dissertation by Roy Thomas Fielding
  • Uniform Resource Identifier (URI, URL, URN) [RFC 3986]
  • Internet MediaTypes
  • Web Application Description Language (WADL)

Meta Links

  • About
  • Contact Us
  • Privacy Policy

Blogs

  • How To Do In Java

Copyright © 2020 · restfulapi.net · All Rights Reserved. | Sitemap