Less stress with

SPA & REST

How did we get here?

Who's got the ball? Naturally!

Rolling up our sleeves

What led to the development of this style of web application & why has it become so popular?

What constitutes a RESTful API? A SPA? Redefining our notions of who should be doing what

Building a REST API & a SPA to consume it. Hidden dangers and ways of overcoming them

Context

Theory

Practice

REST

Representational State Transfer (REST) is a constraint-driven architectural style for building networked software. It is not bound to any specification or protocol but has been most notably implemented in the HTTP protocol and is most often used for creating web services.

SPA

A Single-Page Application (SPA) is a web application built in such a way that it mimics the experience of a desktop application. A single page containing everything the client needs to interact with the API is sent on the initial GET request, the client bootstraps itself, and all further interaction is via data-only HTTP requests.

Alphabetti Spaghetti

SPA

& REST

In Context

Server

Authentication

Authorization

Business Logic

Data access

Event handling

DOM rendering

Feature toggling

Internationalization

Logging

Routing

Static assets

Client

Analytics

Data management/IO (AJAX)

DOM manipulation

Presentation

Separation of concerns then

Server

Authentication

Authorization

Business Logic

Data access

Logging

Static assets

Client

Analytics

Business Logic

Data management/IO (AJAX)

DOM manipulation

DOM rendering

Event handling

Feature toggling

Internationalization

Logging

Presentation

Routing

Static assets

Separation of concerns now

Benefits

of
REST

Scalability

Reliability

Simplicity

Modifiability

Visibility

Performance

Portability

Benefits

of
SPAs

Design

Build

Interact

The most efficient way to do something on the server is to do it on the client!

Browsers
are
free.

Change

Balance

Beauty

"The 19th century culture was defined by the novel, the 20th century culture was defined by the cinema, and the culture of the 21st century will be defined by the interface." @aaronkoblin

SPA

& REST

In Theory

Six
Primary
Constraints

Client-server

Separation of concerns

Separation of concerns is the principle behind the client-server constraints. 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. Perhaps most significant to the Web, however, is that the separation allows the components to evolve independently, thus supporting the Internet-scale requirement of multiple organizational domains.

Stateless

Transparency

...communication must be stateless in nature,...such that 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.

Cache

Efficiency

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.

Uniform Interface

Generality

The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components. 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. Implementations are decoupled from the services they provide, which encourages independent evolvability. The trade-off, though, is that a uniform interface degrades efficiency, since information is transferred in a standardized form rather than one which is specific to an application's needs. The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction.

Layered System

Composition

...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.[...] The combination of layered system and uniform interface constraints induces architectural properties similar to those of the uniform pipe-and-filter style. Although REST interaction is two-way, the large-grain data flows of hypermedia interaction can each be processed like a data-flow network, with filter components selectively applied to the data stream in order to transform the content as it passes. Within REST, intermediary components can actively transform the content of messages because the messages are self-descriptive and their semantics are visible to intermediaries.

Code-On-Demand

Extendability

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. Allowing features to be downloaded after deployment improves system extensibility. However, it also reduces visibility, and thus is only an optional constraint within REST. The notion of an optional constraint may seem like an oxymoron. However, it does have a purpose in the architectural design of a system that encompasses multiple organizational boundaries. It means that the architecture only gains the benefit (and suffers the disadvantages) of the optional constraints when they are known to be in effect for some realm of the overall system.

Four
Secondary
Constraints

Resource Identifiers

