Access files using github api

Posted by Bruce Liu on March 26, 2020

Create, update and delete a file

You can do all of them via Contents API.

  • get_contents in API v3, PyGithub

    Python script as follows:

    from github import Github
    g = Github().get_user()

    Here the filePath can be a path for file or directory. For a file, it will has its encoded content with encoding and content keywords. For a directory, it will return a list-like object contents all infomations of the files or subdirectories except content.

    Responce examples of GitHub API v3:

    The root directory of cscbank: of cscbank:


    • It can be used for a directory and a file.

    • This API has an upper limit of 1,000 files for a directory. If you need to retrieve more files, use the Git Trees API.

    • This API supports files up to 1 megabyte in size.

    • type for a directory is dir, and for a file is file.


    If you do NOT want to access content of a file, then donot get_contents for a file. That is, content is the special of this way. In addition, 1MB seems a little small. My idea is using get_contents for a directory to request sha and download_url keywords, then use requests.get(). Git Blobs API is another solution.

  • create_file in API v3, PyGithub

    Python script as follows:

    g.get_repo(repoName).create_file(path=file,message= 'update '+file,content= dataBase64)
  • update_file in API v3, PyGithub

    Python script as follows:

    g.get_repo(repoName).update_file(path=file,message= 'update '+file,content= dataBase64,sha=sha)

    Notice: update_file need sha parameter, you have to request sha before use it.

Git Trees API and Git Blobs API


Python tools

Share on:

« PREVIOUS: How to change the color of first word in Windows PowerShell
NEXT: Docker commands in Chinese »