How to use the OpenCorporates API, Part 1: widgets

Just before Christmas, we introduced the new OpenCorporates API, which allows access to all the information in OpenCorporates, including allowing searching. We said then that we’d give some examples of how to use the API, and the first one is a simple javascript widget that can be included on any web page that allows you to add javascript.

We’re going to split this post into two parts. The first is for those who have no knowledge of javascript, and just want to add the widget; the second for those who want to understand how it works.

The widget is simple both to install and use, and allows visitors to your site or blog to search for companies by name without leaving the site. There’s a demo page at so you can try it out:

OpenCorporates demonstration widget

When you search, it simply adds the results below the search box:

1. Installing the widget

If ever added a widget to your site or blog, this should be very familiar. All you need to do is to paste these two lines inside the HTML wherever you want it to appear:

…and that’s it! If you want to change the styling, you can – just have a look at the CSS that’s pulled in by the javascript, and override it in your own CSS file.

2. Understanding how the widget works

The widget has two parts. The second part is an empty <div> element that will hold the widget content; the first imports a javascript file from and runs the javascript within it. This file has been ‘minified’ to remove all the redundant spaces and comments, so it’s easier instead to look at the commented, nicely spaced version at .

The first part is semi-boilerplate, which checks whether a useful javascript code library called jQuery is available and if not loads it (if you were writing your own widget just for your website and already include this you could omit most of this). When it’s finished loading it, and the document itself has finished loading, it runs the setupDocument() function:

