Access files using github api
Create, update and delete a file
You can do all of them via Contents API.
-
get_contentsin API v3, PyGithubPython script as follows:
from github import Github g = Github().get_user() g.get_repo(repoName).get_contents(filePath)Here the filePath can be a path for file or directory. For a file, it will has its encoded content with
encodingandcontentkeywords. 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: https://api.github.com/repos/longavailable/cscbank/contents.
README.mdof cscbank: https://api.github.com/repos/longavailable/cscbank/contents/README.md.Important❗
-
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.
-
typefor a directory is dir, and for a file is file.
Suggestion:
If you do NOT want to access content of a file, then donot get_contents for a file. That is,
contentis the special of this way. In addition, 1MB seems a little small. My idea is usingget_contentsfor a directory to requestshaanddownload_urlkeywords, then userequests.get(). Git Blobs API is another solution. -
-
create_filein API v3, PyGithubPython script as follows:
g.get_repo(repoName).create_file(path=file,message= 'update '+file,content= dataBase64) -
update_filein API v3, PyGithubPython script as follows:
g.get_repo(repoName).update_file(path=file,message= 'update '+file,content= dataBase64,sha=sha)Notice:
update_fileneedshaparameter, you have to requestshabefore use it.
Git Trees API and Git Blobs API
-
get a tree in API v3, PyGithub
If a directory has more than 1,000 files or you want to get the content of a over-1MB-while-below-100MB file directly using Git Blobs API.
Responce examples of GitHub API v3:
The root tree/directory of cscbank: https://api.github.com/repos/longavailable/cscbank/git/trees/master.
Subtree/subdirectory
nl/delftof cscbank: https://api.github.com/repos/longavailable/cscbank/git/trees/master:nl/delft.Notices:
-
shais needed to useget_git_treeusing PyGithub. Actually, treePath/directory likesmaster:nl/delftworks as well. -
typefor a directory is tree, and for a file is blob.
-
-
get a blob in API v3, PyGithub
Notices:
-
shais needed to useget_git_blobusing PyGithub. -
This API supports blobs/files up to 100 megabytes in size.
-