Get Build Number with REST API

Article ID:360028147532
2 minute readKnowledge base

Issue

Using the REST API, how do I trigger a new build for a job, and get the build number for that new build?

Resolution

1. Modify JENKINS_URL, USER, and API_TOKEN in the following script to match your specific environment to start a non-parameterized build from a shell script:

#!/bin/bash
BUILD=$1
JENKINS_URL=https://jenkins.example.com
USER=admin
API_TOKEN=11605789ab3612a2193b982b07ed32468b

JENKINS_CRUMB=$(curl -q -u ${USER}:${API_TOKEN} "${JENKINS_URL}/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)")

curl -u ${USER}:${API_TOKEN} -H "${JENKINS_CRUMB}" -i -X POST ${JENKINS_URL}/job/${BUILD}/build

This will yield the following output:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    46  100    46    0     0   5270      0 --:--:-- --:--:-- --:--:--  5750
HTTP/1.1 201 Created
Date: Wed, 15 May 2019 15:52:26 GMT
X-Content-Type-Options: nosniff
Location: https://jenkins.example.com/queue/item/5/
Content-Length: 0
Server: Jetty(9.4.z-SNAPSHOT)
The queue URL (in this example https://jenkins.example.com:8080/queue/item/5/) will expire 5 minutes after the queue item is assigned a build number for the job so the URL will stay valid even if the build sits in the build queue for a long time.

2. Use curl to query api/ of the Location URL from Step 1 to get the build number

curl -u ${USER}:${API_TOKEN} -H "${JENKINS_CRUMB}" 'https://jenkins.example.com/queue/item/5/api/json?pretty=true'

This will yield the following output:

{
...
"executable" : {
"_class" : "hudson.model.FreeStyleBuild",
"number" : 5
"url" : "https://jenkins.example.com:8080/job/test/5/"
}

3. The URL (in this example https://jenkins.example.com:8080/job/test/5/) will be there once the queue item gets assigned a build number.

This article is part of our Knowledge Base and is provided for guidance-based purposes only. The solutions or workarounds described here are not officially supported by CloudBees and may not be applicable in all environments. Use at your own discretion, and test changes in a safe environment before applying them to production systems.