Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

circleci-api

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

circleci-api

A Node and Browser client for the CircleCI API, written in TypeScript.

  • 4.1.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

CircleCi API Client

A Node and Browser client for the CircleCI API, written in TypeScript.

CircleCI branch CircleCI (all branches) Coverage Status

npm version Downloads npm bundle size License

Renovate enabled

API wrapper for CircleCi API, usable in node and the browser. If used in a TypeScript project, you will get types, and auto-complete for all of the api responses. You will no longer need to tab back and fourth to the API documentation.

I recommend using this library if you are writing a tool or website in TypeScript. I have created definitions for each of the CircleCI endpoints. There may still be some errors, but I am open to contributions on making them better.

If there are any features you would like, please feel free to open up an issue.

Notes

Types

I did my best to correctly add types for all of the supported endpoints. However if you notice an incorrect payload type, or some missing properties, please open up an issue, or submit a pull request.

CircleCI API v2

CircleCI is going to be rolling out a new version of their api (see here). Currently this library does not support v2, but I will update it in the future, see #228 for updates.

Migrating from v3 to v4

There have been some breaking changes, please see MIGRATING.md for more info.

Installation

Add using yarn or npm

yarn add circleci-api

## or

npm install circleci-api

Usage

Get your API token from CircleCi

There are two ways to use this library.

1. CircleCi class

Get instance of the factory.

// Module
import { CircleCI, GitType, CircleCIOptions } from "circleci-api";

// Configure the factory with some defaults
const options: CircleCIOptions = {
  // Required for all requests
  token: "", // Set your CircleCi API token

  // Optional
  // Anything set here can be overriden when making the request

  // Git information is required for project/build/etc endpoints
  vcs: {
    type: GitType.GITHUB, // default: github
    owner: "worldturtlemedia",
    repo: "circleci-api"
  }

  // Optional query params for requests
  options: {
    branch: "master", // default: master
    filter: "completed"
  }
}

// Create the api object
const api = new CircleCI(options)

// Use the api

/**
 * Grab the latest artifacts from a successful build on a certain branch
 * @param [branch="master"] - Artifacts for certain branch
 * @return List of successfully built artifact objects
 */
export async function getLatestArtifacts(branch: string = "master"): Promise<Artifact[]> {
  try {
    // Will use the repo defined in the options above
    const result: Aritfact[] = await api.latestArtifacts({ branch, filter: "successful" })
    console.log(`Found ${result.length} artifacts`)
    return result
  } catch (error) {
    console.log("No build artifacts found")
  }

  return []
}

getLatestArtifacts("develop")
  .then(artifacts => {
    artifacts
      .forEach(({ path, url }: Artifact) => console.log(`${path} -> ${url}`))
  })

// Or override settings set above
api
  .latestArtifacts(
    { branch: "develop" },
    {
      vcs: { repo: "awesome-repo" },
      options: { filter: "successful" }
    }
  )
  .then((artifacts: Artifact[]) => console.log(`Found ${artifacts.length} artifacts`))
  .catch(error => console.error(error))

2. Manually

The individual functions can also be imported if you only need one or two. To help with tree-shaking.

import { getMe, getLatestArtifacts } from "circleci-api";

const CIRCLECI_TOKEN: string = "circle-ci-token";

getMe(CIRCLECI_TOKEN)
  .then(me => console.log("token is valid"))
  .catch(error => console.error("invalid token"));

getLatestArtifacts(CIRCLECI_TOKEN, {
  vcs: {
    owner: "billyBob",
    repo: "super-cool-app"
  },
  options: {
    filter: "failed",
    branch: "feature-smith2"
  }
})
  .then(result => console.log(`Found ${result.length} artifacts`))
  .catch(error => console.error(error));

Self-hosted CircleCI

To override the default API base url https://circleci.com/api/v1.1, you can pass a circleHost to the CircleCI constructor, or to the standalone functions.

// Using the CircleCi class
new CircleCI({
  token: "my-token",
  vcs: { owner: "worldturtlemedia", repo = "circleci-api" },
  circleHost: "https://my-selfhosted-circleci.com/"
}).getLatestArtifacts()

// Using the standalone functions
getLatestArtifacts("my-token", {
  ...
  circleHost: "https://my-selfhosted-circleci.com/"
})

While all of the standalone functions support a custom circleHost property. Using the CircleCI class you must specify it in the constructor.

Demo

There are three similar demos are available in the demo folder.

Note: I recommend VSCode for viewing and editing the examples. It will give you great intellisense about the library.

For the TypeScript & JavaScript follow the steps below:

# Step 1 - Change into demo folder and install dependencies
cd demo
yarn

# Javascript example:
node ./index.js

# Typescript example:
npx ts-node --project ../tsconfig.base.json ./index.ts

# To view Browser example, first build project
yarn build

# Then open `index.html` in your browser

Supported endpoints

Using factory:

Optional properties:

export interface CircleRequest {
  token?: string;
  vcs?: GitInfo;
  options?: Options;
}

Any function with an optional paramater of CircleRequest can override any of the values you assigned when using the circleci() factory.

NameRequiredOptionalReturns
me()nonenoneMe
projects()noneCircleRequestProject[]
followProject(){ vcs: GitInfo }noneFollowNewResult
recentBuilds()none{ limit: number, offset: number }BuildSummary[]
builds()none{ limit: number, offset: number }BuildSummary[]
buildsFor()branch: string = "master"{ limit: number, offset: number }BuildSummary[]
build()buildNumber: numberCircleRequestBuildWithSteps
artifacts()buildNumber: numberCircleRequestArtifact[]
latestArtifacts()noneCircleRequestArtifact[]
retry()buildNumber: numberCircleRequestBuildSummary
cancel()buildNumber: numberCircleRequestBuildSummary
triggerBuild()noneCircleRequestBuild
triggerBuildFor()branch: string = "master"CircleRequestBuild
clearCache()noneCircleRequestClearCacheResponse
listEnvVars()noneCircleRequestEnvVariable[]
addEnvVar()variable: EnvVariableCircleRequestEnvVariable
getEnvVar()envName: stringCircleRequestEnvVariable
deleteEnvVar()envName: stringCircleRequestMessageResponse
checkoutKeys()noneCircleRequestCheckoutKeyResponse
createCheckoutKey()type: CheckoutTypeCircleRequestCheckoutKeyResponse
checkoutKey()fingerprint: stringCircleRequestCheckoutKeyResponse
deleteCheckoutKey()fingerprint: stringCircleRequestDeleteCheckoutKeyResponse
getTestMetadata()buildNumber: numberCircleRequestTestMetadataResponse
addSSHKey()key: SSHKeyCircleRequestnone
addHerokuKey()key: HerokuKeyCircleRequestnone

Missing endpoint

The last remaining endpoint probably won't be added unless there is demand.

NameLink
Add user to buildref

Contributing

See CONTRIBUTING.

License

MIT License

Copyright (c) 2019 WorldTurtleMedia

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Keywords

FAQs

Package last updated on 03 May 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc