b2_create_bucket

Creates a new bucket. A bucket belongs to the account used to create it.

Buckets can be named. The name must be globally unique. No account can use a bucket with the same name. Buckets are assigned a unique bucketId which is used when uploading, downloading, or deleting files. There is a limit of 100 buckets per account. Contact our Sales team if you need more than 100 buckets.

Warning: Do not include Protected Health Information (PHI) or Personally Identifiable Information (PII) in bucket names, object/file/folder names, or other metadata. Such metadata is not encrypted in a way that meets Health Insurance Portability and Accountability Act (HIPAA) protection requirements for PHI/PII data and is not generally encrypted in client-side encryption architectures.

Request

Request HTTP Headers

Authorization

required

An account authorization token, obtained from b2_authorize_account. The token must have the writeBuckets capability.

Request HTTP Message Body Parameters

accountId

required

Your account ID.

bucketName

required

The name to give the new bucket.

Bucket names must be a minimum of 6 and a maximum of 63 characters long, and must be globally unique; two different B2 accounts cannot have buckets with the name name. Bucket names can consist of: letters, digits, and "-". Bucket names cannot start with "b2-"; these are reserved for internal Backblaze use.

bucketType

required

Either "allPublic", meaning that files in this bucket can be downloaded by anybody, or "allPrivate", meaning that you need a bucket authorization token to download the files.

bucketInfo

optional

User-defined information to be stored with the bucket: a JSON object mapping names to values. See Buckets.
Cache-Control policies can be set here on a global level for all the files in the bucket.

corsRules

optional

The initial list (a JSON array) of CORS rules for this bucket. See CORS Rules for an overview and the rule structure.

fileLockEnabled

optional

If present, the boolean value specifies whether bucket is Object Lock-enabled. The default value is false. Setting the value to true requires the writeBucketRetentions capability.

lifecycleRules

optional

The initial list (a JSON array) of lifecycle rules for this bucket. Structure defined below. See Lifecycle Rules.

replicationConfiguration

optional

The configuration to create a Replication Rule. See Cloud Replication Rules.

defaultServerSideEncryption

optional

The default server-side encryption settings for this bucket. See Server-Side Encryption for an overview and the parameter structure.
Setting the value requires the writeBucketEncryption application key capability.

Response

Response HTTP Status 200

Bucket successfully created. The JSON response will contain:

accountId

The account that the bucket is in.

bucketId

The unique ID of the bucket.

bucketName

The unique name of the bucket

bucketType

One of: allPublic, allPrivate, restricted, snapshot, shared, or other values added in the future. allPublic means that anybody can download the files is the bucket; allPrivate means that you need an authorization token to download them; snapshot means that it's a private bucket containing snapshots created on the B2 web site.

bucketInfo

The user data stored with this bucket.

corsRules

The CORS rules for this bucket. See CORS Rules for an overview and the rule structure.

fileLockConfiguration

The Object Lock configuration for this bucket.
This field is filtered based on application key capabilities; readBucketRetentions capability is required to access the value. See Object Lock for more details on response structure.

defaultServerSideEncryption

The default bucket Server-Side Encryption settings for new files uploaded to this bucket.
This field is filtered based on application key capabilities; readBucketEncryption capability is required to access the value. See Server-Side Encryption for more details on response structure.

lifecycleRules

The list of lifecycle rules for this bucket. See Lifecycle Rules for an overview and the rule structure.

replicationConfiguration

The list of replication rules for this bucket. See Cloud Replication Rules for an overview and the rule structure.

revision

A counter that is updated every time the bucket is modified, and can be used with the ifRevisionIs parameter to b2_update_bucket to prevent colliding, simultaneous updates.

options

When present and set to s3, the bucket can be accessed through the S3 Compatible API.

Response Errors

Bucket not created. If possible the server will return a JSON error structure. Errors include:

status

code

description

400

bad_bucket_id

The requested bucket ID does not match an existing bucket.

400

bad_request

The request had the wrong fields or illegal values. The message returned with the error will describe the problem.

400

cannot_delete_non_empty_bucket

A bucket must be empty before it can be deleted. To delete this bucket, first remove all of the files in the bucket, then try the delete operation again.

400

too_many_buckets

