Designing JavaScript APIs

25 %
75 %
Information about Designing JavaScript APIs

Published on February 28, 2014

Author: jcleblanc



API creation within JavaScript introduces a whole new array of security and request issues that traditional APIs never encounter. In this session we’ll explore several principles behind JavaScript API design and architecture, including OAuth 2 in the JavaScript model, Cross-Origin Resource Sharing for browser security constraints, building action automation with HATEOAS, and
challenges behind secure resource consumption through JavaScript

Designing JavaScript APIs Jonathan LeBlanc (@jcleblanc) Global Head of Developer Evangelism at PayPal



What JavaScript Can Feel Like

JavaScript Challenges

The Same-Origin Policy

Keeping Private Keys Private

Not Providing a Hacked Experience

How Did We Used to Do It?

Server-side Proxies

Flash / iFrame Proxies

Private Token Storage

Securing Resources

A Modern Approach OAuth 2 Tight Access Control CORS Easy Access Control

OAuth 2 User Agent Flow

Redirect the User to Log In Prepare the Redirect URI Authorization Endpoint client_id response_type (token) scope redirect_uri Browser Redirect Redirect URI

User Agent Flow: Redirect var auth_uri = auth_endpoint + "?response_type=token" + "&client_id=" + client_id + "&scope=profile" + "&redirect_uri=" + window.location; $("#auth_btn").attr("href", auth_uri);

Extract the Access Token Fetch the Hash Mod access_token refresh_token expires_in Extract Access Token

User Agent Flow: Hash Mod Extract the Access Token from the Hash 4AzqE3Q&refresh_token=rEBt51FZr54HayqE3V4a& expires_in=3600 var hash = document.location.hash; var match = hash.match(/access_token=(w+)/);

Get Privileged API Resources Set Request Headers + URI Resource Endpoint Header: token type + access token Header: accept data type HTTPS Request

User Agent Flow: Get Resources Making an Authorized Request $.ajax({ url: resource_uri, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'OAuth ' + token); xhr.setRequestHeader('Accept', 'application/json'); }, success: function (response) { //use response object } });

CORS Easy Access Control

Cross Origin Issues and Options Access to other domains / subdomains is restricted (same origin policy) JSONP to request resources across domains Only supports HTTP GET requests Cross-origin resource sharing (CORS) Supports additional range of HTTP requests

Can you use it? Support: 79.42% Partial support: 8.84% Total: 88.26%

How Does it Work? Site sends Origin header to server OPTIONS /v1/oauth2/token HTTP/1.1 Origin: Access-Control-Request-Method: PUT Host: Accept-Language: en-US Connection: keep-alive ...

How Does it Work? Server responds with matching Access-Control-Allow-Origin header Access-Control-Allow-Origin: Access-Control-Allow-Methods: GET, POST, PUT Content-Type: text/html; charset=utf-8

A Lil’ Bit O’ Automation

Uniform Interface Sub-Constraints Resource Identification Resources must be manipulated via representations Self descriptive messages Hypermedia as the engine of application state

Uniform Interface Sub-Constraints Resource Identification Resources must be manipulated via representations Self descriptive messages Hypermedia as the engine of application state


How we Normally Consume APIs

Using HATEOAS to Automate

How HATEOAS Works You make an API request curl -v -X GET ation/2DC87612EK520411B -H "Content-Type:application/json" -H "Authorization:Bearer ENxom5Fof1KqAffEsXtx1HTEK__KVdIsaCYF8C"

"links": [ { "href":" authorization/6H149011U8307001M", "rel":"self", "method":"GET" },{ "href":" authorization/6H149011U8307001M/capture", "rel":"capture", "method":"POST” },{ "href":" authorization/6H149011U8307001M/void", "rel":"void", "method":"POST” } ]

How do we Make it Work with JS? Open Path Library (what to do next) Hierarchy of Requests

Object Chaining

The System Should be Stateless Send complete object to only make 1 request { "id": "PAY-17S8410768582940NKEE66EQ", "create_time": "2013-01-31T04:12:02Z", "update_time": "2013-01-31T04:12:04Z", "state": "approved", "intent": "sale", "payer": {...}, "transactions": [{...}], "links": [{...}] }

Resources and Representations Manipulate a concept (e.g. payment) with the intended state

Chaining Actions The first request builds the action object Subsequent calls manipulate the object var paymentObj = getPreAuth(paymentID) .getNextAction() .processNext(); //build pay object //next HATEOAS link //process action

In Summation Security needs to allow you to work the browser security model Always assume statelessness Build to allow your developers to automate complexities

Thanks! Questions? Jonathan LeBlanc (@jcleblanc) Global Head of Developer Evangelism at PayPal

Add a comment

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

Designing Better JavaScript APIs – Smashing Magazine

This article focuses on how to make your code accessible to other developers and how to design JavaScript APIs that developers will love using.
Read more

Designing Javascript APIs - Filepicker - Easy, Powerful ...

Posted November 1st, 2012 by admin & filed under Thoughts and Knowledge. We at spend a lot of time thinking about APIs. With the release of ...
Read more

Secrets of Awesome JavaScript API Design - Web Standards ...

Great API design equals great user experience. Brandon details how JavaScript API builders can design great experiences by following principles found in ...
Read more

JavaScript API Design Principles - InfoQ: Software ...

Ariya Hidayat discusses principles for designing JavaScript APIs by observing the interactions between modules, particularly the influence of an ...
Read more

api design - Good Practices in JavaScript API Development ...

What's a good approach to designing a JavaScript API? I'm relatively new to JavaScript and learning the key good features of the language, mostly from ...
Read more

How to Design a Good API and Why it Matters

How to Design a Good API and Why it Matters Why is API Design Important to You? •If you program, you are an API designer
Read more

JavaScript Web APIs - W3C - World Wide Web Consortium

JavaScript Web APIs; JavaScript Web APIs. On this page → what is scripting • what scripting interfaces are available • beyond scripting •
Read more

api design - Best practices and guidelines for designing ...

What are some guidelines and best practices that I can adhere to while designing an API? At the bare minimum, I know that an API should be easy to use and ...
Read more

h4/designing-javascript-apis-usability · GitHub

designing-javascript-apis-usability - Designing Better JavaScript APIs. Skip to content. Sign up Sign in. This repository. Explore; Features; Enterprise ...
Read more