Page:Aaron Swartz s A Programmable Web An Unfinished Work.pdf/45

'''5. BUILDING A PLATFORM: PROVIDING APIS 33''' often has bugs... The quoter often has bugs... Only on rare joyous occasions does it happen that the parser and the quoter both misinterpret the interface in the same way.”).

XML combines the worst of both worlds: it is an incredibly complex system of parsing. Not surprisingly, XML has been responsible for hundreds of security holes.

So aside from being simpler, easier, more featureful, safer, and faster than XML, what does JSON have to offer? Well, it has one killer feature that’s guaranteed its place atop the format wars: because it’s based on JavaScript, it has a deep compatibility with web browsers.

You’ve probably heard about AJAX, a technique that uses the XmlHttpRequest function in modern web browsers to allow web pages to initiate their own HTTP requests to get more data. But, for security reasons, XmlHttpRequest is only permitted to request pages on the same domain as the web page it initiates from. That is, if your page is at http://www.example.net/foo.html it can request things like http://www.example.net/info.xml but not http://whitehouse.gov/data/dump.xml.

For APIs, this is kind of a disaster—the whole point of opening up your data on the web is so that other sites can use it. If you’re the only people who can access it, why go to the trouble?

Luckily, there’s one exception: JavaScript. A webpage can embed an HTML ‘ ‘ tag that points to any random site on the Internet. Even better, JavaScript code can arbitrarily add these script tags to the page. The browser then goes and fetches the page and tries to process it.

Now with regular JSON that wouldn’t be too useful—the browser would download a list or an object or something and wouldn’t know what to do with it. So instead of just returning the JSON, it returns the JSON wrapped in a function call:

>   myCallback([5, ‘‘foo"]);

Then you just have the function “myCallback” do whatever it was you wanted to do with the data.

Of course, if you’re doing lots of requests you’ll want to keep them all separate—they can’t all call myCallback. So you support a callback parameter that