The account is already at the maximum bucket count

400

duplicate_bucket_name

Bucket name is already in use.

401

bad_auth_token

The auth token used is not valid. Call b2_authorize_account again to either get a new one, or an error message describing the problem.

401

expired_auth_token

The auth token used has expired. Call b2_authorize_account again to get a new one.

401

unauthorized

The auth token used is valid, but does not authorize this call with these parameters. The capabilities of an auth token are determined by the application key used with b2_authorize_account.

403

transaction_cap_exceeded

Transaction cap exceeded. To increase your cap, sign in to your B2 Cloud Storage account online. Then select the Caps & Alerts link in the B2 Cloud Storage section of the sidebar.

Sample Code

Code

ACCOUNT_ID=... # Comes from your account page on the Backblaze web site
ACCOUNT_AUTHORIZATION_TOKEN=... # Comes from the b2_authorize_account call
API_URL=... # Comes from the b2_authorize_account call
BUCKET_NAME=any-name-you-pick # 63 char max: letters, digits, and hyphen -
BUCKET_TYPE=allPrivate # Either allPublic or allPrivate

curl -H "Authorization: $ACCOUNT_AUTHORIZATION_TOKEN" \
    "$API_URL/b2api/v2/b2_create_bucket?accountId=$ACCOUNT_ID&bucketName=$BUCKET_NAME&bucketType=$BUCKET_TYPE"

# NOTE: This example uses GET for the sake of brevity.  A curl example using the POST method is shown below. 
#       You will need to replace the bracketed values with your accountId, bucketName, and bucketType

curl -H  "Authorization: $ACCOUNT_AUTHORIZATION_TOKEN" \
	--data '{"accountId":"<ACCOUNT_ID>","bucketName":"<BUCKET_NAME>","bucketType":"<BUCKET_TYPE>"}' \
	"$API_URL/b2api/v2/b2_create_bucket"

Output

{
  "accountId": "12f634bf3cbz",
  "bucketId": "4a48fe8875c6214145260818",
  "bucketInfo" : {},
  "bucketName": "any-name-you-pick",
  "bucketType": "allPrivate",
  "corsRules": [],
  "defaultServerSideEncryption": {
    "isClientAuthorizedToRead" : true,
      "value": {
        "algorithm" : null,
        "mode" : null
      }
  },
  "fileLockConfiguration": {
    "isClientAuthorizedToRead": true,
    "value": {
      "defaultRetention": {
        "mode": null,
        "period": null
      },
      "isFileLockEnabled": false
    }
  },
  "lifecycleRules": [],
  "options": [],
  "revision": 2
}

Code

import java.io.*;
import java.util.*;
import java.net.HttpURLConnection;
import java.net.URL;

String apiUrl = ""; // Provided by b2_authorize_account
String accountId = ""; // Obtained from your B2 account page.
String accountAuthorizationToken = "";  // Provided by b2_authorize_account
String bucketName = ""; // Name of the bucket you want to create
String bucketType = ""; // Either "allPublic" or "allPrivate"
HttpURLConnection connection = null;

try {
    URL url = new URL(apiUrl + "/b2api/v2/b2_create_bucket");
    connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", accountAuthorizationToken);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
    connection.setDoOutput(true);
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    writer.write("{\"accountId\":\"" + accountId + "\",\"bucketName\":\"" + bucketName + "\",\"bucketType\":\"" + bucketType + "\"}".getBytes(StandardCharsets.UTF_8));
    String jsonResponse = myInputStreamReader(connection.getInputStream());
    System.out.println(jsonResponse);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
}

static public String myInputStreamReader(InputStream in) throws IOException {
    InputStreamReader reader = new InputStreamReader(in);
    StringBuilder sb = new StringBuilder();
    int c = reader.read();
    while (c != -1) {
        sb.append((char)c);
        c = reader.read();
    }
    reader.close();
    return sb.toString();
}

Output

