afrieirham / github-commit-rest-api

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GitHub Commit REST API.

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
  • 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>"
}

How to make GitHub commit programatically.

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 as reference_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 as tree_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 as commit_sha.

4. Update the reference [Learn more]

PATCH /repos/{{owner}}/{{repo}}/git/refs/heads/{{branch}}

Body

{
  "sha": "{{commit_sha}}"
}

DONE! 🥳

About


Languages

Language:TypeScript 92.7%Language:CSS 5.5%Language:JavaScript 1.8%