api4jenkins: Jenkins Python Client

raw JSON →
2.1.0 verified Thu Apr 16 auth: no python

api4jenkins is a Python client library for programmatic interaction with Jenkins instances, offering both synchronous and asynchronous APIs. It provides an object-oriented interface for managing Jenkins items like Jobs, Builds, Nodes, and Credentials. Currently at version 2.1.0, it maintains an active release cadence with regular updates including new features, bug fixes, and documentation improvements.

pip install api4jenkins
error TypeError: object AsyncJenkins can't be awaited
cause Attempting to call an asynchronous method (e.g., `client.version`, `client.get_job`) on `AsyncJenkins` without using `await`.
fix
Prepend await to the async method call. E.g., await client.version.
error Error: 404 Not Found (or similar HTTP 4xx error) when accessing OrganizationFolder scan logs
cause A bug in `api4jenkins` versions prior to 2.0.4 caused `OrganizationFolder.get_scan_log` to return a 404.
fix
Update api4jenkins to version 2.0.4 or higher (pip install --upgrade api4jenkins).
error Jenkins job parameters are not being applied or recognized.
cause Incorrectly formatting or passing parameters to the `build_job` method. Parameters must often be a dictionary.
fix
Ensure parameters are passed as a dictionary. For example: item = client.build_job('myjob', params={'MY_PARAM': 'value'}).
error JenkinsAPIException: 401 Client Error: Unauthorized for url: ...
cause Incorrect Jenkins URL, username, or API token/password provided, or insufficient permissions for the user.
fix
Double-check your JENKINS_URL, JENKINS_USER, and JENKINS_TOKEN (or password) environment variables. Ensure the user has the necessary permissions in Jenkins.
error ModuleNotFoundError: No module named 'api4jenkins'
cause The `api4jenkins` library is not installed in the current Python environment.
fix
Install the library using pip: pip install api4jenkins.
breaking Python 3.6 support was dropped in `api4jenkins` v1.14. Users on Python 3.6 will encounter errors and must upgrade to Python 3.8 or newer.
fix Upgrade your Python environment to 3.8 or higher.
breaking Version 2.0.0 introduced significant changes, including the addition of `AsyncClient` and a new exception base class `JenkinsAPIException`. Existing synchronous code should generally continue to work, but if you were catching specific exceptions or intended to use asynchronous features, you will need to adapt.
fix Review your exception handling and consider migrating to `AsyncJenkins` for non-blocking operations if needed. `from api4jenkins.exceptions import JenkinsAPIException` for custom handling.
breaking Certificate validation behavior changed in v2.0.2 due to migration from `requests` to `httpx`. Users with custom SSL/TLS certificate setups might need to adjust their `httpx.Client` `kwargs` passed to the `Jenkins` constructor (e.g., `verify=False` or `cert`).
fix Pass `verify=False` to the `Jenkins` client constructor to disable SSL verification if encountering certificate issues, or provide appropriate `cert` arguments. E.g., `client = Jenkins(url, auth=(user, token), verify=False)`.
gotcha The `OrganizationFolder.get_scan_log` method previously returned a '404 Not found' error in versions prior to 2.0.4.
fix Upgrade to `api4jenkins` v2.0.4 or newer to resolve the `OrganizationFolder.get_scan_log` issue.
gotcha When passing parameters to Jenkins jobs, ensure they are correctly formatted as a dictionary, which then needs to be handled as a string or correctly passed depending on the API call. Incorrect formatting can lead to parameters not being applied.
fix Always verify how job parameters are expected by Jenkins and passed via `api4jenkins`. Often, a dictionary is required (e.g., `client.build_job('myjob', params={'PARAM1': 'value'})`).

Initializes a synchronous Jenkins client, connects to a Jenkins instance using environment variables for authentication, and prints the Jenkins version and a list of available jobs. Remember to set JENKINS_URL, JENKINS_USER, and JENKINS_TOKEN (or JENKINS_PASS) environment variables.

import os
from api4jenkins import Jenkins

JENKINS_URL = os.environ.get('JENKINS_URL', 'http://localhost:8080')
JENKINS_USER = os.environ.get('JENKINS_USER', 'admin')
JENKINS_TOKEN = os.environ.get('JENKINS_TOKEN', 'your_api_token') # or JENKINS_PASS

try:
    client = Jenkins(JENKINS_URL, auth=(JENKINS_USER, JENKINS_TOKEN))
    jenkins_version = client.version
    print(f"Successfully connected to Jenkins v{jenkins_version}")
    # Example: List all jobs
    print("\nAvailable Jobs:")
    for job in client.iter():
        print(f"- {job.name} ({job.url})")
except Exception as e:
    print(f"Failed to connect to Jenkins or retrieve info: {e}")