RESTful

 · 9 mins read

Representational State Transfer (REST) refers to a group of software architecture design constraints that bring about efficient, reliable, and scalable distributed systems. A system is called RESTful when it adheres to those constraints.

The basic idea of REST is that a resource, e.g. a document, is transferred with its state and relationships (hypertext) via well-defined, standardized operations and formats. Often API’s or services call themselves RESTful when they directly modify a type of document as opposed to triggering actions elsewhere.

Because HTTP, the standard protocol behind the Web, also transfers documents and hypertext links, simple HTTP APIs are sometimes colloquially referred to as RESTful APIs, RESTful services, or simply REST services, although they don’t necessarily adhere to all REST constraints. Beginners can assume a REST API means an HTTP service that can be called using standard web libraries and tools.

Key constraints

There are 6 key constraints to think about when considering whether a RESTful API is the right type of API for your needs:

  • Client-Server: This constraint operates on the concept that the client and the server should be separate from each other and allowed to evolve individually.</p>
  • Stateless: REST APIs are stateless, meaning that calls can be made independently of one another, and each call contains all of the data necessary to complete itself successfully.

  • Cache: Because a stateless API can increase request overhead by handling large loads of incoming and outbound calls, a REST API should be designed to encourage the storage of cacheable data.

  • Uniform Interface: The key to the decoupling client from server is having a uniform interface that allows independent evolution of the application without having the application’s services, or models and actions, tightly coupled to the API layer itself.

  • Layered System: REST APIs have different layers of their architecture working together to build a hierarchy that helps create a more scalable and modular application.

  • Code on Demand: Code on Demand allows for code or applets to be transmitted via the API for use within the application.

Unlike SOAP, REST is not constrained to XML, but instead can return XML, JSON, YAML or any other format depending on what the client requests. And unlike RPC, users aren’t required to know procedure names or specific parameters in a specific order.

One of the disadvantages of RESTful APIs is that you can lose the ability to maintain state in REST, such as within sessions. It can also be more difficult for newer developers to use.

HTTP verbs

Use HTTP Verbs to Make Your Requests Mean Something

API consumers are capable of sending GET, POST, PUT, and DELETE verbs, which greatly enhance the clarity of a given request.

Generally, the four primary HTTP verbs are used as follows:

GET

Read a specific resource (by an identifier) or a collection of resources.

PUT

Update a specific resource (by an identifier) or a collection of resources. Can also be used to create a specific resource if the resource identifier is known before-hand.

DELETE

Remove/delete a specific resource by an identifier.

POST

Create a new resource. Also a catch-all verb for operations that don’t fit into the other categories.

Note: GET requests must not change any underlying resource data. Measurements and tracking which update data may still occur, but the resource data identified by the URI should not change.

Provide Sensible Resource Names

Producing a great API is 80% art and 20% science. Creating a URL hierarchy representing sensible resources is the art part. Having sensible resource names (which are just URL paths, such as /customers/12345/orders) improves the clarity of what a given request does.

Appropriate resource names provide context for a service request, increasing understandability of the API. Resources are viewed hierarchically via their URI names, offering consumers a friendly, easily-understood hierarchy of resources to leverage in their applications.

Here are some quick-hit rules for URL path (resource name) design:

  • Use identifiers in your URLs instead of in the query-string. Using URL query-string parameters is fantastic for filtering, but not for resource names.
    • Good: /users/12345
    • Poor: /api?type=user&id=23
  • Leverage the hierarchical nature of the URL to imply structure.</p>
  • Design for your clients, not for your data.

  • Resource names should be nouns. Avoid verbs as resource names, to improve clarity. Use the HTTP methods to specify the verb portion of the request.

  • Use plurals in URL segments to keep your API URIs consistent across all HTTP methods, using the collection metaphor.

    • Recommended: /customers/33245/orders/8769/lineitems/1
    • Not: /customer/33245/order/8769/lineitem/1
  • Avoid using collection verbiage in URLs. For example ‘customer_list’ as a resource. Use pluralization to indicate the collection metaphor (e.g. customers vs. customer_list).</p>
  • Use lower-case in URL segments, separating words with underscores (‘_’) or hyphens (‘-‘). Some servers ignore case so it’s best to be clear.

  • Keep URLs as short as possible, with as few segments as makes sense.

Use HTTP Response Codes to Indicate Status

