Search code examples
gitgithubgithub-api

Is it possible to publish a file one way to a github folder using github API or another method?


I'd like to be able to publish to Github one way. I've read part of the API here at https://docs.github.com/en/rest/quickstart.

It looks like it's possible to read resources from github using this API but I didn't see if it's possible to publish to a repository.

I believe I'd need the user to have git installed and run that. But I'm in a web based environment. That web based environment can't access or run local git calls.

Since my goal is only to push a complete set of files (no diffs) to a specific repository folder, is that possible with the github API?

For example, consider a web form that has an upload feature. In the web page you choose a file with a file input and then send that file with a network request like so:

var request = new XMLHttpRequest(); var formData = new FormData(); formData.append('file', file); request.addEventListener('load', responseHandler, false); request.open('POST', '/upload', true); request.send(formData);

I want to do the same thing. Basically, upload a file or files to a folder in my repository. I can probably reuse the credentials if I'm logged into Github in another tab or authorize through github login.

UPDATE:
This is for the user to be able to post to their own repository not mine. The use case is that the user wants one way write support to a directory of their repository (the github pages directory). They don't need diffs or git or anything else because they are creating the content on their local machine.


Solution

  • You can setup a OAuth app which people will have to install into their account. You can initiate that installation flow from your app.

    An Oauth app will let you act on behalf the logged in user. This sounds like the scenario you're after.

    With the OAuth token in hand, you can call create or update file API to upload the new file.

    // Octokit.js
    // https://github.com/octokit/core.js#readme
    const octokit = new Octokit({
      auth: 'YOUR-TOKEN'
    })
    
    await octokit.request('PUT /repos/{owner}/{repo}/contents/{path}', {
      owner: 'OWNER',
      repo: 'REPO',
      path: 'PATH',
      message: 'my commit message',
      committer: {
        name: 'Monalisa Octocat',
        email: '[email protected]'
      },
      content: 'bXkgbmV3IGZpbGUgY29udGVudHM=',
      headers: {
        'X-GitHub-Api-Version': '2022-11-28'
      }
    })