xyzio

Authenticate with BackBlaze B2 and list buckets with Python

with one comment

Authenticate with BackBlaze B2 and list buckets with Python.

First to authenticate with BackBlaze B2:


import requests
from requests.auth import HTTPBasicAuth

#Credentials from BackBlaze B2 manager
key_id          = 'b2_key_id'
application_key = 'b2_application_key'

#Contact authorization server and check response
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()

#Get results and add authorization token to headers
result_json = result.json()
account_id  = result_json['accountId']
auth_token  = result_json['authorizationToken']
api_url     = result_json['apiUrl'] + '/b2api/v1'
api_session = requests.Session()
api_session.headers.update({ 'Authorization': auth_token })

Now use api_session to interact with B2. For example, download the list of buckets like this:


#Construct the API url
url = api_url + '/b2_list_buckets'

#Use the api_session parameter to get a list of buckets
bucketInfo = api_session.post(url, json={'accountId': account_id})

#Convert datastream to json
jsonBucketInfo = bucketInfo.json()

#List id and name
for bucket in jsonBucketInfo['buckets']:
    bucketId = bucket['bucketId']
    bucketName = bucket['bucketName']

    print bucketId, bucketName

More details about tokens in the json are on BackBlaze’s list_buckets API page.

Written by M Kapoor

December 23, 2019 at 8:05 pm

Posted in Programming

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. […] Now get bucket contents and assemble URL. Sample code for bucket ID and bucket name is here. […]


Leave a reply to Authenticate with BackBlaze B2 and get file URLs using Python | xyzio Cancel reply