Automation: Trigger GitHub workflow from the backend

Trigger GitHub workflow from the backend
Oct 9 2022 · 4 min read

As a developer, we often come around to the requirement of automation at every place. I have experienced the same. I have to trigger the GitHub workflow from our admin panel.

Thanks to GitHub REST APIs. Using them, I was able to do that automation.

We will see the automation flow step-by-step.

Let’s dig deep…


Sponsored


GitHub provides Rest API endpoints to create integration, obtain data, or automate workflow. You can explore more about them in their API reference guidance.

As we have to automate workflow runs, we will use workflow runs API from Actions reference.

It’s always a good practice to break down the task into smaller sub-tasks to make them easy to understand and implement.

Follow the below steps…

  • Generate Personal Access Token(PAT) from GitHub
  • Get GitHub workflows of your repository
  • Find and run the workflow

Generate Personal Access Token(PAT) from GitHub

For using GitHub APIs we have to do authentication first. There are two types of authentication processes it provides.

  1. Using client ID and secret: If authentication is from frontend
  2. Using personal access token(PAT): If authentication is from the backend

As we are working with the backend, we will go with Personal Access Token(PAT) for authentication.

From below path, can generate PAT :

  • GitHub -> settings -> Developer settings -> Personal access tokens -> generate new token
  • As we want to use PAT for repository authentication, create it with all admin and repo access.

Get GitHub workflows of your repository

For running workflow, we want the workflow id of GitHub. We are using List workflow runs for a repository API for it.

You can add filters like the creator of workflow, branches, or status using query parameters in the endpoints and get preferable workflows.

Let’s use this API in the Node.js backend.

// prepare headers
const config = {
    headers: {
      Accept: "application/vnd.github+json",
      Authorization: "Bearer " +  PERSONAL_ACCESS_TOKEN(PAT)
    }
}; 

 /** 
     add filter using query params like below ,
     https://api.github.com/repos/OWNER/REPO/actions/runs?branch=master
 */
 axios.get('https://api.github.com/repos/OWNER/REPO/actions/runs', config)
    .then(res => {
      // res contains list of workflows
 })
 .catch(err => {
     console.error(err.message)
 });
  • Preparing config for API: config contains headers information we will require to access API.
  • Accept: it’s recommended to add this header to access properly formatted GitHub JSON data.
  • Authorization: Pass the Personal access token, that we have generated in step 1 as Bearer.
{      
   Accept: "application/vnd.github+json",
   Authorization: "Bearer " + PERSONAL_ACCESS_TOKEN(PAT)    
}
  • Request list of workflows: Using Axios or any HTTP package or through CLI, you can request the GitHub API endpoint and get workflow run data.
  • Don’t forget to pass the header in a request. otherwise, it will throw a forbidden error.
  • If the request will successful, you will get an array of workflow runs.
"workflow_runs" : [
     {
        "id" : 12345678,
        "workflow_id" : 67854321,
        "name" : "WorkflowName",
        ...
     },
     ...
]
  • From this, get the workflow id and trigger the workflow. I have added a filter on the array by workflow name like below,
const workflows = res.data["workflow_runs"]
                  .filter(function (workflow){
                            return workflow.name == "WorkflowName";
                  })

It will return workflows having the name WorkflowName. I have triggered the first workflow from workflows.

The final code will be,

 axios.get('https://api.github.com/repos/OWNER/REPO/actions/runs', config)
    .then(res => {
         // res contains list of workflows
         const workflows = res.data["workflow_runs"].filter(function (workflow) {
              return workflow.name == "WorkflowName";
         })
         
        // getting id of first workflow
        const wID = workflows[0].id
 })
 .catch(err => {
     console.error(err.message)
 });

Find and run the workflow

You have the workflow’s Id now, It’s time to trigger the workflow from the backend.

We will use Re-run a workflow. It’s a POST request and will trigger workflow if the request will be successful.

Again we need to pass the same header that we have prepared in step 2 here.

axios.post(
      "https://api.github.com/repos/OWENER/REPO/actions/runs/" + wId + "/rerun", 
      null, 
      { headers: config.headers}
);

After this request, check your workflow in GitHub actions. It’s running 👼.

The final code will be like this,

// prepare headers
const config = {
    headers: {
      Accept: "application/vnd.github+json",
      Authorization: "Bearer " +  PERSONAL_ACCESS_TOKEN(PAT)
    }
}; 

 axios.get('https://api.github.com/repos/OWNER/REPO/actions/runs', config)
    .then(res => {
         // res contains list of workflows
         const workflows = res.data["workflow_runs"].filter(function (workflow) {
              return workflow.name == "WorkflowName";
         })
         
        // getting id of first workflow
        const wID = workflows[0].id
    
        axios.post(
              "https://api.github.com/repos/OWENER/REPO/actions/runs/" + wId + "/rerun", 
              null,   // request body will be null
              { headers: config.headers}  //pass headers from config
        );
 })
 .catch(err => {
     console.error(err.message)
 });

Conclusion

This is a sample example of GitHub automation. GitHub provides various APIs from which we can access its resources and by automating things, can save time.

That’s it for now. Thank you for reading.


Video


Related articles


sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.


sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.


Talk to an expert
get intouch
Our team is happy to answer your questions. Fill out the form and we’ll get back to you as soon as possible
footer
Subscribe Here!
Follow us on
2024 Canopas Software LLP. All rights reserved.