How to access Jenkins API Using Python

This Rest API tutorial help to access Jenkins using python. Jenkins is providing an API interface to access all resources. You can do all thing as you do in Jenkins UI using rest API. We’ll use the python third-party API package to access Jenkins rest API.

I have already shared a tutorial on How To Access Python API Using PHP. I’ll demonstrate here how to access Jenkins API using python.

There are two Python packages you can use for this task:

Both Python packages will interact with Jenkins and have access to the JenkinsAPI. To access the rest API, I will use the Jenkins package.

What is Jenkins

Jenkins is a well-known self-contained, open-source build tool. Jenkins can be used to build, test, and deploy software to a server. Jenkins API information can be found at the bottom of the Jenkins server. Jenkins comes with hundreds of plugins to help you build, deploy, and automate any project. More information is available here.

Jenkins API Python

We’ll create a test.py file that contains all of the code for accessing job data.

Install Python Package

Let’s install python-jenkins into your Python application. You can use pip for this:

Create Jenkins Client

Let’s create a Jenkins object using username and password, that ll use further to access the rest API:

The above client is returned is usually a Python dictionary.

Where is :

  • http://jenkins-hostname : This is the Hostname of the Jenkins server.
  • port: This is the port number of the Jenkins server.
  • user: The Jenkins server API username.
  • password: This is the Jenkins server API password.

How To Get All Jenkins Jobs

You can use the python package’s inbuilt method to access all configured Jenkins jobs. The following code is used to retrieve all of the jobs that are configured on your CI system:

The code above will access all configured Jenkins jobs and loop through all of them, printing out their job names.

Conclusions:

You can also use the Python Jenkins package to start a building job, create a new job, or delete an existing job from Jenkins. More information is available in the documentation.