Skip to content
circleci-toolsPublic

About

🌀 CircleCI API Client for Kotlin

Topics

Resources

Code of conduct

Contributing

Stars

4 stars

Watchers

1 watching

Forks

Repository files navigation

CircleCI

CI codecov Libraries.io dependency status for GitHub repo GitHub

This is CircleCI API Client for Kotlin.

The master branch returns RxJava 3 observables (io.reactivex.rxjava3.core.Observable). Version 2.1.2, used below, returns RxJava 2 observables. When upgrading to a version that uses RxJava 3, update your imports and reactive integrations to RxJava 3.

Features

  • Trigger pipelines, inspect workflows and jobs, and retrieve job artifacts and test results with the CircleCI API v2 client.
  • Manage context environment variables and restrictions, and query workflow and job metrics through Insights.
  • On master, trigger and list CircleCI Cloud API v3 runs and poll for completion.
  • On master, connect to an HTTPS CircleCI Server instance with the API v2 client.
  • On master, call any client method from Kotlin coroutines with await() extensions, alongside the RxJava3 API.

Quick start

Use version 2.1.2 in the dependency declaration below. Set CIRCLECI_TOKEN to your CircleCI Cloud personal API token, then run the following in your Kotlin application to print the authenticated user's login.

import com.github.unhappychoice.circleci.CircleCIAPIClient

fun main() {
    val token = requireNotNull(System.getenv("CIRCLECI_TOKEN")) {
        "Set CIRCLECI_TOKEN to your CircleCI personal API token."
    }
    val user = CircleCIAPIClient(token).clientV2().getMe().blockingFirst()
    println(user.login)
}