Set Identity

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 (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. More precisely, a resource R is a temporally varying membership function MR(t), which for time t maps to a set of entities, or values, which are equivalent. The values in the set may be resource representations and/or resource identifiers. A resource can map to the empty set, which allows references to be made to a concept before any realization of that concept exists -- a notion that was foreign to most hypertext systems prior to the Web .
R = M_R(t)
R=MR(t)

Representations

State Information

A representation consists of data, metadata describing the data, and, on occasion, metadata to describe the metadata (usually for the purpose of verifying message integrity). Metadata is in the form of name-value pairs, where the name corresponds to a standard that defines the value's structure and semantics. Response messages may include both representation metadata and resource metadata: information about the resource that is not specific to the supplied representation. Control data defines the purpose of a message between components, such as the action being requested or the meaning of a response. It is also used to parameterize requests and override the default behavior of some connecting elements. For example, cache behavior can be modified by control data included in the request or response message.

Self-Describing

Intermediate Processing

REST enables intermediate processing by constraining messages to be self-descriptive: interaction is stateless between requests, standard methods and media types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.

Hypermedia

HATEOAS

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.

Three
Interface

Structures

Shell

Application Container

A shell is the "single page". It's the initial HTML file that the client downloads on the first GET request and contains everything needed to bootstrap the client application. It typically has a single container into which the application's views are loaded.

<div id="container"></div> <!-- application container -->

Region

Child Containers

A region is a child container of the shell. Regions are typically used for dividing the viewable area into sections like the header, footer, or sidebar. The content within a region is populated by a view.

<div id="header"></div> <!-- header region -->
<div id="footer"></div> <!-- footer region -->

View & Template

Page or Region

The view in a SPA is an interface mapping to a route, taking the place of the 'page', or an interface mapping to a region, such as a shopping cart or header. These are typically stored as fragments of HTML containing placeholders for data called templates, populated with data, and injected into the shell's container.

<div id="header-view"></div> <!-- Header region view -->
<div id="about-view"></div> <!-- About Us view /about -->

Three
Design
Patterns

Module

Namespaces

The Javascript module pattern is used for everything in SPAs to keep each part of the application compartmentalized and prevent leaking variables to the global namespace.

Anchor Interface

Application State

The anchor interface pattern is used to tie application state to a URI using HTML5 History API (pushState). State is loaded via URI by view swapping.

MV*

Separation of Concerns

There are many variations on this theme - MVC, MVVM, MVP, RVP, MVVT, etc. - but they all try to solve the same problem: separating views, presentation logic, and data while providing a way for these three layers to be coordinated, typically involving manipulating, binding to, and/or virtualizing the DOM.

(Controller, Model, Presenter, Resource, Template, View)

SPA

& REST

In Practice

The
Build
Process

Backend

Frontend

Identify system actors & build out SPA w/mock data

Use a tool like apiary to create a realistic mockup of your API

Handoff of data spec to frontend

Integration with SPA

Begin sketching out API, using the mockup

Jump right into whiteboarding

Receive data specs, user stories

Wireframes/HF mockups (or not)

Tools
for
REST

Frameworks, tools & services

Good news! Most of your tools remain the same!

Postman FTW!

There are also a lot of frameworks specifically for building RESTful APIs.

Curl

Services like Apiary, Parse, and Contentful

Most web application frameworks can also do REST.

Tools
for
SPAs

Frameworks, tools & services

TodoMVC for a more complete list!

Whiteboard!

UI Tools 

Build Tools

Pub/Sub

Package Management

NPM

Internationalization

Planning

MV* Frameworks & Tools

SPA School

Tricksy
hobbitses

Five Information Channels

  1. Data (JSON Representations)
  2. URI (Resource IDs)
  3. Request Header
  4. Accept Header
  5. HTTP Status Codes

Authentication & Access Control

Authentication and authorization is usually done using OAuth and ACLs on the models. That information is encoded in the user's auth token, also sometime called an access token, and passed in the header (not as a URL parameter!) with each request. 

REST

HTTP Status Codes

It is crucial to a good REST implementation that it always return the semantically correct HTTP status code with each response! If a resource exists but there is no data, it's okay to return an empty set with a 200 Ok response. If the resource doesn't exist, the correct response is 404 Not Found.

Realtime

No! Realtime is inherently not REST! If you truly have realtime constraints, get rid of the REST constraints and just use websockets.

Testing

Great news! REST APIs can be tested the same way any other web application is tested - using integration and unit tests. Because of RESTs simplicity, testing becomes a breeze compared to traditional monolithic or SOA SaaS applications.

URIs

GET       /widgets (READ)

GET       /widgets/:id (READ)

POST     /widgets (CREATE)

PUT       /widgets/:id (UPDATE)

DELETE /widgets/:id (DELETE)

GET       /widgets/?name=foo

Versioning

There are three ways that you can version your API:

  • in the URL:

      /api/v1/widgets/42

  • in the request header

      api-version: 1

  • in the accept header

      Accept: application/vnd.widgetco.v1+json

Data

  • What should be cached?
  • What should be synced?
  • Can/should we sync it P2P?
  • Pub/Sub?
  • Models, View Models, Paradigm?

Logic

  • Can we do it on the client?
  • Magic vs. hackability
  • What is unnecessary and therefore, can be thrown away?
  • Frameworks?
  • Libraries?
  • Tools?

SPAs

Security

Always serve over HTTPS!

Authentication and access control should be done server-side to an OAuth provider.

Trust but verify!

Rendering

  • What level of control do we want over the templating and rendering process?
  • Magic vs. hackability
  • What is unnecessary and therefore, can be thrown away?
  • Frameworks?
  • Libraries?
  • Tools?

REST Resources

R. T. Fielding. Architectural Styles for Network-based Applications, Draft 1.1. Phase II Survey Paper, Department of Information and Computer Science, University of California, Irvine, July 1999.

R. T. Fielding. Architectural Styles and the Design of Network-based Software Architectures. Dissertation, Department of Information and Computer Science, University of California, Irvine, 2000.

R. T. Fielding. Architectural Styles for Network-based Applications, Draft 2.0. Phase II Survey Paper, Department of Information and Computer Science, University of California, Irvine, January 2000.

R. T. Fielding and R. N. Taylor. Principled Design of the Modern Web Architecture. In Proceedings of the 2000 International Conference on Software Engineering (ICSE 2000), Limerick, Ireland, June 2000, pp. 407-416.

R. T. Fielding. REST APIs must be hypertext-driven. Untangled, October 2008.

Design Resources

Demo!

Less Stress with SPA & REST

By Carlo DiCelico

Less Stress with SPA & REST

+ What led to the development of this style of web application? + Why has this approach become so popular? + Redefining our notions of who should be doing what + What constitutes a RESTful API? + What constitutes a SPA? + What are some of the hidden challenges in building applications this way? + What are some accepted tools and techniques for addressing these challenges? + End-to-end application demo

  • 1,437