BearPanther.com

Using JSONP APIs

Introduction

user

bear


LATEST POSTS

Using jsformat with Sublime Text 26th July, 2014

There are many d3 demos like this but this one is mine 08th June, 2014

Blog

Using JSONP APIs

Posted on .

Everybody loves JSON. (No, I don’t have any links to back that up.) And for good reason– browsers are fluent in it, it’s easy to generate, easy to parse and lightweight enough to make it the ideal way to communicate with web services.

JSONP (the P is for padding) is a well known technique to get around web browsers’ same origin policy. By circumventing the same origin policy, JSONP removes the need to do any server-side work to access cross domain resources. CORS obsoletes JSONP, but until it’s more widely implemented, JSONP will continue to have a prominent place in any web developer’s toolkit.

Most modern web services support JSON as a response format but not all support JSONP. The key to supporting JSONP is for services to include a callback name parameter. What that means is, the server returns a text response in JSON format and wraps that JSON in a callback function. When the client receives the response, it injects it into a script tag where the browser immediately executes the callback function. After the callback function executes, the JSON text from the server is now be accessible to the client as a JavaScript object. Pretty slick, right?

Fortunately, when using any of the popular JavaScript libraries, you don’t need to worry about manually injecting a script tag to execute a callback function. It’s good to know how that works (create a script tag, set the tag’s src attribute, add the script tag to the DOM) but As a web developer in 2012, all you need to worry about is supplying the proper parameters for a web service and your JavaScript library of choice will do the rest for you.

The Instagram app that I’ve been talking about the last few posts takes full advantage of JSONP to talk to multiple web services. The obvious one is Instagram. Being the cool kids that they are, they provide an easy to use JSONP API. The bearpanther.InstagramSearch class uses esri.request (which uses dojo.io.script.get under the hood) to talk to Instagram. The app’s bearpanther.BingGeocode class also uses JSONP to retrieve geocoding results from bing. Finally, the ArcGIS API for JavaScript uses JSONP extensively to talk to ArcGIS Server services.

So there you have it, JSONP APIs. This has been post number three of five discussing the techniques and technologies used to build bearpanther’s instamap.

Comments

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

View Comments (1) ...