{
  "accountId": "12f634bf3cbz",
  "bucketId": "4a48fe8875c6214145260818",
  "bucketInfo" : {},
  "bucketName": "any-name-you-pick",
  "bucketType": "allPrivate",
  "corsRules": [],
  "defaultServerSideEncryption": {
    "isClientAuthorizedToRead" : true,
      "value": {
        "algorithm" : null,
        "mode" : null
      }
  },
  "fileLockConfiguration": {
    "isClientAuthorizedToRead": true,
    "value": {
      "defaultRetention": {
        "mode": null,
        "period": null
      },
      "isFileLockEnabled": false
    }
  },
  "lifecycleRules": [],
  "options": [],
  "revision": 2
}

Code

import json
import urllib2

ACCOUNT_ID = "..." # Comes from your account page on the Backblaze web site
ACCOUNT_AUTHORIZATION_TOKEN = "..." # Comes from the b2_authorize_account call
API_URL = "..." # Comes from the b2_authorize_account call
BUCKET_NAME = "any-name-you-pick" # 63 char max: letters, digits, and hyphen -
BUCKET_TYPE = "allPrivate" # Either allPublic or allPrivate

url = API_URL + '/b2api/v2/b2_create_bucket'
params = {
    'accountId': ACCOUNT_ID,
    'bucketName': BUCKET_NAME,
    'bucketType': BUCKET_TYPE
    }
headers = {
    'Authorization': ACCOUNT_AUTHORIZATION_TOKEN
    }

request = urllib2.Request(url, json.dumps(params), headers)
response = urllib2.urlopen(request)
response_data = json.loads(response.read())
response.close()

print 'bucket id:', response['bucketId']


Output

bucket id: 4a48fe8875c6214145260818

Code

import Foundation

let apiUrl = "" // Provided by b2_authorize_account
let accountAuthorizationToken = "" // Provided by b2_authorize_account
let accountId = "" // B2 Cloud Storage Account ID
let bucketName = "" // Name of the bucket you want to create
let bucketType = "" // Either "allPublic" or "allPrivate"

// Create the request
var request = URLRequest(url: URL(string: "\(apiUrl)/b2api/v2/b2_create_bucket")!)
request.httpMethod = "POST"
request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
request.httpBody = "{\"accountId\":\"\(accountId)\", \"bucketName\":\"\(bucketName)\", \"bucketType\":\"\(bucketType)\"}".data(using: .utf8)

// Create the task
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
	if let data = data {
		let json = String(data: data, encoding: .utf8)
		print(json!)
	}
}

// Start the task
task.resume()

// Swift 4.1 (swiftlang-902.0.48 clang-902.0.37.1) Xcode 9.3.1 (9E501)

Output

{
  "accountId": "12f634bf3cbz",
  "bucketId": "4a48fe8875c6214145260818",
  "bucketInfo" : {},
  "bucketName": "any-name-you-pick",
  "bucketType": "allPrivate",
  "corsRules": [],
  "defaultServerSideEncryption": {
    "isClientAuthorizedToRead" : true,
      "value": {
        "algorithm" : null,
        "mode" : null
      }
  },
  "fileLockConfiguration": {
    "isClientAuthorizedToRead": true,
    "value": {
      "defaultRetention": {
        "mode": null,
        "period": null
      },
      "isFileLockEnabled": false
    }
  },
  "lifecycleRules": [],
  "options": [],
  "revision": 2
}

Code

require 'json'
require 'net/http'

api_url = "" # Provided by b2_authorize_account
account_id = "" # B2 Cloud Storage Account ID
account_authorization_token = "" # B2 Cloud Authorization Token
bucket_name = "" # Name of the bucket you want to create
bucket_type = "" # Either "allPublic" or "allPrivate"
uri = URI("#{api_url}/b2api/v2/b2_create_bucket")
req = Net::HTTP::Post.new(uri)
req.add_field("Authorization","#{account_authorization_token}")
req.body = "{\"accountId\":\"#{account_id}\",\"bucketName\":\"#{bucket_name}\",\"bucketType\":\"#{bucket_type}\"}"
http = Net::HTTP.new(req.uri.host, req.uri.port)
http.use_ssl = true
res = http.start {|http| http.request(req)}
case res
when Net::HTTPSuccess then
    res.body
when Net::HTTPRedirection then
    fetch(res['location'], limit - 1)
else
    res.error!
end

Output

