Skip to content
David E. Wheeler edited this page May 13, 2011 · 5 revisions

JSONP

All API Sever APIs that return the content type application/json are JSONP-enabled. To use it, simply pass the callback query parameter in the URL-encoded GET query string. The returned content type will be changed to text/javascript and the JSON contents wrapped in the function call specified by the callback parameter. This enables web applications to easily process JSON APIs via a callback function.

Note that this functionality is provided only by APIs provided by the API Server. Mirror servers do not provide JSONP callback functionality.

Here's a quick example of how it works. First a regular JSON request, returned with the content type application/json:

> curl http://api.pgxn.org/tag/md5.json
{
   "releases": {
      "sha": {
         "abstract": "This module provides datatypes for storing SHA-1, SHA-2 and MD5 hashes",
         "stable": [{ "date": "2011-03-16T10:33:00Z", "version": "1.0.0" } ]
      }
   },
   "tag": "md5"
})

Now we add callback=foo, which returns content-type text/javascript:

> curl 'http://api.pgxn.org/tag/md5.json?callback=foo'
foo({
   "releases": {
      "sha": {
         "abstract": "This module provides datatypes for storing SHA-1, SHA-2 and MD5 hashes",
         "stable": [{ "date": "2011-03-16T10:33:00Z", "version": "1.0.0" } ]
      }
   },
   "tag": "md5"
})

This can be especially handy for web applications. Say you're a PGXN user and want to show off a list of distributions you've released on PGXN in a sidebar on your blog. You might do something like this:

function pgxn_distros(data) {
    document.write('<dl>');
    for (dist in data.releases) {
        document.write(
            '<dt><a href=http://pgxn.org/dist/' + dist +
            '>' + dist + '</a></dt>' +
            '<dd>' + data.releases[dist].abstract + '</dd>'
        );
    }
    document.write('</dl>');
}

And then to use it, it's just:

<h2>Recent PGXN Releases</h2>
<script type="text/javascript"
         src="http://api.pgxn.org/user/theory.json?callback=pgxn_distros">
</script>
Clone this wiki locally