March 13, 2022 • 2 min read
I recently started using the GitHub API for a project I'm working on. My goal was to have users fill out a form and when the form is submitted, have the content saved as a new file in a folder of a GitHub repo. In order to get this working, four things need to happen.
For my scenario, I only wanted to automate, steps 1, 2, and 3. Step four will be done manually once the PR is reviewed. I found that the GitHub API offers great tutorials on step 2 and step 3, but not so much step 1, creating a branch.
The firs thing we need to do is install and configure a REST client that will allow us to make requests to the API.
I'm assuming you will be using JavaScript to interact with the API. If you are, GitHub offers an easy to use and minimilistic JS REST client, @octokit/core
, which is
what I used.
Once you have an Octokit client installed, create a Personal Access Token (PAT) by following this guide. Make sure to assign only the scopes you need and then copy the auth token that is created. Once you do that, pass the auth token to the contstructor of Octokit.
1import { Octokit } from '@octokit/core';2// If using commonJs:3// const { Octokit } = require('@octokit/core');45const octokit = new Octokit({ auth: 'auth-token' })
Make sure not to save the auth token in your code/repo as is it is a security risk. At the very least, you can store it in an environment variable.
To create a branch using the GitHub API, you actually need to create a ref
, short for 'references'. You can do this by calling the following API with the given parameters.
Make sure to modify it to use your own values. You can learn more about this API resource here.
1await octokit.request('POST /repos/{owner}/{repo}/git/refs', {2owner: 'my-username',3repo: 'my-repo',4ref: 'refs/heads/my-new-branch',5sha: 'base-branch-sha'.6})
The ref
value is required. The name of the ref has to follow the format you see in the example code above. It should start with refs
and have at last two slashes.
The sha
value, aka SHA1 hash value is also required. This is the hash identifying the change you are basing your branch off of. For example, if you
wanted to base your branch off the latest change in your main
branch you would use that SHA value. For convenience if you wanted to
get the current SHA of a branch you can run the following, where main is the name of the branch you care about.
1git rev-parse main
That will spit out the SHA hash value which you can copy and paste in the sha
key of the request params.
Once you run the example code, you should have a new branch created in your repo. To create a pull request using that branch you can follow this guide.
If you found this hepful, don't forget to share and subscribe 😀