This is an old revision of the document!


Zotero API documentation

This documentation is a work in progress, and at this stage you see many TODO entries in the list. There are also things I haven't thought of. If you end up writing code that interacts with the Zotero API, please consider adding to the list below so that source-diving within the zotero XPI can become a thing of the past.

The simplest Zotero development environment

The two easiest way to set up a development environment for Zotero is with the Firefox extension Plain old Webserver (POW) which runs a web server inside of Firefox. POW can use server side Javascript to dynamically create pages, and as such all of the Zotero internals are accessible to code running within this web server.

An example of getting POW to interact with Zotero which creates a rich annotated bibliography from data stored inside zoters is available as a from here. This shows how simple it is to deploy code using POW to other users once they have installed the Firefox extension.

The second simplest development environment

There are a number of suitable interactive javascript environments for interacting with Firefox's internals (FireBug is not suitable). The suitable extensions that I have been able to find are:

  1. Chickenfoot A simplified javascript development environment that uses enhanced javascript to get the job done (think simplified API).
  2. MozRepl, an interactive shell available by telnetting to localhost on port 4242 (by default). Linux and Mac OS X users can use the built in telnet client. Windows users should use Putty.
  3. A Firefox plugin to provide MozRepl access directly inside firefox .
  4. The ExecuteJS extension.

Setting up a Firefox development environment is beyond the scope of this document.

Perl programmers should be aware of the MozRepl CPAN module, and the closely related MozRepl::RemoteObject which allows you to access Javascript objects from inside perl programs.

A problem with MozREPL: With a longer script I've had trouble with MozRepl timing out on me for no apparent reason. The solution to this is to either send the code to the terminal application in smaller sized chunks, or to keep pasting the code in until it works. Unfortunately in some cases missing semicolons and curly brackets can cause silent failure in the REPL as well which means that debugging longer bits of code can be interesting. Avoid this by avoiding excessively long blocks of procedural code - factor everything into smaller functions wherever possible.

Zotero API Howtos

The Zotero API is under-documented, and at present requires a lot of looking around in the source code. The most useful parts of the source code are in chrome/content/zotero/xpcom and xpcom/data, and the chrome/content/zotero (particularly overlay.js and fileInterface.js)

Create new Zotero object

This is the first thing that you need to do when interacting with zotero's internals. The code to do so is:

    var Zotero = Components.classes["@zotero.org/Zotero;1"] .getService(Components.interfaces.nsISupports).wrappedJSObject;

Get the Zotero Pane to interact with the Zotero GUI

var ZoteroPane = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser").ZoteroPane;

Then grab the currently selected items from the zotero pane:

//get first selected item
var selected_items = ZoteroPane.getSelectedItems();
var item = selected_items[0];
 
// proced if selected item is neither a collection nor a note
if ( ! item.isCollection() & ! item.isNote()) {
    if (item.isAttachment()) {
        // find out about attachment
    }
    if (item.isRegularItem()) {
        // we could grab attachments:
        // var att_ids = item.getAttachments(false);
        // if (att_ids.length>1) exit(); // bailout
        // item_att=Zotero.Items.get(att_ids[0]);
    }
    alert(item.id);
}

If you are focused on data access, then the first thing you will want to do will be to retrieve items from your zotero. Creating an in-memory search is a good start.

    var search = new z.Search(); 

Search for items containing a specific tag

Starting with the code from “Setup a Zotero search” we then use the following code to retrieve items with a particular tag:

    search.addCondition('tag', 'is', 'tag name here');

Zotero Collection Operations

Get the collection tree and display as a series of nested ordered lists

This code was developed in the firefox extension Plain Old Webserver server side javascript. Note that it's a recursive function. With a bit of jquery the nested ordered list can be easily transformed into a tree widget.

var Zotero = Components.classes["@zotero.org/Zotero;1"] .getService(Components.interfaces.nsISupports).wrappedJSObject;
 
var render_collection = function(coll) {
    if (!coll) { 
        coll = null; 
    }
    var collections = Zotero.getCollections(coll);
    document.writeln("<ul>");
    for (c in collections) {
        document.writeln('<li>' + '<a href="view_collection.sjs?name=' + encodeURI(collections[c].name) + '&id=' + collections[c].id + '">' + collections[c].name  + '</a></li>');
        if (collections[c].hasChildCollections) {
	   var childCol = render_collection(collections[c].id);
        }
    }   
    document.writeln("</ul>");
}
 
render_collection();

Get the items for a particular collection

