b2_create_key

Creates a new application key.

There is a limit of 100 million key creations per account.

Request

Request HTTP Headers

Authorization

required

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

Request HTTP Message Body Parameters

accountId

required

Your account ID.

capabilities

required

A list of strings, each one naming a capability the new key should have. Possibilities are: listKeys, writeKeys, deleteKeys, listAllBucketNames, listBuckets, readBuckets, writeBuckets, deleteBuckets, readBucketRetentions, writeBucketRetentions, readBucketEncryption, writeBucketEncryption, listFiles, readFiles, shareFiles, writeFiles, deleteFiles, readFileLegalHolds, writeFileLegalHolds, readFileRetentions, writeFileRetentions, bypassGovernance, readBucketReplications, and writeBucketReplications.

keyName

required

A name for this key. There is no requirement that the name be unique. The name cannot be used to look up the key. Names can contain letters, numbers, and "-", and are limited to 100 characters.

validDurationInSeconds

optional

When provided, the key will expire after the given number of seconds, and will have expirationTimestamp set. Value must be a positive integer, and must be less than 1000 days (in seconds).

bucketId

optional

When present, the new key can only access this bucket. When set, only these capabilities can be specified: listAllBucketNames, listBuckets, readBuckets, readBucketEncryption, writeBucketEncryption, readBucketRetentions, writeBucketRetentions, listFiles, readFiles, shareFiles, writeFiles, deleteFiles, readFileLegalHolds, writeFileLegalHolds, readFileRetentions, writeFileRetentions, and bypassGovernance.

namePrefix

optional

When present, restricts access to files whose names start with the prefix. You must set bucketId when setting this.

Response

Response HTTP Status 200

Bucket successfully created. The JSON response will contain:

keyName

required

The name assigned when the key was created.

applicationKeyId

required

The ID of the newly created key.

applicationKey

required

The secret part of the key. This is the only time it will be returned, so you need to keep it. This is not returned when you list the keys in your account.

capabilities

required

A list of strings, each one naming a capability the key has. Possibilities are: listKeys, writeKeys, deleteKeys, listAllBucketNames, listBuckets, readBuckets, writeBuckets, deleteBuckets, readBucketRetentions, writeBucketRetentions, readBucketEncryption, writeBucketEncryption, listFiles, readFiles, shareFiles, writeFiles, deleteFiles, readFileLegalHolds, writeFileLegalHolds, readFileRetentions, writeFileRetentions, and bypassGovernance.

accountId

required

The account that this application key is for.

expirationTimestamp

optional

When present, says when this key will expire, in milliseconds since 1970.

bucketId

optional

When present, restricts access to one bucket.

namePrefix

optional

When present, restricts access to files whose names start with the prefix

options

optional

When present, contains a set of strings. Reserved for future use.

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.

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

API_URL=""  # Provided by b2_authorize_account
ACCOUNT_ID=""  # Provided by b2_authorize_account
ACCOUNT_AUTHORIZATION_TOKEN=""  # Provided by b2_authorize_account
CAPABILITIES=""  # JSON array of key capabilities
KEY_NAME=""  # Name for the key
VALID_DURATION_IN_SECONDS=0  # Validity period, positive integer less than 86,400,000 (optional)
BUCKET_ID=""  # Restrict key to this bucket (optional)
NAME_PREFIX=""  # Restrict access to files with names starting with this prefix (optional)

curl -H "Authorization: ${ACCOUNT_AUTHORIZATION_TOKEN}" \
    -d "{
           \"accountId\":  \"${ACCOUNT_ID}\", \
           \"capabilities\":  ${CAPABILITIES}, \
           \"keyName\":  \"${KEY_NAME}\", \
           \"validDurationInSeconds\":  ${VALID_DURATION_IN_SECONDS}, \
           \"bucketId\":  \"${BUCKET_ID}\", \
           \"namePrefix\":  \"${NAME_PREFIX}\" \
       }" \
    "${API_URL}/b2api/v2/b2_create_key"

Output

{
  "accountId": "12f634bf3cbz",
  "applicationKey": "K0041ZMxZEop4JkYUJqEei1ZSep14zz",
  "applicationKeyId": "00512f95cf4dcf0000000004z",
  "bucketId": "e1256f0973908bfc71ed0c1z",
  "capabilities": [
    "listFiles",
    "readFiles"
  ],
  "expirationTimestamp": 1671147546259,
  "keyName": "key-0003",
  "namePrefix": "foo",
  "options": [
    "s3"
  ]
}

