Using the CircleCI Public API with JavaScript

The CircleCI Public API provides a simple way to interact with the CircleCI platform and automate your build, test, and deployment processes. In this blog post, we will cover how to use the API with JavaScript and provide some example code snippets to help you get started.

Authentication

Before we dive into using the API, let's start with authentication. To make requests to the CircleCI API, you will need to authenticate with a personal API token. You can find your token in the CircleCI user settings. Once you have your token, you will need to pass it in as an authorization header in all API requests.

const axios = require('axios');

const token = process.env.CIRCLECI_TOKEN; // Replace with your personal API token

const config = {
  headers: {'Authorization': `Bearer ${token}`}
};

// Example API request
axios.get('https://circleci.com/api/v1.1/projects', config)
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

Example API Requests

Now that we have covered authentication, let's take a look at some example API requests you can make using the CircleCI Public API.

List All Projects

The following API request lists all projects under your CircleCI account.

axios.get('https://circleci.com/api/v1.1/projects', config)
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

Trigger a Build

The following API request triggers a new build for a specific project and branch.

const requestBody = {
  "build_parameters": {
    "CIRCLE_JOB": "build"
  }
};

axios.post('https://circleci.com/api/v1.1/project/:username/:project/tree/:branch', requestBody, config)
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

Retrieve Build Artifacts

The following API request retrieves the artifacts for a specific build.

axios.get('https://circleci.com/api/v1.1/project/:username/:project/:build_num/artifacts', config)
  .then(response => console.log(response.data))
  .catch(error => console.log(error));

Conclusion

In this blog post, we covered how to authenticate and make API requests using the CircleCI Public API with JavaScript. We provided some example code snippets to help you get started, but there are many more API endpoints available for you to explore. With the power of the API, you can automate your build, test, and deployment processes, and seamlessly integrate CircleCI into your workflow. Happy coding!

Related APIs