0

Salutations - I'm trying to use the Github API to update a file which I'm generating in Google Apps Script. I'm displaying the file (an image) on a Github page. Unfortunately my knowledge of the Github API and of HTTP requests are poor.

How would I configure UrlFetchApp to commit a file to my Github repo? I think a similar idea is expressed in this question but I don't know how to translate it accurately to Apps Script and I'm finding it hard to debug against the API. Very grateful for help!

Mark C.
  • 1,773
  • 2
  • 16
  • 26

1 Answers1

2

From:

If you want to convert the following curl command of this thread to Google Apps Script,

curl -i -X PUT \
  -H 'Authorization: token <token_string>' \
  -d '{"path": "<filename.extension>", "message": "<Commit Message>", "committer": {"name": "<Name>", "email": "<E-Mail>"}, "content": "<Base64 Encoded>", "branch": "master"}' \
  https://api.github.com/repos/<owner>/<repository>/contents/<filename.extension>

To:

it becomes as follows.

function myFunction() {
  const fileId = "###"; // Please set the file ID you want to upload here.
  const content = Utilities.base64Encode(DriveApp.getFileById(fileId).getBlob().getBytes());
  const url = "https://api.github.com/repos/<owner>/<repository>/contents/<filename.extension>";
  const data = {"path": "<filename.extension>", "message": "<Commit Message>", "committer": {"name": "<Name>", "email": "<E-Mail>"}, "content": content, "branch": "master"};
  const params = {
    method: "put",
    payload: JSON.stringify(data),
    headers: {
      authorization: `token <token_string>`,
      // Accept: "application/vnd.github.v3+json"  // Even when this is not used, the request works.
    }
  };
  const res = UrlFetchApp.fetch(url, params);
  console.log(res.getContentText())
}
  • About <filename.extension>, for example, when you want to put sample.txt to the under the directory of ./sample, please use the URL like https://api.github.com/repos/<owner>/<repository>/contents/sample/sample.txt.

Note:

  • In this case, your token is required to be able to be used. So please be careful this.

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165