Skip to main content

Working with REST API

1. Authenticating API Requests

Method Description Notes
API Token Generate an API token from Jenkins UI under User Configuration Use as Authorization: Token <token>
Jenkins Crumb Include a crumb in requests to prevent CSRF attacks Fetch with GET /crumbIssuer/api/json
Basic Auth Use username/password for authentication Base64 encode username:password in header

Example: Using API Token

curl -H "Authorization: Token <your-api-token>" \
  http://jenkins.example.com/api/json

Example: Using Crumb with Token

CRUMB=$(curl -s "http://jenkins.example.com/crumbIssuer/api/json" | jq -r .crumb)
curl -H "Authorization: Token <your-api-token>" \
     -H "Jenkins-Crumb: $CRUMB" \
  http://jenkins.example.com/api/json

2. Getting Job Information

Property Description Example
jobName Name of the Jenkins job build-app
jobUrl URL to the job in Jenkins http://jenkins.example.com/job/build-app/
buildNumber Build number of the job 123
buildStatus Status of the build (SUCCESS, FAILURE, etc.) SUCCESS
lastBuildTime Timestamp of the last build 2025-04-05T10:30:00Z

Example: Fetching job information via REST API

curl -X GET "http://jenkins.example.com/job/build-app/lastBuild/api/json" \
  -H "Authorization: Basic <base64-encoded-credentials>"

Example: Parsing job information response

const jobInfo = {
  name: "build-app",
  url: "http://jenkins.example.com/job/build-app/",
  lastBuild: {
    number: 123,
    status: "SUCCESS",
    timestamp: "2025-04-05T10:30:00Z"
  }
};

3. Triggering Builds

Method Endpoint Description Notes
POST /job/<jobName>/build Triggers a build for the specified job Requires Build permission
POST /job/<jobName>/buildWithParameters Triggers a build with parameters Requires Build permission and job must support parameters

Example: Triggering a Build

curl -X POST http://jenkins.example.com/job/myJob/build \
  --user "username:apiToken"

Example: Triggering a Build with Parameters

curl -X POST "http://jenkins.example.com/job/myJob/buildWithParameters?param1=value1&param2=value2" \
  --user "username:apiToken"
Note: The buildWithParameters endpoint supports passing parameters as query string arguments. Ensure parameter names match those defined in the job configuration.

4. Getting Build Status

Property Description Example
buildNumber Unique identifier for the build 123
result Outcome of the build (SUCCESS, FAILURE, ABORTED) SUCCESS
timestamp Start time of the build in milliseconds 1634567890000
duration Duration of the build in milliseconds 45000
url Full URL to the build page https://jenkins.example.com/job/myjob/123/

Example: Fetching Build Status via API

curl -X GET "https://jenkins.example.com/job/myjob/123/api/json" \
  -H "Authorization: Basic base64credentials"

Example: Parsing Build Status Response

const buildStatus = {
  "number": 123,
  "result": "SUCCESS",
  "timestamp": 1634567890000,
  "duration": 45000,
  "url": "https://jenkins.example.com/job/myjob/123/"
};
Note: The result field can be SUCCESS, FAILURE, ABORTED, or NOT_BUILT.

5. Using Build Parameters in API

Parameter Type Description Example
buildId string Unique identifier for the build 123
parameterName string Name of the parameter to set environment
parameterValue string Value to set for the parameter production

Example: Setting Build Parameters via API

curl -X POST "http://jenkins.example.com/job/myjob/123/parameterizedBuild" \
  -d "environment=production" \
  -H "Content-Type: application/x-www-form-urlencoded"
Note: Build parameters must be defined in the job configuration to be used via API.

6. Getting Queue Information

Property Description Example
queue.url URL to get queue information http://jenkins.example.com/queue/api/json
queue.items List of items in the queue [{ "id": 123, "task": { "name": "build-job" } }]

Example: Fetch Queue Information via API

curl -X GET "http://jenkins.example.com/queue/api/json"
Note: The queue API returns a JSON object containing details about jobs currently in the build queue.

7. Using JSON API

Endpoint Method Description Notes
/api/json GET Retrieve general API information Returns a JSON object with API version and other metadata
/job/{jobName}/api/json GET Get job details Includes build history, parameters, and configuration
/job/{jobName}/build POST Trigger a new build Requires authentication and job permissions
/job/{jobName}/buildWithParameters POST Trigger a build with parameters Allows passing parameters to the build
/job/{jobName}/lastBuild/api/json GET Get last build details Includes status, duration, and console output

Example: Triggering a Build with Parameters

curl -X POST "http://jenkins.example.com/job/MyJob/buildWithParameters?token=secretToken&param1=value1&param2=value2" \
  -H "Authorization: Basic base64encodedcredentials"

Example: Fetching Job Configuration

{
  "name": "MyJob",
  "url": "http://jenkins.example.com/job/MyJob/",
  "buildable": true,
  "lastBuild": {
    "number": 123,
    "url": "http://jenkins.example.com/job/MyJob/123/"
  },
  "builds": [
    {
      "number": 123,
      "url": "http://jenkins.example.com/job/MyJob/123/"
    }
  ]
}
Note: The JSON API is the preferred method for programmatic access to Jenkins. It supports filtering, pagination, and detailed build information.

8. Using XML API

Endpoint Description Notes
/api/xml Provides XML representation of Jenkins API Useful for automation and integration with tools that consume XML
/api/xml?tree=jobs[name,buildable] XML API with tree filter Allows filtering of response fields using tree syntax

Example: Fetching job information via XML API

curl -X GET "http://jenkins.example.com/api/xml?tree=jobs[name,buildable,lastBuild[number,result]]" -H "Authorization: Basic base64encodedcredentials"
Note: The XML API is deprecated in favor of the JSON API. Consider migrating to the JSON API for better performance and feature support.

9. Using Python API

The Jenkins Python API allows developers to interact with Jenkins programmatically using Python. It provides a convenient way to automate tasks such as job creation, build triggering, and status monitoring.

Method Description Example
Jenkins() Initialize a Jenkins instance
from jenkins import Jenkins
server = Jenkins('http://localhost:8080', username='admin', password='password')
get_jobs() Retrieve list of all jobs
jobs = server.get_jobs()
for job in jobs:
    print(job['name'])
build_job() Trigger a build for a specific job server.build_job('my-job')
get_build_info() Get details about a specific build
build_info = server.get_build_info('my-job', 1)
print(build_info['result'])

Example: Get job status

from jenkins import Jenkins

server = Jenkins('http://localhost:8080', username='admin', password='password')
job_name = 'test-job'
build_number = 1

try:
    build_info = server.get_build_info(job_name, build_number)
    print(f"Build #{build_number} status: {build_info['result']}")
except Exception as e:
    print(f"Error retrieving build info: {e}")
Note: Ensure that the Jenkins server has the python plugin installed and configured to allow API access.
Warning: The Python Jenkins API requires proper authentication and authorization to interact with the Jenkins server.

10. Canceling Builds via API

Endpoint Method Description
/job/<jobName>/build/<buildNumber>/stop POST Cancel a specific build by job name and build number

Example: Canceling a Build

curl -X POST http://jenkins.example.com/job/MyJob/build/123/stop \
  -H "Authorization: Bearer <token>"
Note: The build must be in progress to be cancelable. If the build has already completed or is queued, this action will have no effect.

Was this article helpful?