{
  "accountId": "12f634bf3cbz",
  "bucketId": "4a48fe8875c6214145260818",
  "bucketInfo" : {},
  "bucketName": "any-name-you-pick",
  "bucketType": "allPrivate",
  "corsRules": [],
  "defaultServerSideEncryption": {
    "isClientAuthorizedToRead" : true,
      "value": {
        "algorithm" : null,
        "mode" : null
      }
  },
  "fileLockConfiguration": {
    "isClientAuthorizedToRead": true,
    "value": {
      "defaultRetention": {
        "mode": null,
        "period": null
      },
      "isFileLockEnabled": false
    }
  },
  "lifecycleRules": [],
  "options": [],
  "revision": 2
}

Code

String apiUrl = "API_URL"; //Provided by b2_authorize_account
String accountAuthorizationToken = "ACCOUNT_AUTHORIZATION_TOKEN"; //Provided by b2_authorize_account
String accountId = "ACCOUNT_ID"; //B2 Cloud Storage AccountID
String bucketName = "BUCKET_NAME"; //Name for the new bucket(unique)
String bucketType = "BUCKET_TYPE"; //"allPrivate" - or - "allPublic" 
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(apiUrl + "/b2api/v2/b2_create_bucket");
string body =
	"{\"accountId\":\"" + accountId + "\",\n" +
	"\"bucketName\":\"" + bucketName + "\",\n" +
	"\"bucketType\":\"" + bucketType + "\"}";
var data = Encoding.UTF8.GetBytes(body);
webRequest.Method = "POST";
webRequest.Headers.Add("Authorization", accountAuthorizationToken);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.ContentLength = data.Length;
using (var stream = webRequest.GetRequestStream())
{
	stream.Write(data, 0, data.Length);
	stream.Close();
}
WebResponse response = (HttpWebResponse)webRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();
Console.WriteLine(responseString);

Output

{
  "accountId": "12f634bf3cbz",
  "bucketId": "4a48fe8875c6214145260818",
  "bucketInfo" : {},
  "bucketName": "any-name-you-pick",
  "bucketType": "allPrivate",
  "corsRules": [],
  "defaultServerSideEncryption": {
    "isClientAuthorizedToRead" : true,
      "value": {
        "algorithm" : null,
        "mode" : null
      }
  },
  "fileLockConfiguration": {
    "isClientAuthorizedToRead": true,
    "value": {
      "defaultRetention": {
        "mode": null,
        "period": null
      },
      "isFileLockEnabled": false
    }
  },
  "lifecycleRules": [],
  "options": [],
  "revision": 2
}

Code

$account_id = ""; // Obtained from your B2 account page
$api_url = ""; // From b2_authorize_account call
$auth_token = ""; // From b2_authorize_account call
$bucket_name = ""; // 6 char min, 63 char max: letters, digits, and hyphen -
$bucket_type = "allPrivate"; // Either allPublic or allPrivate

$session = curl_init($api_url .  "/b2api/v2/b2_create_bucket");

// Add post fields
$data = array("accountId" => $account_id, "bucketName" => $bucket_name, "bucketType" => $bucket_type);
$post_fields = json_encode($data);
curl_setopt($session, CURLOPT_POSTFIELDS, $post_fields); 

// Add headers
$headers = array();
$headers[] = "Authorization: " . $auth_token;
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); 

curl_setopt($session, CURLOPT_POST, true); // HTTP POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);  // Receive server response
$server_output = curl_exec($session); // Let's do this!
curl_close ($session); // Clean up
echo ($server_output); // Tell me about the rabbits, George!

Output

{
  "accountId": "12f634bf3cbz",
  "bucketId": "4a48fe8875c6214145260818",
  "bucketInfo" : {},
  "bucketName": "any-name-you-pick",
  "bucketType": "allPrivate",
  "corsRules": [],
  "defaultServerSideEncryption": {
    "isClientAuthorizedToRead" : true,
      "value": {
        "algorithm" : null,
        "mode" : null
      }
  },
  "fileLockConfiguration": {
    "isClientAuthorizedToRead": true,
    "value": {
      "defaultRetention": {
        "mode": null,
        "period": null
      },
      "isFileLockEnabled": false
    }
  },
  "lifecycleRules": [],
  "options": [],
  "revision": 2
}