function setupDocument () {
var form_stuff = '';
  form_stuff += '&lt;div class=&quot;ocwidget-header&quot;&gt;
&lt;h3&gt;&lt;a href=&quot;;&gt;OpenCorporates company search&lt;/a&gt;&lt;/h3&gt;
&lt;div class=&quot;scope&quot;&gt;30 million companies, 35 jurisdictions&lt;/div&gt;
&lt;/div&gt;\n&lt;form id=&quot;ocwidget-search&quot; class=&quot;search&quot; action=&quot;; method=&quot;get&quot; accept-charset=&quot;UTF-8&quot;&gt;
&lt;div style=&quot;margin: 0; padding: 0; display: inline;&quot;&gt;&lt;input type=&quot;hidden&quot; name=&quot;utf8&quot; value=&quot;✓&quot; /&gt;&lt;/div&gt;\n&lt;input id=&quot;openc_api_search_q&quot; type=&quot;text&quot; name=&quot;q&quot; /&gt;\n&lt;input class=&quot;button&quot; type=&quot;submit&quot; name=&quot;commit&quot; value=&quot;Search&quot; /&gt;\n&lt;/form&gt;
&lt;div class=&quot;loading&quot; style=&quot;display: none;&quot;&gt;Searching...&lt;/div&gt;
&lt;div id=&quot;ocwidget-result&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;ocwidget-footer&quot;&gt;Powered by &lt;a href=&quot;;&gt;OpenCorporates :: The Open Database Of The Corporate World&lt;/a&gt;&lt;/div&gt;';
 jQuery(&quot;#ocwidget-search&quot;).submit(function(event) {
 if (jQuery(&quot;#ocwidget-result&quot;).is(&quot;:visible&quot;)) {jQuery(&quot;#ocwidget-result&quot;).slideUp(&quot;slow&quot;);}
 var $form = jQuery( this ),
 term = $form.find( 'input[name=&quot;q&quot;]' ).val(),
 url = $form.attr( 'action' ).replace('http://','http://api.') + '/search?callback=?';
 jQuery.getJSON( url, { q: term },
 function( data ) { insertCompanyData(data, term); }

This function builds the basic HTML for the widget (first the CSS style and then the HTML itself), and puts it in the div you’ve already got on the page.

Next it uses jQuery to add a listener to the form you’ve just put on the page, looking out for when the submit action happens, and running the function attached when this happens. And that’s it for the setup. The rest is dealing with what happens when a form is submitted.

When this does happen, the first thing is that the normal behaviour of the submit button – to make a fresh HTTP request and treat the response as a new page – is disabled. Then if the results area is visible (i.e. because a search has already been made), it’s slid out of the way. Next a ‘Searching…’  message is shown to let the user know something’s happening.

After that the information on the form is obtained and submitted  via the jQuery.getJSON call. This makes an Ajax request to the url, and does something with the result, in this case runs the function insertCompanyData(data, term). A couple of things worth noticing here:

  • The URL in the form isn’t actually for the OpenCorporates API, but for the main OpenCorporates websites. There’s no reason why you couldn’t use the API address in the form, but as this is, in part, a demonstration of how to use the API, and some people might want to use the javascript not as a widget but as a javascript-enabled HTML form on their website, it was worth showing a some nice graceful degradation. By using the OpenCorporates URL on the form, if javascript isn’t enabled  (e.g. visitors using screenreaders) the search will still work.
  • We’ve added ‘?callback=’ to the URL. This tells jQuery we want to make a JSONP request, and that it should add a callback parameter, and handle the JSONP response accordingly. This gets over the ‘same-origin policy‘, which prevents scripts handling data from a different domain than you’re already on. It’s the fix that allows all these javascript widgets to work, but does require the API to understand and handle callback requests. Fortunately the OpenCorporates API does 😉

Having made the request, the browser gets on with whatever it was doing, until the response comes back, and the the data (together with the term we searched for) is passed to  insertCompanyData():

function insertCompanyData (data, term) {
var companies = data.companies;
content = &quot;&lt;div class='summary'&gt;Found &lt;a href='; + term + &quot;'&gt;&quot; + data.total_count + &quot; results&lt;/a&gt;&lt;/div&gt;&quot;;
content += listAll(companies);
jQuery(&quot;.ocwidget-container .loading&quot;).hide();
jQuery( &quot;#ocwidget-result&quot; ).html(content).slideDown(&quot;slow&quot;);

This does what it says on the can, building up the results content with some useful information (the total number of responses, with a link to all the results on OpenCorporates). It iterates through each of the companies returned (via the listAll function), and then uses listItemFor to build up a <li> list element for each, consisting of the company name and link to the company page on OpenCorporates, the incorporation date if known, the curent status, and the jurisdiction code, which is made a little more readable by converting ‘gb’ to ‘GB’, and us_dc to US (DC). A CSS class is also added if the company is inactive, to allow us to show those in a different colour.

function listItemFor(company) {
  var jurisdiction = company.jurisdiction_code.replace(/_(\w+)/,&quot; ($1)&quot;).toUpperCase();
  var li = &quot;&lt;li class='&quot; + (company.inactive ? 'inactive' : '') + &quot;'&gt;&quot;;
  li += &quot; &lt;a class='company' href='&quot; + company.opencorporates_url + &quot;'&gt;&quot; + + &quot;&lt;/a&gt;, &quot; + jurisdiction;
  li += company.incorporation_date ? ', ' + company.incorporation_date : &quot;&quot;;
  li += company.current_status ? ', ' + company.current_status : &quot;&quot;;
  li += &quot;&lt;/li&gt;&quot;;
  return li;

function listAll(coll) {
  if(coll.length &amp;&amp; coll.length &gt; 0){
    var listResult = &quot;&lt;ul&gt;&quot;;
    for (var i = 0; i &lt; coll.length &amp;&amp; i &lt; 8; i++) {
      var li = coll[i].company;
      listResult += listItemFor(li);
    listResult += &quot;&lt;/ul&gt;&quot;;
    return listResult;
  else { return '';}

And that’s it. It’s on GitHub, so feel free to fork it, or use the code for your own purposes, but please remember that OpenCorporates is under the Open Database Licence and so if you’re using the API, you must link back to the OpenCorporates as per the links requirements.

4 thoughts on “How to use the OpenCorporates API, Part 1: widgets

  1. This is great! Nice job.

    Have you considered using something like MustacheJS to separate the HTML-building from the rest of the code so you can change the templates without pulling teeth? Might also allow savvy developers to override the templates themselves.

    1. That might be a good idea. Haven’t used MustacheJS, and was conscious not to introduce too many dependencies, but anything that makes it easier for people…Another thing we could do is allow filtering by jurisdiction, or show details for a company when the link is clicked. Maybe we should have a competition for the best widget or mobile app using the API…

  2. Do you use RDF for your data? Is it possible to query OpenCorporates via a SPARQL endpoint? If not, is it possible to send a batch request to an OpenCorporates web service?

    1. We have a little RDF for some of the data. This will be extended and improved when we incorporate the new EU/W3c Business Vocabulary. We don’t have a SPARQL endpoint present, as there isn’t the demand for it yet.

Comments are closed.