Response status codes are part of the HTTP specification. There are quite a number of them to address the most common situations. In the spirit of having our RESTful services embrace the HTTP specification, our Web APIs should return relevant HTTP status codes. For example, when a resource is successfully created (e.g. from a POST request), the API should return HTTP status code 201. A list of valid HTTP status codes is available here which lists detailed descriptions of each.

200 OK

General success status code. This is the most common code. Used to indicate success.

201 CREATED

Successful creation occurred (via either POST or PUT). Set the Location header to contain a link to the newly-created resource (on POST). Response body content may or may not be present.

Offer Both JSON and XML

Favor JSON support unless you’re in a highly-standardized and regulated industry that requires XML, schema validation and namespaces, and offer both JSON and XML unless the costs are staggering. Ideally, let consumers switch between formats using the HTTP Accept header, or by just changing an extension from .xml to .json on the URL.

Be aware that as soon as we start talking about XML support, we start talking about schemas for validation, namespaces, etc. Unless required by your industry, avoid supporting all that complexity initially, if ever. JSON is designed to be simple, terse and functional. Make your XML look like that if you can.

In other words, make the XML that is returned more JSON-like — simple and easy to read, without the schema and namespace details present, just data and links. If it ends up being more complex than this, the cost of XML will be staggering. In my experience no one has used XML responses anyway for the last several years, it’s just too expensive to consume.

Note that JSON-Schema offers schema-style validation capabilities, if you need that sort of thing.

Create Fine-Grained Resources

When starting out, it’s best to create APIs that mimic the underlying application domain or database architecture of your system. Eventually, you’ll want aggregate services that utilize multiple underlying resources to reduce chattiness. However, it’s much easier to create larger resources later from individual resources than it is to create fine-grained or individual resources from larger aggregates. Make it easy on yourself and start with small, easily defined resources, providing CRUD functionality on those. You can create those use-case-oriented, chattiness-reducing resources later.

Consider Connectedness

One of the principles of REST is connectedness—via hypermedia links (search HATEOAS). While services are still useful without them, APIs become more self-descriptive and discoverable when links are returned in the response. At the very least, a ‘self’ link reference informs clients how the data was or can be retrieved. Additionally, utilize the HTTP Location header to contain a link on resource creation via POST (or PUT). For collections returned in a response that support pagination, ‘first’, ‘last’, ‘next’ and ‘prev’ links at a minimum are very helpful.

Regarding linking formats, there are many. The HTTP Web Linking Specification (RFC5988) explains a link as follows:

a link is a typed connection between two resources that are identified by Internationalised Resource Identifiers (IRIs) [RFC3987], and is comprised of:

  • a context IRI,
  • a link relation type
  • a target IRI, and
  • optionally, target attributes.

A link can be viewed as a statement of the form “{context IRI} has a {relation type} resource at {target IRI}, which has {target attributes}.”

At the very least, place links in the HTTP Link header as recommended in the specification, or embrace a JSON representation of this HTTP link style (such as Atom-style links, see: RFC4287) in your JSON representations. Later, you can layer in more complex linking styles such as HAL+JSON, Siren, Collection+JSON, and/or JSON-LD, etc. as your REST APIs become more mature.

see HATEOAS

Hypermedia As The Engine Of Application State (HATEOAS)

In a nut shell,

A REST client enters a REST application through a simple fixed URL. All future actions the client may take are discovered within resource representations returned from the server.

In this way, RESTful interaction is driven by hypermedia, rather than out-of-band information.

The advantages of REST for development

  1. Separation between the client and the server: the REST protocol totally separates the user interface from the server and the data storage. This has some advantages when making developments. For example, it improves the portability of the interface to other types of platforms, it increases the scalability of the projects, and allows the different components of the developments to be evolved independently.

  2. Visibility, reliability and scalability.

    The separation between client and server has one evident advantage, and that is that each development team can scale the product without too much problem. They can migrate to other servers or make all kinds of changes in the database, provided the data from each request is sent correctly. The separation makes it easier to have the front and the back on different servers, and this makes the apps more flexible to work with.

  3. The REST API is always independent of the type of platform or languages:

    the REST API always adapts to the type of syntax or platforms being used, which gives considerable freedom when changing or testing new environments within the development. With a REST API you can have PHP, Java, Python or Node.js servers. The only thing is that it is indispensable that the responses to the requests should always take place in the language used for the information exchange, normally XML or JSON.

LINKS:

RESTful

A RESTful Tutorial