SDKs overview
Travis CI offers a range of SDKs and libraries that enable developers to interact with its continuous integration platform programmatically. These tools extend the functionality beyond the web interface, allowing for automation of common tasks such as triggering builds, managing repositories, accessing build logs, and administering user permissions. The availability of SDKs in multiple languages facilitates integration into diverse development environments and custom CI/CD pipelines.
The primary method for configuring Travis CI for a project remains the .travis.yml file, which defines the build environment, scripts, and deployment steps as described in Travis CI's build customization guide. SDKs complement this by providing an interface for managing the CI process itself, rather than just defining the build logic. This distinction allows for greater control over the CI workflow from external applications or scripts.
While Travis CI maintains official SDKs for core languages, the open-source nature of many projects leveraging Travis CI has also fostered a collection of community-contributed libraries. These community efforts often provide additional utilities or language bindings for less common use cases, expanding the ecosystem of tools available to developers. Access to the Travis CI API is typically secured using API tokens, which are generated and managed within the Travis CI platform according to the API token management documentation.
Official SDKs by language
Travis CI provides official SDKs designed to offer robust and maintained interfaces for interacting with its API. These libraries streamline common operations and ensure compatibility with the platform's features. The following table outlines the key official SDKs, their primary language, installation methods, and general maturity levels.
| Language | Package Name | Installation Command | Maturity |
|---|---|---|---|
| Python | travispy |
pip install travispy |
Stable |
| Ruby | travis |
gem install travis |
Stable |
| Go | go-travis |
go get github.com/shuheiktgw/go-travis |
Stable |
| JavaScript (Node.js) | travis-ci |
npm install travis-ci |
Stable |
Each SDK is designed to abstract the underlying HTTP requests to the Travis CI API, providing idiomatic methods for common tasks. Developers can refer to the specific documentation for each SDK for detailed usage instructions and available functionalities.
Installation
Installing Travis CI SDKs typically follows the standard package management practices for each respective programming language. Below are detailed instructions for installing the official SDKs.
Python: travispy
The travispy library for Python allows interaction with the Travis CI API. It can be installed using pip:
pip install travispy
After installation, you can import and use the library in your Python scripts:
from travispy import TravisPy
# Authenticate with your Travis CI token
travis = TravisPy('YOUR_TRAVIS_TOKEN')
# Example: Get your current user
user = travis.user()
print(f"Logged in as: {user.login}")
Ruby: travis gem
The travis gem provides a command-line interface and a Ruby library for Travis CI. Install it using RubyGems:
gem install travis
You can then use it in your Ruby applications or via the command line:
require 'travis'
# Authenticate with your Travis CI token
Travis.access_token = 'YOUR_TRAVIS_TOKEN'
# Example: Get a repository
repo = Travis::Repository.find('owner/repo-name')
puts "Repository slug: #{repo.slug}"
Go: go-travis
For Go developers, the go-travis library provides a client for the Travis CI API. Install it using the go get command:
go get github.com/shuheiktgw/go-travis
Here's a basic example of how to use it:
package main
import (
"context"
"fmt"
"github.com/shuheiktgw/go-travis"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
// Authenticate with your Travis CI token
tc := oauth2.NewClient(ctx, oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: "YOUR_TRAVIS_TOKEN"},
))
client := travis.NewClient(tc, travis.ApiDotComURL)
// Example: Get the current user
user, _, err := client.Users.Get(ctx)
if err != nil {
fmt.Printf("Error getting user: %v\n", err)
return
}
fmt.Printf("Logged in as: %s\n", user.Name)
}
JavaScript (Node.js): travis-ci
The travis-ci npm package offers a JavaScript client for the Travis CI API, suitable for Node.js environments. Install it via npm:
npm install travis-ci
Here’s an example of its usage:
const Travis = require('travis-ci');
const travis = new Travis({
version: '2.0.0' // Specify API version
});
// Authenticate with your Travis CI token
travis.authenticate({
github_token: 'YOUR_GITHUB_TOKEN' // Or use travis_token
}, function (err) {
if (err) {
console.error('Authentication error:', err);
return;
}
console.log('Authenticated successfully.');
// Example: Get repos
travis.repos.get(function (err, res) {
if (err) {
console.error('Error getting repositories:', err);
return;
}
console.log('Repositories:', res.repos.map(repo => repo.slug));
});
});
Quickstart example
This quickstart demonstrates how to use the Python travispy library to list active builds for a specific repository. This requires a Travis CI API token with sufficient permissions.
Prerequisites:
- Python 3 installed.
travispyinstalled (pip install travispy).- A Travis CI API token. You can generate one from your Travis CI profile settings.
- A repository slug (e.g.,
owner/repo-name).
Python script (list_builds.py):
import os
from travispy import TravisPy
# Set your Travis CI API token as an environment variable
# e.g., export TRAVIS_TOKEN="YOUR_SECRET_TOKEN"
TRAVIS_TOKEN = os.environ.get('TRAVIS_TOKEN')
if not TRAVIS_TOKEN:
print("Error: TRAVIS_TOKEN environment variable not set.")
exit(1)
REPO_SLUG = "travis-ci/travis-web" # Replace with your repository slug
def list_repo_builds(token, repo_slug):
"""Lists recent builds for a given Travis CI repository slug."""
try:
travis = TravisPy(token)
repo = travis.repo(repo_slug)
if not repo:
print(f"Error: Repository '{repo_slug}' not found or unauthorized.")
return
print(f"--- Recent Builds for {repo.slug} ---")
builds = travis.builds(slug=repo.slug, limit=5) # Get last 5 builds
if not builds:
print("No builds found for this repository.")
return
for build in builds:
commit = travis.commit(build.commit_id)
print(f" Build #{build.number}: {build.state} (Branch: {commit.branch}, Message: {commit.message[:50]}...)")
print(f" Duration: {build.duration}s, Started: {build.started_at}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
list_repo_builds(TRAVIS_TOKEN, REPO_SLUG)
How to run:
- Save the code above as
list_builds.py. - Replace
"travis-ci/travis-web"with the actual slug of the repository you wish to query. - Set your Travis CI API token as an environment variable named
TRAVIS_TOKEN:
export TRAVIS_TOKEN="YOUR_ACTUAL_TRAVIS_TOKEN"(on Linux/macOS)
$env:TRAVIS_TOKEN="YOUR_ACTUAL_TRAVIS_TOKEN"(on PowerShell)
set TRAVIS_TOKEN="YOUR_ACTUAL_TRAVIS_TOKEN"(on Windows Command Prompt) - Run the script from your terminal:
python list_builds.py
This script will authenticate with your Travis CI token, find the specified repository, and then print the details of its five most recent builds. This demonstrates basic API interaction for fetching resource information.
Community libraries
Beyond the officially supported SDKs, the Travis CI ecosystem benefits from several community-driven libraries and tools. These often extend functionality, provide bindings for additional languages, or offer specialized utilities not covered by official offerings. While not officially maintained by Travis CI, they can be valuable resources for specific use cases.
- Various language clients: Developers have created clients for languages like PHP, Rust, and others, often available through their respective package managers (e.g., Composer for PHP). Searching package repositories for
travis-ciortraviscan reveal these options. - CLI wrappers and extensions: Some community tools provide enhanced command-line interfaces or integrate Travis CI functionality into other developer tools, such as IDE extensions or shell scripts.
- Webhooks and integrations: Libraries exist to help process Travis CI webhooks or integrate build status into chat platforms, project management tools, or custom dashboards. For example, webhook security is a critical aspect for many CI/CD systems as highlighted in Cloudflare's guide on processing webhooks.
When considering community libraries, it is advisable to review their documentation, community activity, and maintenance status to ensure they meet project requirements for stability and security. GitHub repositories are often the best place to find the latest versions and contribute to these projects.