January 19, 2025
+ 12
Get up and running quickly, installing the Couchbase Python SDK, and running our Hello World example.

The Couchbase Python SDK allows Python applications to access a Couchbase cluster. It offers a traditional synchronous API as well as integration with twisted and asyncio.

In this guide, you will learn:

Hello Couchbase

We will go through the code sample step by step, but for those in a hurry to see it, here it is:

To connect to Couchbase Capella, be sure to get the correct endpoint as well as user, password, and bucket name. The certificate for connecting to Capella is included in the 4.1 Python SDK.

python
from datetime import timedelta # needed for any cluster connection from couchbase.auth import PasswordAuthenticator from couchbase.cluster import Cluster # needed for options -- cluster, timeout, SQL++ (N1QL) query, etc. from couchbase.options import (ClusterOptions, ClusterTimeoutOptions, QueryOptions) # Update this to your cluster endpoint = "--your-instance--.dp.cloud.couchbase.com" username = "username" password = "Password!123" bucket_name = "travel-sample" # User Input ends here. # Connect options - authentication auth = PasswordAuthenticator(username, password) # get a reference to our cluster options = ClusterOptions(auth) # Sets a pre-configured profile called "wan_development" to help avoid latency issues # when accessing Capella from a different Wide Area Network # or Availability Zone(e.g. your laptop). options.apply_profile('wan_development') cluster = Cluster('couchbases://{}'.format(endpoint), options) # Wait until the cluster is ready for use. cluster.wait_until_ready(timedelta(seconds=5)) # get a reference to our bucket cb = cluster.bucket(bucket_name) cb_coll = cb.scope("inventory").collection("airline") def upsert_document(doc): print("\nUpsert CAS: ") try: # key will equal: "airline_8091" key = doc["type"] + "_" + str(doc["id"]) result = cb_coll.upsert(key, doc) print(result.cas) except Exception as e: print(e) # get document function def get_airline_by_key(key): print("\nGet Result: ") try: result = cb_coll.get(key) print(result.content_as[str]) except Exception as e: print(e) # query for new document by callsign def lookup_by_callsign(cs): print("\nLookup Result: ") try: inventory_scope = cb.scope('inventory') sql_query = 'SELECT VALUE name FROM airline WHERE callsign = $1' row_iter = inventory_scope.query( sql_query, QueryOptions(positional_parameters=[cs])) for row in row_iter: print(row) except Exception as e: print(e) airline = { "type": "airline", "id": 8091, "callsign": "CBS", "iata": None, "icao": None, "name": "Couchbase Airways", } upsert_document(airline) get_airline_by_key("airline_8091") lookup_by_callsign("CBS")

The Couchbase Capella free tier version comes with the Travel Sample Bucket, and its Query indexes, loaded and ready.

Quick Installation

The SDK will run on supported versions Python. A more detailed guide in our Installation page covers every supported platform, but this section should be enough to get up and running for most supported Operating Systems.

If you are running Catalina (macOS 10.15) — or have other detailed requirements — take a look at our full installation guide. Otherwise, read on for a quick install on macOS Big Sur or Monterey.

The Python SDK has wheels are available on macOS for supported versions of Python.

First, make sure that your brew package index is up-to-date:

console
$ brew update

Install a compatible Python 3:

console
$ brew install python3

Ensure that the Python installation can be called from the shell:

console
$ echo 'export PATH="/usr/local/bin:"$PATH' >> ~/.zshrc
console
$ source ~/.zshrc

Now, install the Python SDK:

console
$ sudo -H python3 -m pip install couchbase
Starting with Python 3.11.5, macOS installers from python.org now use OpenSSL 3.0. If using a version prior to 4.1.9 of the Python SDK, a potential side-effect of this change is an ImportError: DLL load failed while importing pycbc_core error. Upgrade the SDK to a version >= 4.1.9 to avoid this side-effect. If unable to upgrade, a work-around is to set the PYCBC_OPENSSL_DIR environment variable to the path where the OpenSSL 1.1 libraries (libssl.1.1.dylib ` and `libcrypto.1.1.dylib) can be found.

If there are any problems, refer to the full Installation page.

Prerequisites

The following code samples assume:

  • You have signed up to Couchbase Capella.

  • You have created your own bucket, or loaded the Travel Sample dataset. Note, the Travel Sample dataset is installed automatically when deploying a Capella free tier cluster.

  • A user is created with permissions to access the cluster (at least Application Access permissions). See the Capella connection page for more details.

Couchbase Capella uses Roles to control user access to cluster resources. For the purposes of this guide, you can use the Organization Owner role automatically assigned to your account during installation of the Capella cluster. In a production scenario, we strongly recommend setting up users with more granular access roles as a best practice.

Step-by-Step

At this point we want to transition from the terminal to your code editor of choice.

Let’s now create an empty file named cb-test.py and walk through adding code step-by-step.

Here are all the import statements that you will need to run the sample code:

