Taming the Jenkins JSON API with Depth and "Tree"

Written by: Michael Neale

3 min read

Jenkins has a neat JSON api - which can expose or as much or as little as you want (and even do JSON-P to boot - for direct browser shenanigans). For the api purposes, you can think of Jenkins as a tree of interesting data.

You can control the "depth" of what the api returns when you do  GET on it -  depth tells it how deep to go. (?depth=X query parameter). So if you hit up your jenkins /api/json url - you can see everything down to a certain "depth". You can of course drill down - but if you have a lot of builds/jobs, then you can end up repeatedly loading data for each job - it is nice to get the data you want with one call of the api!

In one case I had, the difference between depth 2 and depth 3 was about 3MB of data *per request*. Ouch.

There is, however, a nicer way to control the data back - the "tree" query parameter - here you specify what elements and sub elements of a tree you want returned (nesting as needed) - this simple thing lets you craft a URL that specifies just the data you want back (at the cost of a horrendously long url that takes some time to tune) - this is also more efficient than filtering data as it was never generated and returned in the first place.

For example, https://yourjenkins/api/json?depth=2&pretty=true  will return something like:

Don't worry - I can't read it either. It is a bit of a "death ray" of data - let alone if you go deeper to get the data you want. If you are loading this into a client or browser this can hurt a lot.

However, the tree query parameter to the rescue (tweak the URL):

&tree=jobs[name,lastBuild[number,duration,timestamp,result,changeSet[items[msg,author[fullName]]]]]

And you see something neat like this:

This is a lot more manageable (and in my case, exactly what I wanted and no more).

The whole point of this is to be explicit over what elements of the tree you want, and what fields.
In the above, I am saying I only want to know about "jobs", and the "name" and "lastBuild" fields etc. Of course - you can nest these structures - so you end up with an odd looking but powerful url that tells Jenkins to only return what you care about.

The pattern is tree=keyname[field1,field2,subkeyname[subfield1]] and so on.

Hit up your Jenkins /api to find out more.

Hope this saves you some time. 


Learn more about managing and scaling Jenkins for the enterprise with this eBook.

Stay up to date

We'll never share your email address and you can opt out at any time, we promise.