Access files using github api
Create, update and delete a file
You can do all of them via Contents API.
-
get_contents
in 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
encoding
andcontent
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: https://api.github.com/repos/longavailable/cscbank/contents.
README.md
of 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.
-
type
for 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,
content
is the special of this way. In addition, 1MB seems a little small. My idea is usingget_contents
for a directory to requestsha
anddownload_url
keywords, then userequests.get()
. Git Blobs API is another solution. -
-
create_file
in API v3, PyGithubPython script as follows:
g.get_repo(repoName).create_file(path=file,message= 'update '+file,content= dataBase64)
-
update_file
in API v3, PyGithubPython script as follows:
g.get_repo(repoName).update_file(path=file,message= 'update '+file,content= dataBase64,sha=sha)
Notice:
update_file
needsha
parameter, you have to requestsha
before 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/delft
of cscbank: https://api.github.com/repos/longavailable/cscbank/git/trees/master:nl/delft.Notices:
-
sha
is needed to useget_git_tree
using PyGithub. Actually, treePath/directory likesmaster:nl/delft
works as well. -
type
for a directory is tree, and for a file is blob.
-
-
get a blob in API v3, PyGithub
Notices:
-
sha
is needed to useget_git_blob
using PyGithub. -
This API supports blobs/files up to 100 megabytes in size.
-