How can query Jenkins using API to know the last few builds that it executed. I don't know the name of build jobs. I just want Jenkins to return the last n builds it executed or the builds executed between 2 timestamps
-
Try this solution: https://stackoverflow.com/a/54191349/1805453 – DawnPaladin Feb 13 '19 at 19:00
2 Answers
In order to query build results via API , you have to know the job name in Jenkins. You have to append your jenkins job URL with the this suffix /api/json
to get the JSON data String.
For ex: If your Jenkins server has a job named A_SLAVE_JOB , then you have to do a HTTP GET in your java rest client at this end point : http://<YourJenkinsURL>:<PortNumber>/job/A_SLAVE_JOB/api/json
This shall return a String with all the build history URL (with numbers), Last successful build and last failed build status.
You can traverse the subsequent build of a given job using a for loop. All you need is a JSON parser for extracting values from keys in JSON string. You can use org.json
library in java to do the parsing. A pseudocode sample goes like this :
import org.json.*;
class myJenkinsJobParser {
public static void main(String... args){
JSONObject obj = new JSONObject("YOUR_API_RESPONSE_STRING");
String pageName = obj.getJSONObject("build").getString("status");
JSONArray arr = obj.getJSONArray("builds");
for (int i = 0; i < arr.length(); i++)
{
String url = arr.getJSONObject(i).getString("url");
// just a psuedoCode......
}
}
}

- 1,776
- 3
- 20
- 29
Just to summarize. The way you have to request info. Below number 0, 5 it's range of latest 5 builds.
curl -g "${SERVER}/job/${JOB}/api/json?pretty=true&tree=builds[number,url,result]{0,5}" \
--user $USER:$TOKEN

- 5,538
- 4
- 24
- 53