Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using Jenkins REST API

Introduction

The Jenkins REST API allows users to interact programmatically with Jenkins' features, enabling automation and integration with other tools. This lesson provides a comprehensive overview of how to use the Jenkins REST API effectively.

Key Concepts

What is Jenkins REST API?

The Jenkins REST API is a set of HTTP endpoints that allow users to interact with Jenkins server via standard HTTP methods (GET, POST, PUT, DELETE).

Key API Endpoints

  • Get job details: /job/{jobName}/api/json
  • Trigger a build: /job/{jobName}/build
  • Get build status: /job/{jobName}/{buildNumber}/api/json
  • Get all jobs: /api/json

Authentication

To access the Jenkins API, you may need to authenticate. Jenkins supports multiple authentication methods:

  • Basic Authentication using username and API Token.
  • Using a Jenkins crumb for anti-CSRF protection.
Note: Always use HTTPS to protect your credentials and API tokens.

Making API Requests

API requests can be made using tools like curl, Postman, or directly from your application code. Below is an example using curl:

curl -u username:api_token http://your-jenkins-url/job/job-name/api/json

Code Examples

Triggering a Build

Here’s a Python example that triggers a Jenkins job using the REST API:

import requests

url = "http://your-jenkins-url/job/job-name/build"
response = requests.post(url, auth=('username', 'api_token'))

if response.status_code == 201:
    print("Build triggered successfully!")
else:
    print("Failed to trigger build:", response.status_code)

Getting Job Status

Example to get the status of the last build:

import requests

url = "http://your-jenkins-url/job/job-name/lastBuild/api/json"
response = requests.get(url, auth=('username', 'api_token'))

if response.status_code == 200:
    data = response.json()
    print("Last build status:", data['result'])
else:
    print("Failed to get job status:", response.status_code)

Best Practices

  • Utilize API tokens instead of passwords for authentication.
  • Implement rate limiting in your application to avoid overwhelming the Jenkins server.
  • Use webhooks to trigger builds rather than polling Jenkins constantly.

FAQ

What is the base URL for Jenkins REST API?

The base URL for the Jenkins REST API is typically http://your-jenkins-url/.

Can I use the Jenkins REST API without authentication?

It depends on your Jenkins security settings. If security is enabled, authentication is required.

How do I get the API token for a user?

Go to the user configuration page in Jenkins, and you will find an option to generate an API token.