Take the 2-minute tour ×
Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. It's 100% free, no registration required.

I had an idea for an app that required calling the stackapps API from JavaScript, but when I started prototyping it I quickly found out that the API does not allow cross origin requests. This means trying to retrieve the JSON object via JavaScript on another domain will fail because the browser will block it due to the same origin policy. This is usually an issue for Flash and Silverlight requests as well, but I do see that the API already implements the Flash crossdomain.xml (example) and Silverlight clientaccesspolicy.xml (example) files to allow cross origin requests using plugins.

While I could potentially use Flash or Silverlight instead of JavaScript, it is a pretty simple app that only needs access to a few method calls. Also I did already see a request for a JavaScript wrapper, however without allowing cross origin requests the wrapper would not be very useful. There are a few different methods of getting around the same origin policy, but most of them involve a lot of work or are not compatible with the IP based rate limiting used by the API. I think there are two main methods that could be used to allow access to the API using javascript:

  1. Add the Access-Control-Allow-Origin: * http header to all API methods. This allows cross domain requests using the XMLHttpRequest object in most browsers or XDomainRequest object in IE8.

  2. Add a type=jsonp parameter to each method that lets you use the On-Demand Javascript or JSON with Padding approach to get around the same origin policy by downloading the JSON object as a dynamic script tag instead of raw JSON text and then passing it to a user defined callback function.

Both approaches have their benefits and down sides, but I think the easiest approach would be to add the access control header. To show an example of the problem and potential solution I have setup a test page that should work with IE8, Firefox, Chrome, and Safari. The test page lets you try and download various files using the XMLHttpRequest or XDomainRequest objects and see how the same origin policy and access control header affects each of them. You can also use the web-sniffer.net site to check the HTTP headers for each requested URL.

share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

JSONP support was recently added to the API ( See this question ).

The name of the parameter to trigger padding is jsonp:

http://api.stackoverflow.com/0.8/tags?jsonp=blah

share|improve this answer
    
That will work. I tried checking the docs but it wasn't listed anywhere. I also tried searching for jsonp but I guess I missed the response in that question. Thanks! –  Greg Bray May 27 '10 at 19:52
add comment

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .