Running parameterized and non parameterized Jenkins job via its API and get results
Pre requestees-
Build Authorization Token Root Jenkins plugin should be isntalled before.https://plugins.jenkins.io/build-token-root/
Get an API token for your Jenkins user from
https://jenkins.com/user/myusername@skynet.com/configure
We can send an optional HEAD request to check Jenkins server is up.
{{base_url}}/api/json
You can check your user’s details and access is by sending a GET request with basic authentication username, API token.
username=myusername@skynet.com
password=API token
{{base_url}}/me/api/json/
This is basic authentication, so if you are using postman, can give like below in Authorization to run non-parameterized job.
URL-http://localhost:8080/job/FirstJob/build
Now, let’s try to send with parameters. from UI, you can get the exact URL by navigating to it.
https://jenkins.com/job/MyJenkinsFolder/job/MyJenkinsJobName/
After that append buildWithParameters as a path petameter,
https://jenkins.com/job/MyJenkinsFolder/job/MyJenkinsJobName/buildWithParameters
We could send a POST request , with parameters such as TestPlanName and NoOfReruns, if the request is a successes ,status code =201
TestPlanName=MyTestPlan.xml&NoOfReruns=2
So all together the post request is,
https://jenkins.com/job/MyJenkinsFolder/job/MyJenkinsJobName/buildWithParameters?TestPlanName=MyTestPlan.xml&NoOfReruns=2
Now, lets see how to send a GET request to see the execution status of the latest build.
https://jenkins.com/job/MyJenkinsFolder/job/MyJenkinsJobName/lastBuild/api/json
Above GET request gives below response We can use result field , to get the results of the Jenkins Job using “result” Key and value . Success for pass , null for ongoing Job and FAILURE for failure.
"id": "7",
"keepLog": false,
"number": 7,
"queueId": 11376969,
"result": "SUCCESS",
"timestamp": 1702883255878,
From above request’s id field contains the Jenkins build number, let’s say its 7 so using it we can the results as well.
https://jenkins.com/job/MyJenkinsFolder/job/MyJenkinsJobName/7/api/json
Similarly, we can get details about below values as per below by sending a get request.
lastStableBuild, lastSuccessfulBuild, lastFailedBuild, lastUnstableBuild, lastUnsuccessfulBuild, lastCompletedBuild
{{base_url}}/job/{{DirectoryName}}/job/{{JenkinJobName}}/lastFailedBuild/buildTimestamp
Also, if you have sufficient permission, you could enable and disable a Jenkins job via POST API request by passing enable and disable with credentials.
https://jenkins.com/job/myfolder/job/myJobName/enable
Send below GET request to Obtains a CSRF (Cross-Site Request Forgery) protection token, also known as a “crumb.”
{{base_url}}/crumbIssuer/api/json
Using building number 10, view build’s console log.
{{base_url}}/job/{{DirectoryName}}/job/{{JenkinJobName}}/10/consoleText
Refer-
Jenkins API
https://www.jenkins.io/doc/book/using/remote-access-api/