Prerequisite
- Get your GitHub Personal Access Token here
- Fine-grained tokens
- All repository access or choose specific repository
- Read and write access for
Contents
- Tokens (classic)
- Tick ✅
repo
scope
- Tick ✅
- Fine-grained tokens
- Add into
.env
file
Make POST
request to /api/commit
with body below
Body
{
"username": "your-github-username",
"reponame": "your-repo-name",
"filePath": "path-to-file-to-edit.txt",
"content": "file content here",
"message": "commit message here"
}
Response
{
"status": "success",
"url": "https://github.com/<your-github-username>/<your-repo-name>/commit/<commit-sha>"
}
What's hapening under the hood.
Reference: https://blog.apihero.run/how-to-programmatically-create-a-commit-on-github
1. Fetch latest commit to get reference [Learn more]
GET /repos/{{owner}}/{{repo}}/git/ref/heads/{{branch}}
Save
body.object.sha
from response asreference_sha
.
2. Create a tree [Learn more]
POST /repos/{{owner}}/{{repo}}/git/trees
Body
{
"base_tree": "{{reference_sha}}",
"tree": [
{
"path": "{{filename}}",
"mode": "100644",
"type": "blob",
"content": "hello world"
}
]
}
Save
body.sha
from response astree_sha
.
3. Create a commit [Learn more]
POST /repos/{{owner}}/{{repo}}/git/commits
Body
{
"message": "commit message",
"parents": ["{{reference_sha}}"],
"tree": "{{tree_sha}}"
}
Save
body.sha
from response ascommit_sha
.
4. Update the reference [Learn more]
PATCH /repos/{{owner}}/{{repo}}/git/refs/heads/{{branch}}
Body
{
"sha": "{{commit_sha}}"
}
DONE! 🥳