xyzio

Authenticate with BackBlaze B2 and get file URLs using Python

leave a comment »

Authenticate with BackBlaze B2 and get the URLs of files in a bucket.

First to authenticate with BackBlaze B2:


import requests
from requests.auth import HTTPBasicAuth

#Auth information from Backblaze
key_id = 'key_id'
application_key = 'application_key'

#Authenticate
path = 'https://api.backblazeb2.com/b2api/v1/b2_authorize_account'
result = requests.get(path, auth=HTTPBasicAuth(key_id, application_key))
if result.status_code != 200:
    print 'Error - Could not connect to BackBlaze B2'
    exit()

#Read response
result_json = result.json()
account_id = result_json['accountId']
auth_token = result_json['authorizationToken']
api_url    = result_json['apiUrl'] + '/b2api/v1'
download_url = result_json['downloadUrl'] + '/file/'
api_session = requests.Session()
api_session.headers.update({ 'Authorization': auth_token })

Now get bucket contents and assemble URL. Sample code for bucket ID and bucket name is here.


#Initialize
bucketId = 'bucket_id_from_b2'
bucketName = 'name_of_bucket'

params = {'bucketId': bucketId}
urls = set()

#Loop for as long as a nextFile exists
while True:
    #Construct api call, execute, and read back information
    url = api_url + '/' + 'b2_list_file_names'
    fileList =  api_session.post(url, json=params)
    jFileList = fileList.json()

    #Loop through files and construct url
    for file in jFileList['files']:
        urls.add(download_url + bucketName + '/' + file['filename'])

    #Check for next file and break if it doesn't exist
    startFileName = jFileList['nextFileName']
    if startFileName == None:
        break
    else:
        #continue If next file exists
        params['startFileName'] = startFileName
        

Written by M Kapoor

December 23, 2019 at 7:17 pm

Posted in Programming

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: