Build a Github Actions API support for Strapi using Lambda function
techMajority of websites are REST/HTTP API driven on runtime with caching mechanisms in place. Right now, this blog site pulls data only during build time through GitHub due to its SSG setup and to make sure it gets the updated data, we need Strapi to connect with GitHub.
Strapi's webhook configuration only lets us pass a URL, some headers where we can include our authentication token, query strings and events to choose from, such as publish, unpublish and other updates through a POST request. On the other side, Github's REST API requires more data to trigger the workflow correctly. So, we'll be needing a friendly middleman to connect the two and this is where we will be using AWS Lambda. We will be creating a simple request using AWS Lambda to trigger a dispatch event in our Github workflow.
Why Lambda is the one?
AWS Lambda isn't really the only way. There are other ways to create the middle layer such as creating an Express API and deploy it to your server but I went to the serverless approach as I just need the API only when needed and its a short-lived function that I will likely have 1-2 requests in a week.
Preparing the Request Payload
Below is just preparing the request payload where the variables user, repo, workflowID, branch, gToken are passed as environment variables stored in AWS lambda. The variables that we pass across will be used in creating the URL and the payload. The rest of the headers and body parameters can be referred to in Github's REST API on Creating a Workflow Dispatch Event.
Our workflows may be setup differently such as a workflow can be setup per environment, per branch or maybe a single workflow for everything.
// Define the GitHub API URL and headers
const url = `https://api.github.com/repos/${user}/${repo}/actions/workflows/${workflowID}/dispatches`;
const headers = {
Accept: 'application/vnd.github.v3+json',
Authorization: gtoken,
ContentType: 'application/json',
'X-GitHub-Api-Version': '2022-11-28'
};
// Request body
const body = JSON.stringify({
ref: branch,
inputs: inputs
});
const response = await fetch(url, { method: 'POST', headers, body });
We've put together a simple fetch to Github Actions that will be called whenever our Lambda function from Strapi.
I have created a simple node.js API which you can readily deploy as a container image in your AWS Lambda. I have included the steps on how to use this as well as the prerequisites to have this simple API up and running. If you find this useful and want to check out the code, you can get it from here.