var Zotero = Components.classes["@zotero.org/Zotero;1"] .getService(Components.interfaces.nsISupports).wrappedJSObject;
var collectionid = pow_server.GET.id; // or some other way of finding the collectionID here
var collection = z.Collections.get(collectionid);
var items = collection.getChildItems();
// or you can obtain an array of itemIDs instead:
var itemids = collection.getChildItems(true);

TODO

Zotero Search Basics

var s = new Zotero.Search();
s.addCondition('joinMode', 'any'); // joinMode defaults to 'all' as per the 
                                        // advanced search GUI

To add the other conditions available in the advanced search GUI, use the following:

s.addCondition('recursive', 'true');  // equivalent of "Search subfolders" checked
s.addCondition('noChildren', 'true'); //               "Only show top level children
s.addCondition('includeParentsAndChildren', 'true');   "Include parent and child ..."

There are also some “hidden” search conditions around line 1735 of chrome/content/zotero/xpcom/search.js in the zotero source code (although some should only be used internally). [TODO remove mention of source code and enumerate all conditions]

One example is:

s.addCondition('deleted', 'true');  // Include deleted items

Search by collection

To search for a collection or a saved search you need to know the ID:

<source javascript> s.addCondition('collectionID', 'is', collectionID); s.addCondition('savedSearchID', 'is', savedSearchID); </source>

Search by tag

To search by tag, you use the tag text:

<source javascript>

  var tagname = 'something';
  search.addCondition('tag', 'is', tagname);

</source>

Search by other fields

The complete list of other fields available to search on is on the search_fields page.

Combining search terms

TODO

Complete list of search operators

TODO (should be pretty easy)

Complete list of search fields

TODO (with description of what the more obscure fields mean - e.g. abstractNote for abstract, and how do we search the fulltext archive?)

Once the search conditions have been set up, then it's time to execute the results:

   var results = search.search();

This returns the item ids in the search as an array [I could be wrong … ]. The next thing to do is to get the Zotero items for the array of IDs:

    var items = z.Items.get(results);

Getting a bibliography for an array of items:

Here we use zotero's quickcopy functions to get a bibliography in the style specified in Zotero's preferences.

First we start with a list of as in the previous entry.

  var qc = z.QuickCopy;
  var biblio = qc.getContentFromItems(new Array(item),
                                      z.Prefs.get("export.quickCopy.setting"));
    var biblio_html_format = cite.html;
    var biblio_txt         = cite.text; 

TODO: get citations. change the style. get stuff in other formats, especially RTF

Get information about an item.

TODO: need to list all the possible fields here, and what kind of entry they belong to.

To get an item's abstract, we get the 'abstractNote' field from the Zotero item:

    var abstract = item.getField('abstractNote'); 

Get fulltext for an item.

TODO

Get stored attachements for an item

TODO

Get child notes for an item

To get the child notes for an item, we use the following code:

     var notes = item.getNotes(); 

This returns an array of notes. Each note is in HTML format. To get each note in turn we just iterate through the array:

    for (var j=0;j<notes.length;j++) {
        var note = z.Items.get(notes[j]);
        var note_html = note.getNote;
    } 

This technique works for anything that can have related items attached within the zotero database. This includes items and notes.

  var related_items = item.relatedItemsBidirectional 

This returns a list of items just like in the search examples.

Get an Item's Attachments

Here's some example code to get the full text of html and pdf items in storage and puts the data in an array:

var item = 'some item' ; // some Zotero Item obtained previously
var fulltext = new Array;
if (item.isRegularItem()) { // not an attachment already
    var attachments = selected_items[item].getAttachments(false);
    for (a in attachments) {
        var a_item = Zotero.Items.get(attachments[a]);
        if (a_item.attachmentMIMEType == 'application/pdf'
            || a_item.attachmentMIMEType == 'text/html') {
            fulltext.push(a_item.attachmentText);
        }
    }
}

Generic XUL Javascript to provide support functions

Writing out a file:

This function will write out a file to a specified filename. If the file already exists it will be silently overwritten. [TODO: obviously this needs to be cleaned up, talk about append mode as well, and failure if file already exists …]

Note that Plain Old Webserver contains quite a few simplified support functions for reading, writing and deleting files, including new bits of javascript, and generally making things nice and easy.

  function writeFile(filename, data)    {
      var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
      var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
      file.initWithPath(filename); 
      foStream.init(file, 0x02 , 00666, 0);
      foStream.write(data, data.length);
      foStream.close();
  };
 
  writeFile("/tmp/boo.txt", "boo\n"); 

Or just use Zotero.File.putContents(str)…

TODO

many other things :)