简体   繁体   中英

Python How to download repository zip file from GitHub using github api

I am trying to download zip file of my repository using api but can not do so.

GitHub doc: github-download-zip-ref

What is the problem with my code? Thanks for your help.

I get only 404: not found error

import requests
import wget

from requests.api import request
headers = {"Authorization" : 'token ***', "Accept": 'application/vnd.github.v3+json'}
parameters = {"owner": 'enestekerlek', "repo": 'Hello-World', "ref": 'ref'}

r =requests.get('https://api.github.com/user/repos', headers = headers)
if (r.status_code == 200) : 
    x = requests.get('https://api.github.com/repos/enestekerlek/Hello-World/zipball/ref', headers = headers, params = parameters)

    print(x.content)
    print(type(x))
else :
    print("can not connect")

Your first problem can be that you use word ref in url.

It has to be (probably) branch name or empty string for master/main branch.

Other problem can be that your repo is empty so there is nothing to download. But I couldn't check it because I don't have empty repo and I was using Private Token to access only my repos.


Minimal working code which I used for tests.

import requests

headers = {
    "Authorization" : 'token ghp_r5***',
    "Accept": 'application/vnd.github.v3+json'
#    "Accept": '*.*',
}

OWNER = 'enestekerlek'
REPO  = 'Hello-World'

OWNER = 'furas'
#REPO = 'python-examples'  # it is downloading too long
REPO  = 'AutoDraw'

REF  = 'main'  # branch name
REF  = ''      # master/main branch 

EXT  = 'zip'
#EXT  = 'tar'  # it also works

url = f'https://api.github.com/repos/{OWNER}/{REPO}/{EXT}ball/{REF}'
print('url:', url)

r = requests.get(url, headers=headers)

if r.status_code == 200:
    print('size:', len(r.content))
    with open(f'output.{EXT}', 'wb') as fh:
        fh.write(r.content)
    print(r.content[:10])  # display only some part
else:
    print(r.text)    

Result:

url: https://api.github.com/repos/furas/AutoDraw/zipball/
size: 663179
b'PK\x03\x04\n\x00\x00\x00\x00\x00'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM