--- layout : 'default' css : 'api' title : 'API' description : 'API allows elements to trigger actions on a server' type : 'Draft' --- <%- @partial('header', { tabs: 'behavior' }) %>

There a few key features which make API more useful then jQuery AJAX or and simpler than MVC patterns.

Already Knows Your UI

Attach an API event to an input, by default, it will occur oninput. Attach an API event to a button, onclick. State management is built in: rate throttling, UI state changes like active, loading, disabled, min/max request lengths and more.

Deal with resources not URLs

Create named actions like 'follow user' and have API handle URL templating, parameters, and other annoyances for you.

State Management

Easily tie server events like AJAX loading elements using intuitive defaults based on the context inside your interface. Set maximum and minimum request times, toggle between UI states, and easily sync state between multiple elements with the same API actions.

Server Traces For Humans

View your API request as it occurs in your web console, get errors if required url variables are missing, and useful performance metrics.

Stevie Feliciano
Joined in Sep 2014

Defining Your API

Creating Server Actions

API works best by defining named API actions which can be converted to URLs for each request.

You must define your endpoints once in your application before making requests. Usually this is done in a central configuration file included on each page.

URLs listed in your API can include required parameters and optional parameters which may be adjusted for each call.

Required Parameters
Uses format {variable}
Will abort the request if they cannot be found.
Optional Parameters
Uses format {/variable}
Will abort the request if they cannot be found.
Will be removed from the url automatically if not available.
Any trailing slashes before optional parameters will also be removed from the URL, allowing you to include them in resource paths.
/* Define API endpoints once globally */ $.fn.api.settings.api = { 'get followers' : '/followers/{id}?results={count}', 'follow user' : '/follow/{id}', 'search' : '/search/?query={value}' };

Querying API Actions

Open Your Web Console
The following examples work best while viewing logs in your web console. This experienced is optimized for Firebug, but will also appear in webkit browsers with minor issues.
API requests for the following demos have been faked using SinonJS to avoid rate throttling from public APIs. No actual data is returned.

Attaching API to UI

Any element can have an API action attached directly to it. By default the action will occur on the most appropriate event for the type of element. For example a button will assume onclick or an input oninput, or a form onsubmit.

$('.follow.button') .api({ action: 'follow user' }) ;

Specifying Events

If you need to override what action an API event occurs on you can use the on parameter.

$('.follow.button') .api({ action: 'follow user', on: 'mouseenter' }) ;

Calling Immediately

If you require API action to occur immediately use on: 'now'. This will still trigger the same state updates to the invoked element, but will occur immediately.

$('.follow.button') .api({ action: 'follow user', on: 'now' }) ;

Providing Data

URL Variables

If your API urls include templated variables they will be replaced during your request by one of four possible ways (listed in order of inheritance).

Only variables specified in your URL will be searched for in metadata. Adding metadata attributes will not be automatically included in GET or POST values.

...automatically Routed Data

Some useful values are automatically included in every request

Variable Description Available for
text current text value of element All DOM elements
value current input value of element All input elements
// replaces /search?query={value} $('.search input') .api({ action: 'search', // this setting will be explained later stateContext: '.ui.input' }) ;

...by Data Attributes

If many elements trigger a similar function, it is often easiest to include unique url data in each triggering element. For example, many follow buttons will trigger the same endpoint, but each will have its own user id.

$('.follow.button') .api({ action: 'follow user' }) ;

....in Javascript

URL variables can be specified at run-time in the javascript object

$('.follow.button') .api({ action: 'follow user', urlData: { id: 22 } }) ;

...returned values from beforeSend Callback

In addition all parameters can be adjusted in a special callback beforeSend which occurs, quite intuitively, before the API request is sent.

You can also use this callback to adjust other settings before each API call

$('.follow.button') .api({ action: 'follow user', beforeSend: function(settings) { settings.urlData = { id: 22 }; return settings; } }) ;

Controlling State

UI State

Many elements like button, input, and form have loading, disabled, and active states defined.

API will automatically attach a loading state when an API request is triggered, but makes no other assumptions about states.

State Management

If state() is invoked after an API event is attached to an element, it will automatically toggle an active state on the element after a successful API request.

Basic included states

State Description API event
loading Indicates a user needs to wait XHR has initialized
error Indicates an error has occurred Request returns error (does not trigger onAbort caused by page change)

UI State

Invoking state also includes additional states which can adjust text values:

State Description Occurs on
inactive User has not selected
active User has selected Toggled on succesful API request
activate Text explaining activating action On hover if inactive
deactivate default state
hover Text-only state explaining interaction On hover if inactive or active
disabled Indicates element is disabled Only triggered programatically
Flash Text-only state used to display a temporary message Only triggered programatically
Disabled Cannot receive user interaction
  • Inactive - Default state
  • Active - API request is completed succesfully
  • Enable - Text on hover if currently in inactive state
  • Disable - Text on hover if currently in inactive state
  • Deactivate - Text on hover if currently in active state
  • Hover - Text appears on hover regardless of state
  • Flash - Text appears on element for time duration set by flashDuration
$('.follow.button') .state({ text: { inactive : 'Follow', active : 'Followed', deactivate : 'Unfollow', flash : 'Updated!' } }) ;