Code

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class CreateKey {
    public static void main(String[] args) {
        String apiUrl = ""; // Provided by b2_authorize_account
        String accountId = ""; // Provided by b2_authorize_account
        String accountAuthorizationToken = ""; // Provided by b2_authorize_account
        String capabilities = ""; // JSON array of key capabilities
        String keyName = ""; // Name for the key
        int validDurationInSeconds = 0; // Validity period, positive integer less than 86,400,000 (optional)
        String bucketId = ""; // Restrict key to this bucket (optional)
        String namePrefix = ""; // Restrict access to files with names starting with this prefix (optional)
        HttpURLConnection connection = null;

        String postParams = "{" +
                "\"accountId\": \"" + accountId + "\"," +
                "\"capabilities\": " + capabilities + "," +
                "\"keyName\": \"" + keyName + "\"," +
                "\"validDurationInSeconds\": " + validDurationInSeconds + "," +
                "\"bucketId\": \"" + bucketId + "\"," +
                "\"namePrefix\": \"" + namePrefix + "\"" +
        "}";
        byte[] postData = postParams.getBytes(StandardCharsets.UTF_8);

        try {
            URL url = new URL(apiUrl + "/b2api/v2/b2_create_key");
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", accountAuthorizationToken);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
            connection.setDoOutput(true);
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.write(postData);
            String jsonResponse = myInputStreamReader(connection.getInputStream());
            System.out.println(jsonResponse);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                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",
  "applicationKey": "K0041ZMxZEop4JkYUJqEei1ZSep14zz",
  "applicationKeyId": "00512f95cf4dcf0000000004z",
  "bucketId": "e1256f0973908bfc71ed0c1z",
  "capabilities": [
    "listFiles",
    "readFiles"
  ],
  "expirationTimestamp": 1671147546259,
  "keyName": "key-0003",
  "namePrefix": "foo",
  "options": [
    "s3"
  ]
}

Code

import requests

api_url = ""  # Provided by b2_authorize_account
account_id = ""  # Provided by b2_authorize_account
account_authorization_token = ""  # Provided by b2_authorize_account
capabilities = []  # Array of key capabilities
key_name = ""  # Name for the key
valid_duration_in_seconds = 0  # Validity period, positive integer less than 86,400,000 (optional)
bucket_id = ""  # Restrict key to this bucket (optional)
name_prefix = ""  # Restrict access to files with names starting with this prefix (optional)

response = requests.post(f'{api_url}/b2api/v2/b2_create_key',
                         json={
                             'accountId': account_id,
                             'capabilities': capabilities,
                             'keyName': key_name,
                             'validDurationInSeconds': valid_duration_in_seconds,
                             'bucketId': bucket_id,
                             'namePrefix': name_prefix
                         },
                         headers={'Authorization': account_authorization_token})
print(response.text)

Output

{
  "accountId": "12f634bf3cbz",
  "applicationKey": "K0041ZMxZEop4JkYUJqEei1ZSep14zz",
  "applicationKeyId": "00512f95cf4dcf0000000004z",
  "bucketId": "e1256f0973908bfc71ed0c1z",
  "capabilities": [
    "listFiles",
    "readFiles"
  ],
  "expirationTimestamp": 1671147546259,
  "keyName": "key-0003",
  "namePrefix": "foo",
  "options": [
    "s3"
  ]
}

Code

import Foundation

let apiUrl = "" // Provided by b2_authorize_account
let accountId = "" // Provided by b2_authorize_account
let accountAuthorizationToken = "" // Provided by b2_authorize_account
let capabilities = "" // JSON array of key capabilities
let keyName = "" // Name for the key
let validDurationInSeconds = 0 // Validity period, positive integer less than 86,400,000 (optional)
let bucketId = "" // Restrict key to this bucket (optional)
let namePrefix = "" // Restrict access to files with names starting with this prefix (optional)

// Create the request
var request = URLRequest(url: URL(string: "\(apiUrl)/b2api/v2/b2_create_key")!)
request.httpMethod = "POST"
request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
request.httpBody = """
{
    "accountId": "\(accountId)",
    "capabilities": \(capabilities),
    "keyName": "\(keyName)",
    "validDurationInSeconds": \(validDurationInSeconds),
    "bucketId": "\(bucketId)",
    "namePrefix": "\(namePrefix)"
}
""".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()

Output

{
  "accountId": "12f634bf3cbz",
  "applicationKey": "K0041ZMxZEop4JkYUJqEei1ZSep14zz",
  "applicationKeyId": "00512f95cf4dcf0000000004z",
  "bucketId": "e1256f0973908bfc71ed0c1z",
  "capabilities": [
    "listFiles",
    "readFiles"
  ],
  "expirationTimestamp": 1671147546259,
  "keyName": "key-0003",
  "namePrefix": "foo",
  "options": [
    "s3"
  ]
}

Code

require 'json'
require 'net/http'

api_url = "" # Provided by b2_authorize_account
account_id = "" # Provided by b2_authorize_account
account_authorization_token = "" # Provided by b2_authorize_account
capabilities = [] # Array of key capabilities
key_name = "" # Name for the key
valid_duration_in_seconds = 0 # Validity period, positive integer less than 86,400,000 (optional)
bucket_id = "" # Restrict key to this bucket (optional)
name_prefix = "" # Restrict access to files with names starting with this prefix (optional)

uri = URI("#{api_url}/b2api/v2/b2_create_key")
req = Net::HTTP::Post.new(uri)
req.add_field("Authorization","#{account_authorization_token}")
req.body = JSON.generate({
    accountId: account_id,
    capabilities: capabilities,
    keyName: key_name,
    validDurationInSeconds: valid_duration_in_seconds,
    bucketId: bucket_id,
    namePrefix: name_prefix
})
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
    puts res.body
when Net::HTTPRedirection then
    fetch(res['location'], limit - 1)
else
    res.error!
end

Output

{
  "accountId": "12f634bf3cbz",
  "applicationKey": "K0041ZMxZEop4JkYUJqEei1ZSep14zz",
  "applicationKeyId": "00512f95cf4dcf0000000004z",
  "bucketId": "e1256f0973908bfc71ed0c1z",
  "capabilities": [
    "listFiles",
    "readFiles"
  ],
  "expirationTimestamp": 1671147546259,
  "keyName": "key-0003",
  "namePrefix": "foo",
  "options": [
    "s3"
  ]
}

Code

using System.Net;
using System.Net.Http;
using System.Text;

var apiUrl = ""; //Provided by b2_authorize_account 
var accountAuthorizationToken = ""; //Provided by b2_authorize_account
var accountId = ""; //Provided by b2_authorize_account
var capabilities = ""; // JSON array of key capabilities
var keyName = ""; // Name for the key
int validDurationInSeconds = 0; // Validity period, positive integer less than 86,400,000 (optional)
var bucketId = ""; // Restrict key to this bucket (optional)
var namePrefix = ""; // Restrict access to files with names starting with this prefix (optional)

var body = "{" +
    "\"accountId\": \"" + accountId + "\"," +
    "\"capabilities\": " + capabilities + "," +
    "\"keyName\": \"" + keyName + "\"," +
    "\"validDurationInSeconds\": " + validDurationInSeconds + "," +
    "\"bucketId\": \"" + bucketId + "\"," +
    "\"namePrefix\": \"" + namePrefix + "\"" +
"}";

HttpClient client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, 
    new Uri(apiUrl + "/b2api/v2/b2_create_key"));
request.Headers.TryAddWithoutValidation("Authorization", accountAuthorizationToken);
request.Content = new StringContent(body, Encoding.UTF8, "application/json");

using var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();

Console.WriteLine(responseBody);

Output

{
  "accountId": "12f634bf3cbz",
  "applicationKey": "K0041ZMxZEop4JkYUJqEei1ZSep14zz",
  "applicationKeyId": "00512f95cf4dcf0000000004z",
  "bucketId": "e1256f0973908bfc71ed0c1z",
  "capabilities": [
    "listFiles",
    "readFiles"
  ],
  "expirationTimestamp": 1671147546259,
  "keyName": "key-0003",
  "namePrefix": "foo",
  "options": [
    "s3"
  ]
}

Code

$account_id = ""; // From b2_authorize_account call
$api_url = ""; // From b2_authorize_account call
$auth_token = ""; // From b2_authorize_account call
$capabilities = []; // Array of key capabilities
$key_name = ""; // Name for the key
$valid_duration_in_seconds = 0; // Validity period, positive integer less than 86,400,000 (optional)
$bucket_id = ""; // Restrict key to this bucket (optional)
$name_prefix = ""; // Restrict access to files with names starting with this prefix (optional)

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

// Add post fields
$data = array(
    "accountId" => $account_id,
    "capabilities" => $capabilities,
    "keyName" => $key_name,
    "validDurationInSeconds" => $valid_duration_in_seconds,
    "bucketId" => $bucket_id,
    "namePrefix" => $name_prefix
);
$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);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($session);
curl_close ($session);

echo ($server_output);

Output

{
  "accountId": "12f634bf3cbz",
  "applicationKey": "K0041ZMxZEop4JkYUJqEei1ZSep14zz",
  "applicationKeyId": "00512f95cf4dcf0000000004z",
  "bucketId": "e1256f0973908bfc71ed0c1z",
  "capabilities": [
    "listFiles",
    "readFiles"
  ],
  "expirationTimestamp": 1671147546259,
  "keyName": "key-0003",
  "namePrefix": "foo",
  "options": [
    "s3"
  ]
}