Skip to content

Vault Management API in Python

fer edited this page Apr 22, 2024 · 6 revisions

Overview

This guide details the steps to set up a Python script for interacting with the Bitwarden Vault Management API to retrieve items from a user's vault.

It assumes you have a Bitwarden account and are familiar with basic Python programming.

Prerequisites

  • Bitwarden account.
  • Python preinstalled on your system.
  • An API key from Bitwarden for authenticating API requests.
  • bw cli tool is preinstalled on your system.

Step 1: Install CLI

  1. Download the zipped file from the Bitwarden download page.
  2. Install unzip with sudo apt-get install unzip -y.
  3. Unzip the downloaded file with unzip bw-linux-X.zip (where X is the release num ber).
  4. Give the binary executable permissions with chmod u+x bw.
  5. Move the executable to a directory in your path with sudo mv bw /usr/local/bin.

Step 2: Login to CLI

You'll now need to log in to your Bitwarden account with the command:

bw login

You'll be prompted for your Bitwarden email address, master password, and (if applicable) the two-step login code. Once you've successfully logged in, you'll be greeted with You are now logged in!.

Don't forget to export your session before the next step:

export BW_SESSION="2BroUblBCqw4M5hx1MMG4rZ+zU2/p588AsIanBYbynRCBlGW4111Yl38EQ1TJ3XbckQVWI3pq4dzlCKmOH7VMA=="

Step 3: Run serve command

The serve command starts a local express web server that can be used to take all actions accessible from the CLI in the form of RESTful API calls from an HTTP interface.

By default, serve will start the web server at port 8087 however you can specify an alternate port with the --port option.

bw serve

Step 4: Fetch all Vault items

Retrieve a list of existing items in your vault. By default, this will return a list of all existing items in your vault.

import requests

URL = 'http://localhost:8087/list/object/items'

def list_vault_items():

    response = requests.get(URL, headers={})
    
    if response.status_code == 200:
        resp = response.json()['data']
        for item in resp['data']:                    
            print(item['name'])
    else:
        print(f"Failed to retrieve items: {response.text}")

if __name__ == "__main__":
    list_vault_items()

Step 5: Execute

Simply execute your python script from the same terminal you exported BW_SESSION environment variable:

$ python3 list_vault_items.py 
Clone this wiki locally