Updated July 8, 2021
I face a similar issue - I'm working on a Web App that can be integrated with GitHub. In the app's flow, a user can add a link to the GitHub repo and then commit and push files into the remote GitHub repository. I use GitHub v3 API for this.
The problem is to commit a file, you need to make a chain of requests:
- Get existing file tree from the repo
GET https://api.github.com/repos/USER/REPO/git/commits/COMMIT_SHA
- Create new file tree
- Create a commit
For the step 1 you need to know a commit's sha which does not exist if a repository is completelly empty.
If the repo is empty and it doesn't contain any files, you can add files there like this (with this API you can add a file without commit's sha):
PUT https://api.github.com/repos/USER/REPO/contents/YOUR_FILE_NAME
{
"branch": "BRANCH_NAME",
"message": "COMMIT_MESSAGE",
"content": "ENCODED_FILE_CONTENT"
}
ENCODED_FILE_CONTENT can be get with btoa
JS function, like this:
var encodedFileContent = btoa(fileString);
For example, the following request will create test.js
file with content "123" and commit's message "test" in the branch with the name "main".
PUT https://api.github.com/repos/USER/REPO/contents/test.js
{
"branch": "main",
"message": "test",
"content": "MTIz"
}