With the public CircleCIAPIClient(token) constructor, clientV2() sends requests to CircleCI Cloud (https://circleci.com/api/v2/). The CircleCIAPIClient.async(token) factory on master uses the same URL. For example, getMe() sends the supplied token to https://circleci.com/api/v2/me.

Configuration

Pass the personal API token to CircleCIAPIClient(token) for CircleCI Cloud. On master, pass the instance's token and HTTPS origin to server(token, instanceUrl) for CircleCI Server. Use async or serverAsync on master to make asynchronous HTTP calls.

The examples read CIRCLECI_TOKEN and, for Server, CIRCLECI_SERVER_URL from the application's environment. The library takes these values as arguments, so the application can supply them from its own configuration.

Asynchronous calls on master

When using a build from the master branch, use the same token from the quick start:

val client = CircleCIAPIClient.async(token).clientV2()
client.getMe().subscribe(
    { user -> println(user.login) },
    { error -> error.printStackTrace() },
)

With CircleCIAPIClient.async(token), subscribe() returns without waiting for the HTTP response. Keep the application running until the success or error callback executes. Use CircleCIAPIClient(token) for synchronous subscriptions.

CircleCI Cloud API v3

Use a personal API token and a pipeline definition ID to trigger a run and wait for it to finish before starting a dependent step. Use getRun(id) for a single status snapshot. For projects using the GitHub App integration, you can omit projectId as shown below.

import com.github.unhappychoice.circleci.CircleCIAPIClient
import com.github.unhappychoice.circleci.v3.request.TriggerRunRequest
import com.github.unhappychoice.circleci.waitForRun
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds

val v3 = CircleCIAPIClient("your-api-token").clientV3()
val created = v3.triggerRun(TriggerRunRequest(pipelineId = "your-pipeline-definition-id")).blockingSingle()
val run = v3.waitForRun(created.data.id, pollInterval = 5.seconds, timeout = 20.minutes)
    .blockingGet().data
check(run.attributes.currentOutcome == "succeeded") {
    "Run ${run.id} ended with outcome ${run.attributes.currentOutcome}"
}

For GitHub OAuth and Bitbucket OAuth projects, replace the val created line with the call below. Pass the UUID of the CircleCI project that owns the pipeline definition. triggerRun sends it as filter[project_id], which CircleCI requires to resolve the definition. Omitting it returns HTTP 404. See the CircleCI migration guide.

val created = v3.triggerRun(
    TriggerRunRequest(pipelineId = "your-pipeline-definition-id"),
    projectId = "your-project-uuid",
).blockingSingle()

waitForRun returns a Single that schedules its first poll on subscription, then waits for the configured interval after each response. It returns the first response whose phase is ended, even if an earlier response had a currentOutcome. A later rerun can change the observed outcome.

Synchronous clients share a limit of eight concurrent waitForRun requests. Polls queue when all eight slots are busy. The timeout covers the full wait, including time spent queued, awaiting approval, or fetching status. It emits a TimeoutException when the deadline expires. Request errors, including HTTP 429, terminate the wait immediately. Dispose the subscription to stop polling. The CircleCI run itself continues independently.

List recent runs for a project using its UUID, or call listMyRuns() for runs triggered by the authenticated user across projects. Both methods accept an optional pageSize (up to 20) and an opaque cursor. Pass page.next back to the same method to fetch the next page. A null page.next marks the last page.

val projectId = "your-project-uuid"
val firstPage = v3.listProjectRuns(projectId, pageSize = 10).blockingSingle()
firstPage.data.forEach { summary ->
    println("${summary.id}: ${summary.attributes.phase} (${summary.branch})")
}

firstPage.data.firstOrNull()?.let { selected ->
    val details = v3.getRun(selected.id).blockingSingle().data
    println("${details.id}: ${details.attributes.currentOutcome}")
}

val nextPage = firstPage.page.next?.let { cursor ->
    v3.listProjectRuns(projectId, pageSize = 10, cursor = cursor).blockingSingle()
}

Download a V2 job artifact

List the job's artifacts, select the path you want, and copy its stream to a local file. The artifact can be on any page, so follow page.nextPageToken as pageToken until it is found or no pages remain.

import com.github.unhappychoice.circleci.CircleCIAPIClient
import java.io.File

val api = CircleCIAPIClient(token)
var page = api.clientV2().getJobArtifacts("gh/my-org/my-project", "123", pageToken = null).blockingSingle()
var artifact = page.items.find { it.path == "reports/junit.xml" }
while (artifact == null && page.nextPageToken != null) {
    page = api.clientV2().getJobArtifacts("gh/my-org/my-project", "123", page.nextPageToken).blockingSingle()
    artifact = page.items.find { it.path == "reports/junit.xml" }
}

if (artifact == null) {
    error("reports/junit.xml not found in any artifact page")
}

api.downloadArtifact(artifact) { input ->
    File("junit.xml").outputStream().use { output -> input.copyTo(output) }
}.blockingGet()

The download starts on subscription and runs the callback on a scheduler shared by all downloadArtifact calls, limited to eight concurrent downloads. Downloads beyond the limit queue until a slot becomes available. A download subscribed to directly on a download worker runs inline and uses an additional slot. If all eight slots are in use, the nested download fails without waiting for a slot. Read or copy the stream within the callback. The client closes the response when the callback exits, including on failure. The RxJava I/O scheduler delivers the result or error, including a RejectedExecutionException for a rejected nested download. Disposing a queued download removes it from the queue without starting it. Disposing an active download cancels the HTTP call and interrupts pending network reads.

Downloads require HTTPS. For CircleCI Cloud, the client sends Circle-Token to circleci.com, dl.circleci.com, and subdomains of circle-artifacts.com on port 443. It keeps the token on same-origin redirects and drops it when the origin changes. This supports storage redirects such as the S3 redirects described by CircleCI.

Coroutines on master

Every client method still returns an RxJava 3 type, but await() extension functions on Observable<T> and Completable let suspend code call the client without hand-written bridging. await() on an Observable<T> matches blockingSingle()'s semantics (the client's methods emit exactly one item on success); await() on a Completable matches blockingAwait(). Both extensions start subscriptions on a shared pool of eight workers. With the default synchronous client, each blocking HTTP call occupies a worker until it returns. Additional subscriptions queue until a worker is free, and the calling coroutine's dispatcher remains available. With an asynchronous client, the subscription enqueues the call and OkHttp handles it asynchronously. Cancelling the calling coroutine disposes the underlying subscription, cancelling the in-flight HTTP call.

