Quickstart: Build a Cassandra app with Python SDK and Azure Cosmos DB

This quickstart shows how to use Python and the Azure Cosmos DB Cassandra API to build a profile app by cloning an example from GitHub. This quickstart also shows you how to use the web-based Azure portal to create an Azure Cosmos DB account.

Azure Cosmos DB is Microsoft's globally distributed multi-model database service. You can quickly create and query document, table, key-value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.


If you don't have an Azure subscription, create a free account before you begin. Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments.

In addition, you need:

Create a database account

Before you can create a document database, you need to create a Cassandra account with Azure Cosmos DB.

  1. In a new browser window, sign in to the Azure portal.

  2. Select Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new

    Then enter the same unique name as provided in ID
    Select Create new. Then enter a new resource-group name for your account. For simplicity, use the same name as your ID.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    The ID can use only lowercase letters, numbers, and the hyphen (-) character. It must be between 3 and 31 characters in length.
    API Cassandra The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core(SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. Currently, you must create a separate account for each API.

    Select Cassandra because in this quickstart you are creating a table that works with the Cassandra API.

    Learn more about the Cassandra API.
    Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.

    Select Review+Create. You can skip the Network and Tags section.

    The new account page for Azure Cosmos DB

  4. The account creation takes a few minutes. Wait for the portal to display the page saying Congratulations! Your Azure Cosmos DB account was created.

Clone the sample application

Now let's clone a Cassandra API app from GitHub, set the connection string, and run it. You see how easy it is to work with data programmatically.

  1. Open a command prompt. Create a new folder named git-samples. Then, close the command prompt.

    md "C:\git-samples"
  2. Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
  3. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-cassandra-python-getting-started.git

Review the code

This step is optional. If you're interested to learn how the code creates the database resources, you can review the following snippets. The snippets are all taken from the pyquickstart.py file. Otherwise, you can skip ahead to Update your connection string.

  • The username and password values were set using the connection string page in the Azure portal. The path\to\cert provides a path to an X509 certificate.

      ssl_opts = {
      	    'ca_certs': 'path\to\cert',
      	    'ssl_version': ssl.PROTOCOL_TLSv1_2
      auth_provider = PlainTextAuthProvider( username=cfg.config['username'], password=cfg.config['password'])
      cluster = Cluster([cfg.config['contactPoint']], port = cfg.config['port'], auth_provider=auth_provider, ssl_options=ssl_opts)
      session = cluster.connect()
  • The cluster is initialized with contactPoint information. The contactPoint is retrieved from the Azure portal.

    cluster = Cluster([cfg.config['contactPoint']], port = cfg.config['port'], auth_provider=auth_provider)
  • The cluster connects to the Azure Cosmos DB Cassandra API.

    session = cluster.connect()
  • A new keyspace is created.

    session.execute('CREATE KEYSPACE IF NOT EXISTS uprofile WITH replication = {\'class\': \'NetworkTopologyStrategy\', \'datacenter1\' : \'1\' }')
  • A new table is created.

    session.execute('CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)');
  • Key/value entities are inserted.

    insert_data = session.prepare("INSERT INTO  uprofile.user  (user_id, user_name , user_bcity) VALUES (?,?,?)")
    session.execute(insert_data, [1,'Lybkov','Seattle'])
    session.execute(insert_data, [2,'Doniv','Dubai'])
    session.execute(insert_data, [3,'Keviv','Chennai'])
    session.execute(insert_data, [4,'Ehtevs','Pune'])
    session.execute(insert_data, [5,'Dnivog','Belgaum'])
  • Query to get all key values.

    rows = session.execute('SELECT * FROM uprofile.user')
  • Query to get a key-value.

    rows = session.execute('SELECT * FROM uprofile.user where user_id=1')

Update your connection string

Now go back to the Azure portal to get your connection string information and copy it into the app. The connection string enables your app to communicate with your hosted database.

  1. In the Azure portal, select Connection String.

    Use the Copy button button on the right side of the screen to copy the top value, the CONTACT POINT.

    View and copy an access user name, password and contact point in the Azure portal, connection string blade

  2. Open the config.py file.

  3. Paste the CONTACT POINT value from the portal over <FILLME> on line 10.

    Line 10 should now look similar to

    'contactPoint': 'cosmos-db-quickstarts.cassandra.cosmosdb.azure.com:10350'

  4. Copy the USERNAME value from the portal and paste it over <FILLME> on line 6.

    Line 6 should now look similar to

    'username': 'cosmos-db-quickstart',

  5. Copy the PASSWORD value from the portal and paste it over <FILLME> on line 8.

    Line 8 should now look similar to

    'password' = '2Ggkr662ifxz2Mg==';`

  6. Save the config.py file.

Use the X509 certificate

  1. Download the Baltimore CyberTrust Root certificate locally from https://cacert.omniroot.com/bc2025.crt. Rename the file using the file extension .cer.

    The certificate has serial number 02:00:00:b9 and SHA1 fingerprint d4🇩🇪20:d0:5e:66:fc:53:fe:1a:50:88:2c:78:db:28:52:ca:e4:74.

  2. Open pyquickstart.py and change the path\to\cert to point to your new certificate.

  3. Save pyquickstart.py.

Run the Python app

  1. Use the cd command in the git terminal to change into the azure-cosmos-db-cassandra-python-getting-started folder.

  2. Run the following commands to install the required modules:

    python -m pip install cassandra-driver
    python -m pip install prettytable
    python -m pip install requests
    python -m pip install pyopenssl
  3. Run the following command to start your node application:

    python pyquickstart.py
  4. Verify the results as expected from the command line.

    Press CTRL + C to stop execution of the program and close the console window.

    View and verify the output

  5. In the Azure portal, open Data Explorer to query, modify, and work with this new data.

    View the data in Data Explorer

Review SLAs in the Azure portal

The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.

To review metrics and SLAs:

  1. Select Metrics in your Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. Review the metrics on the other tabs.

Clean up resources

When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:

  1. In the Azure portal, select Resource groups on the far left. If the left menu is collapsed, select Expand button to expand it.

  2. Select the resource group you created for this quickstart.

    Select the resource group to delete

  3. In the new window, select Delete resource group.

    Delete the resource group

  4. In the next window, enter the name of the resource group to delete, and then select Delete.

Next steps

In this quickstart, you've learned how to create an Azure Cosmos DB account, create a container using the Data Explorer, and run an app. You can now import additional data to your Cosmos DB account.