python
from datetime import timedelta # needed for any cluster connection from couchbase.auth import PasswordAuthenticator from couchbase.cluster import Cluster # needed for options -- cluster, timeout, SQL++ (N1QL) query, etc. from couchbase.options import (ClusterOptions, ClusterTimeoutOptions, QueryOptions)

Connect

The basic connection details that you’ll need are given below — for more background information, refer to the Managing Connections page.

From version 4.0, the Python SDK includes Capella’s standard certificates by default, so you don’t need any additional configuration. You do need to enable TLS, which can be done by simply using couchbases:// in the connection string as in this example.

python
# Update this to your cluster endpoint = "--your-instance--.dp.cloud.couchbase.com" username = "username" password = "Password!123" bucket_name = "travel-sample" # User Input ends here. # Connect options - authentication auth = PasswordAuthenticator(username, password) # get a reference to our cluster options = ClusterOptions(auth) # Sets a pre-configured profile called "wan_development" to help avoid latency issues # when accessing Capella from a different Wide Area Network # or Availability Zone(e.g. your laptop). options.apply_profile('wan_development') cluster = Cluster('couchbases://{}'.format(endpoint), options) # Wait until the cluster is ready for use. cluster.wait_until_ready(timedelta(seconds=5))

When accessing Capella from a different Wide Area Network or Availability Zone, you may experience latency issues with the default connection settings. SDK 4.1 introduces a wan_development Configuration Profile, which provides pre-configured timeout settings suitable for working in high latency environments. Basic usage is shown in the example above, but if you want to learn more see Constrained Network Environments.

The Configuration Profiles feature is currently a Volatile API and may be subject to change.

Following successful authentication, add this code snippet to access your Bucket:

python
# get a reference to our bucket cb = cluster.bucket(bucket_name)

Add and Retrieve Documents

The Python SDK supports full integration with the Collections feature introduced in Couchbase Server 7.0. Collections allow documents to be grouped by purpose or theme, according to a specified Scope.

Here we refer to the users collection within the tenant_agent_00 scope from the Travel Sample bucket as an example, but you may replace this with your own data.

python
cb_coll = cb.scope("inventory").collection("airline")

The code shows how you would use a named collection and scope.

For Local Couchbase Server only

The default_collection must be used when connecting to a 6.6 cluster or earlier.

python
# Get a reference to the default collection, required for older Couchbase server versions cb_coll_default = cb.default_collection()

Let’s create a dictionary object in our application that we can add to our travel-sample bucket that conforms to the structure of a document of type airline.

python
airline = { "type": "airline", "id": 8091, "callsign": "CBS", "iata": None, "icao": None, "name": "Couchbase Airways", }

Data operations, such as storing and retrieving documents, can be done using simple methods on the Collection class such as Collection.get and Collection.upsert. Simply pass the key (and value, if applicable) to the relevant methods.

The following function will upsert a document and print the returned CAS value:

python
def upsert_document(doc): print("\nUpsert CAS: ") try: # key will equal: "airline_8091" key = doc["type"] + "_" + str(doc["id"]) result = cb_coll.upsert(key, doc) print(result.cas) except Exception as e: print(e)

Call the upsert_document() function passing in our airline document:

python
upsert_document(airline)

Now let’s retrieve that document using a key-value operation. The following function runs a get() for a document key and either logs out the result or error in our console:

python
# get document function def get_airline_by_key(key): print("\nGet Result: ") try: result = cb_coll.get(key) print(result.content_as[str]) except Exception as e: print(e)

Call the get_airline_by_key function passing in our valid document key airline_8091:

python
get_airline_by_key("airline_8091")

SQL++ Lookup

Couchbase SQL++ queries can be performed at the Cluster or Scope level by invoking Cluster.query() or Scope.query().

Cluster level queries require you to specify the fully qualified keyspace each time (e.g. travel-sample.inventory.airline). However, with a Scope level query you only need to specify the Collection name — which in this case is airline:

python
# query for new document by callsign def lookup_by_callsign(cs): print("\nLookup Result: ") try: inventory_scope = cb.scope('inventory') sql_query = 'SELECT VALUE name FROM airline WHERE callsign = $1' row_iter = inventory_scope.query( sql_query, QueryOptions(positional_parameters=[cs])) for row in row_iter: print(row) except Exception as e: print(e)

We call the lookup_by_callsign function passing in our callsign CBS:

python
lookup_by_callsign("CBS")

Execute!

Now we can run our code using the following command:

console
$ python3 cb-test.py

The results you should expect are as follows:

console
Upsert CAS: 1598469741559152640 Get Result: {'type': 'airline', 'id': 8091, 'callsign': 'CBS', 'iata': None, 'icao': None, 'name': 'Couchbase Airways'} Lookup Result: Couchbase Airways

Next Steps

Now you’re up and running, try one of the following:

Additional Resources

The API reference is generated for each release and the latest can be found here.

Older API references are linked from their respective sections in the Individual Release Notes. Most of the API documentation can also be accessed via pydoc.

Migration page highlights the main differences to be aware of when migrating your code.

Couchbase welcomes community contributions to the Python SDK. The Python SDK source code is available on GitHub.

Troubleshooting