import com.github.unhappychoice.circleci.CircleCIAPIClient
import com.github.unhappychoice.circleci.await

suspend fun printLogin(token: String) {
    val user = CircleCIAPIClient.async(token).clientV2().getMe().await()
    println(user.login)
}

waitForRun already returns a Single, so kotlinx-coroutines-rx3's own Single<T>.await() extension covers it directly; no extra wrapper is needed for that one case.

Legacy SSH key creation and deletion

The V1 and V1.1 addSshKey and deleteSshKey methods return an RxJava 3 Completable. Use await() in coroutines, blockingAwait(), or a completion callback to handle success. The methods complete when CircleCI returns a successful HTTP response, including an empty response. HTTP failures still reach the error handler. Update explicit return types and custom client overrides to Completable from Observable<SSHKey> for addSshKey and Observable<Unit> for deleteSshKey.

V2 context environment variables

addEnvironmentVariableToContext returns Observable<EnvironmentVariable>. Use the variable, contextId, createdAt, and updatedAt properties in place of map lookups. Both timestamps are OffsetDateTime values. Update explicit Observable<Any> declarations and custom client overrides to Observable<EnvironmentVariable>. If a caller still requires Observable<Any>, use .map<Any> { it } at that boundary.

V2 context restrictions

getContextRestrictions returns a ContextProjectRestrictionsList whose items are now List<ContextRestriction>. Replace map casts and key lookups with the id, contextId, restrictionType, restrictionValue, and nullable name properties. For project restrictions, read the project ID from restrictionValue. Use nextPageToken to retrieve the next page.

CircleCI Server on master

Set CIRCLECI_SERVER_URL to the instance's HTTPS origin (for example, https://ci.example.com:8443) and CIRCLECI_TOKEN to a personal API token issued by that instance.

import com.github.unhappychoice.circleci.CircleCIAPIClient

val instanceUrl = requireNotNull(System.getenv("CIRCLECI_SERVER_URL"))
val token = requireNotNull(System.getenv("CIRCLECI_TOKEN"))
val client = CircleCIAPIClient.server(token, instanceUrl)
val jobs = client.getWorkflowJobs("your-workflow-id").blockingSingle()
println(jobs.items)

Use CircleCIAPIClient.serverAsync(token, instanceUrl) for asynchronous subscriptions. Both factories return a CircleCIServerClient, a V2 client that also exposes downloadArtifact bound to the same instance token and origin, and send requests under /api/v2/. The instance URL accepts an optional port and trailing slash. Reverse-proxy path prefixes are unsupported. The client follows redirects only within the same HTTPS origin, and downloadArtifact sends the instance token only to that origin, dropping it on redirects elsewhere.

val page = client.getJobArtifacts("gh/my-org/my-project", "123").blockingSingle()
val artifact = page.items.first { it.path == "reports/junit.xml" }
client.downloadArtifact(artifact) { input ->
    File("junit.xml").outputStream().use { output -> input.copyTo(output) }
}.blockingGet()

The CircleCI Server automation guide documents listing workflow jobs and getting job details. This library tests those two endpoints against a local HTTPS mock. Compatibility with live CircleCI Server versions and other V2 endpoints is unverified.

Installation

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}
dependencies {
    implementation 'com.github.circleci-tools:circleci:2.1.2'
}

Documentation

See Getting Started for a deeper walkthrough from installation through triggering a pipeline and reading back its workflows, Usage and API Reference for an index of every client's methods grouped by resource, and Architecture for how a request flows through the library.

Troubleshooting

See Troubleshooting for token errors, CircleCI Server URLs, and RxJava version differences.

Changelog

See CHANGELOG.md for notable changes per release.

License

MIT License

About

🌀 CircleCI API Client for Kotlin

Topics

Resources

Code of conduct

Contributing

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages