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

Setting API Endpoints

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 preceding slash before an optional parameter will 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}', 'create user' : '/create', 'add user' : '/add/{id}', 'follow user' : '/follow/{id}', 'search' : '/search/?query={value}' };

Working with URLs

Named API actions are offered for convenience and maintanability, but are not required. You can also specify the url in each request, templated or not.

$('.search.button') .api({ url: 'http://www.google.com?q={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 Events

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' }) ;
Or
$('.follow.button') .api() ;

Specifying DOM 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' }) ;

Keep in mind passing a new settings object will destroy all previously attached events. If you want to preserve the events, you can trigger a new request with the the query behavior

// set-up API button with events $('.follow.button') .api({ action: 'follow user' }) ; // do an immediate query $('.follow.button') .api('query') ;

Setting-up Requests

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).

Automatically Routed Data

Some special values are available for routing without additional set-up

Variable Description Available for
text current text value of element All DOM elements
value current input value of element All input elements
$.fn.api.settings.api.search = '/search/?query={value}'; $('.search input') .api({ action: 'search', // what receives state class names stateContext: '.ui.input' }) ;

Request Information in Data Attributes

You can include url values as html5 metadata attributes

This is often easiest to include unique url data for each triggering element, for example, many follow buttons will trigger the same endpoint, but each will have its own user id.

As a convenience, you can also specify your API action in metadata, to allow you to instantiate multiple types of api actions in one statement.

Only variables specified in your API's URL will be searched for in metadata.
Follow 1
Add Stevie
Follow Jenny
Add Jennie
$('.follow.button') .api() ;

Data specified in Javascript

URL variable, and GET/POST data can be specified at run-time in the javascript object

$('.follow.button') .api({ action : 'follow user', method : 'POST', // Substituted into URL urlData: { id: 22 }, // passed via POST data: { name: 'Joe Henderson' } }) ;

Adjusting Request in Before Send

All run settings, not just url data, can be adjusted in a special callback beforeSend which occurs before the API request is sent.

An additional callback beforeXHR lets you modify the XHR object before sending. This is different than beforeSend.
$('.follow.button') .api({ action: 'follow user', beforeSend: function(settings) { settings.urlData = { id: 22 }; return settings; } // basic auth login beforeXHR: function(xhr) { xhr.setRequestHeader ('Authorization', 'Basic XXXXXX'); } }) ;

Cancelling Requests

BeforeSend can also be used to check for special conditions for a request to be made. It the beforeSend callback returns false, the request will be cancelled.

// set somewhere in your code window.isLoggedIn = false; $('.follow.button') .api({ action: 'follow user', // cancels request beforeSend: function(settings) { return isLoggedIn; } }) ;

Sending Data

Automatically Routed Data

Calling API on any element inside of a form, will automatically include serialized form content in your request when using a special setting serializeForm, or using a form as the stateContext.

Using serializeForm requires including the serialize-object dependency.

Unlike jQuery's serialize, data will be serialized as a javascript object using macek's serialize object.

Benefits of Structured Data
  • Serialized Form Data can be modified in javascript in beforeSend
  • Structured data can be used by using names like name="user[name]" in your form
  • Form data will automatically be converted to useful values, for instance, checkbox to to boolean values.
  • Submit
    $('form .submit.button') .api({ action: 'create user', serializeForm: true, beforeSend: function(settings) { // open console to inspect object console.log(settings.data); return settings; } }) ;

Included in Javascript

POST or GET data can be included, when setting up API requests, through automatic inclusion, or during the beforeSend callback. This data will be joined together

$('.form .submit') .api({ action: 'create user', serializeForm: true, data: { sessionID: '232' }, beforeSend: function(settings) { settings.data.token = window.generateToken(); // will include serialized data, session id, and token return settings; } }) ;

Server Responses

Determining Success

API is designed to work with APIs that return JSON objects. Instead of providiing success and failure callbacks based on the HTTP response of the request. A request is considered succesful only if the returned JSON value passes a successTest.

For example you might expect all successful JSON responses to return a top level property signifying the success of the response

{ "success": true, "message": "We've retreived your data from the server" "data": { // payload here } }

The success test function recieves the servers json response, and returns whether the result should be considered successful. Succesful results will trigger onSuccess, invalid results onFailure.

onError will only trigger on XHR errors (except due to page navigation like clicking a link), but not invalid JSON responses.

$('.follow.button') .api({ successTest: function(response) { return response.success || false; } onSuccess: function() { // valid response and response.success = true }, onFailure: function() { // valid response but response.success = false }, onError: function() { // invalid response }, onAbort: function() { // user cancelled request } }) ;

Controlling State

API State Management

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

States adjust class names on the triggering element or on the element specified by settings.stateContext.

Using stateContext allows you to easily do things like, trigger a loading state on a form when a submit button is pressed.

States Included in API Module
State Description API event
loading Indicates a user needs to wait XHR has initialized
error Indicates an error has occurred XHR Request returns error (does not trigger onAbort caused by page change, or if successTest fails). Stays visible for settings.errorDuration

Coupling with State Module

Initializing an API action with the state module gives you more granular control over UI states, like setting an activated or de-activated state and the ability to adjust text values for each state:

For additional examples of the possibilities available with state behaviors check the state module documentation

$('.follow.button') .api({ action: 'follow user' }) .state({ text: { inactive : 'Follow', active : 'Followed', deactivate : 'Unfollow', flash : 'Added follower!' } }) .state('setting', 'onActivate', function() { $(this).state('flash text'); }) ;
States Included in State Module
State Description Occurs on
inactive Default state
active Selected state Toggled on succesful API request
activate Explains activating action On hover if inactive
deactivate Explains deactivating action On hover if active
hover Explains interaction On hover in all states, overrides activate/deactivate
disabled Indicates element cannot be interacted Triggered programatically. Blocks API requests.
flash Text-only state used to display a temporary message Triggered programatically
success Indicates user action was a success Triggered programatically
warning Indicates there was an issue with a user action Triggered programatically

Needs to be written still...

API

Behavior

Default Description
on auto When API event should occur
filter
.disabled
Selector filter for elements that should not be triggerable
stateContext this UI state will be applied to this element, defaults to triggering element.
defaultData true Whether to automatically include default data like {value} and {text}
serializeForm false Whether to serialize closest form and include in request
loadingDuration 0 Minimum duration to show loading indication
errorDuration 2000 Duration in milliseconds to show error state after request error.

Request Settings

Default Description Possible Values
action Named API action for query, originally specified in $.fn.settings.api String or false
url false Templated URL for query, will override specified action String or false
urlData false Variables to use for replacement
method get Method for transmitting request to server post, get
dataType JSON Expected data type of response xml, json, jsonp, script, html, text
data {} POST/GET Data to Send with Request

Callbacks

Context Description
beforeSend(settings) initialized element Allows modifying settings before request, or cancelling request
beforeXHR(xhrObject) Allows modifying XHR object for request
onSuccess(response, element) state context Callback on response object that passed successTest
onFailure(response, element) state context Callback on response object that fails successTest
onError(errorMessage, element) state context Callback on server error from returned status code, or XHR failure.
onAbort(errorMessage, element) state context Callback on abort caused by user clicking a link or manually cancelling request
onComplete(response, element) state context Callback on request complete regardless of conditions

Module

These settings are native to all modules, and define how the component ties content to DOM attributes, and debugging settings for the module.

Default Description
name API Name used in log statements
namespace api Event namespace. Makes sure module teardown does not effect other events attached to an element.
regExp
regExp : { required: /\{\$*[A-z0-9]+\}/g, optional: /\{\/\$*[A-z0-9]+\}/g, }
Regular expressions used for template matching
selector
selector: { form: 'form' }
Selectors used to find parts of a module
className
className: { loading : 'loading', error : 'error' }
Class names used to determine element state
metadata
metadata: { action : 'action', request : 'request', xhr : 'xhr' }
Metadata used to store xhr and response promise
debug false Debug output to console
performance false Show console.table output with performance metrics
verbose false Debug output includes all internal behaviors
errors
// errors error : { beforeSend : 'The before send function has aborted the request', error : 'There was an error with your request', exitConditions : 'API Request Aborted. Exit conditions met', JSONParse : 'JSON could not be parsed during error handling', legacyParameters : 'You are using legacy API success callback names', missingAction : 'API action used but no url was defined', missingSerialize : 'Required dependency jquery-serialize-object missing, using basic serialize', missingURL : 'No URL specified for api event', noReturnedValue : 'The beforeSend callback must return a settings object, beforeSend ignored.', parseError : 'There was an error parsing your request', requiredParameter : 'Missing a required URL parameter: ', statusMessage : 'Server gave an error: ', timeout : 'Your request timed out' }