Quickstart: Azure Cosmos DB for NoSQL client library for Python

APPLIES TO: NoSQL

Get started with the Azure Cosmos DB client library for Python to create databases, containers, and items within your account. Follow these steps to install the package and try out example code for basic tasks.

Note

The example code snippets are available on GitHub as a .NET project.

API reference documentation | Library source code | Package (PyPI) | Samples

Prerequisites

Prerequisite check

  • In a terminal or command window, run python --version to check that the .NET SDK is version 3.7 or later.
  • Run az --version (Azure CLI) or Get-Module -ListAvailable AzureRM (Azure PowerShell) to check that you have the appropriate Azure command-line tools installed.

Setting up

This section walks you through creating an Azure Cosmos DB account and setting up a project that uses Azure Cosmos DB for NoSQL client library for .NET to manage resources.

Create an Azure Cosmos DB account

Tip

No Azure subscription? You can try Azure Cosmos DB free with no credit card required. If you create an account using the free trial, you can safely skip ahead to the Create a new Python app section.

This quickstart will create a single Azure Cosmos DB account using the API for NoSQL.

Tip

For this quickstart, we recommend using the resource group name msdocs-cosmos-quickstart-rg.

  1. Sign in to the Azure portal.

  2. From the Azure portal menu or the Home page, select Create a resource.

  3. On the New page, search for and select Azure Cosmos DB.

  4. On the Select API option page, select the Create option within the NoSQL section. Azure Cosmos DB has six APIs: NoSQL, MongoDB, PostgreSQL, Apache Cassandra, Apache Gremlin, and Table. Learn more about the API for NoSQL.

    Screenshot of select API option page for Azure Cosmos DB.

  5. On the Create Azure Cosmos DB Account page, enter the following information:

    Setting Value Description
    Subscription Subscription name Select the Azure subscription that you wish to use for this Azure Cosmos account.
    Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group.
    Account Name A unique name Enter a name to identify your Azure Cosmos account. The name will be used as part of a fully qualified domain name (FQDN) with a suffix of documents.azure.com, so the name must be globally unique. The name can only contain lowercase letters, numbers, and the hyphen (-) character. The name must also be between 3-44 characters in length.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.
    Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.
    Apply Azure Cosmos DB free tier discount Apply or Do not apply Enable Azure Cosmos DB free tier. With Azure Cosmos DB free tier, you'll get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier.

    Note

    You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    Screenshot of new account page for API for NoSQL.

  6. Select Review + create.

  7. Review the settings you provide, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete before moving on.

  8. Select Go to resource to go to the Azure Cosmos DB account page.

    Screenshot of deployment page for API for NoSQL resource.

  9. From the API for NoSQL account page, select the Keys navigation menu option.

    Screenshot of an API for NoSQL account page. The Keys option is highlighted in the navigation menu.

  10. Record the values from the URI and PRIMARY KEY fields. You'll use these values in a later step.

    Screenshot of Keys page with various credentials for an API for NoSQL account.

Create a new Python app

Create a new Python code file (app.py) in an empty folder using your preferred integrated development environment (IDE).

Install the package

Add the azure-cosmos PyPI package to the Python app. Use the pip install command to install the package.

pip install azure-cosmos

Configure environment variables

To use the URI and PRIMARY KEY values within your code, persist them to new environment variables on the local machine running the application. To set the environment variable, use your preferred terminal to run the following commands:

$env:COSMOS_ENDPOINT = "<cosmos-account-URI>"
$env:COSMOS_KEY = "<cosmos-account-PRIMARY-KEY>"

Object model

Before you start building the application, let's look into the hierarchy of resources in Azure Cosmos DB. Azure Cosmos DB has a specific object model used to create and access resources. The Azure Cosmos DB creates resources in a hierarchy that consists of accounts, databases, containers, and items.

Diagram of the Azure Cosmos DB hierarchy including accounts, databases, containers, and items.

Hierarchical diagram showing an Azure Cosmos DB account at the top. The account has two child database nodes. One of the database nodes includes two child container nodes. The other database node includes a single child container node. That single container node has three child item nodes.

For more information about the hierarchy of different resources, see working with databases, containers, and items in Azure Cosmos DB.

You'll use the following Python classes to interact with these resources:

  • CosmosClient - This class provides a client-side logical representation for the Azure Cosmos DB service. The client object is used to configure and execute requests against the service.
  • DatabaseProxy - This class is a reference to a database that may, or may not, exist in the service yet. The database is validated server-side when you attempt to access it or perform an operation against it.
  • ContainerProxy - This class is a reference to a container that also may not exist in the service yet. The container is validated server-side when you attempt to work with it.

Code examples

The sample code described in this article creates a database named adventureworks with a container named products. The products table is designed to contain product details such as name, category, quantity, and a sale indicator. Each product also contains a unique identifier.

For this sample code, the container will use the category as a logical partition key.

Authenticate the client

From the project directory, open the app.py file. In your editor, import the os and json modules. Then, import the CosmosClient and PartitionKey classes from the azure.cosmos module.

import os
import json
from azure.cosmos import CosmosClient, PartitionKey

Create variables for the COSMOS_ENDPOINT and COSMOS_KEY environment variables using os.environ.

endpoint = os.environ["COSMOS_ENDPOINT"]
key = os.environ["COSMOS_KEY"]

Create a new client instance using the CosmosClient class constructor and the two variables you created as parameters.

client = CosmosClient(url=endpoint, credential=key)

Create a database

Use the CosmosClient.create_database_if_not_exists method to create a new database if it doesn't already exist. This method will return a DatabaseProxy reference to the existing or newly created database.

database = client.create_database_if_not_exists(id="cosmicworks")

Create a container

The PartitionKey class defines a partition key path that you can use when creating a container.

partitionKeyPath = PartitionKey(path="/categoryId")

The Databaseproxy.create_container_if_not_exists method will create a new container if it doesn't already exist. This method will also return a ContainerProxy reference to the container.

container = database.create_container_if_not_exists(
    id="products", partition_key=partitionKeyPath, offer_throughput=400
)

Create an item

Create a new item in the container by first creating a new variable (newItem) with a sample item defined. In this example, the unique identifier of this item is 70b63682-b93a-4c77-aad2-65501347265f. The partition key value is derived from the /categoryId path, so it would be 61dba35b-4f02-45c5-b648-c6badc0cbd79.

newItem = {
    "id": "70b63682-b93a-4c77-aad2-65501347265f",
    "categoryId": "61dba35b-4f02-45c5-b648-c6badc0cbd79",
    "categoryName": "gear-surf-surfboards",
    "name": "Yamba Surfboard",
    "quantity": 12,
    "sale": False,
}

Tip

The remaining fields are flexible and you can define as many or as few as you want. You can even combine different item schemas in the same container.

Create an item in the container by using the ContainerProxy.create_item method passing in the variable you already created.

container.create_item(newItem)

Get an item

In Azure Cosmos DB, you can perform a point read operation by using both the unique identifier (id) and partition key fields. In the SDK, call [ContainerProxy.read_item](/python/api/azure-cosmos/azure.cosmos.containerproxy#azure-cosmos-containerproxy-read-item) passing in both values to return an item as a dictionary of strings and values (dict[str, Any]`).

existingItem = container.read_item(
    item="70b63682-b93a-4c77-aad2-65501347265f",
    partition_key="61dba35b-4f02-45c5-b648-c6badc0cbd79",
)

In this example, the dictionary result is saved to a variable named existingItem.

Query items

After you insert an item, you can run a query to get all items that match a specific filter. This example runs the SQL query: SELECT * FROM products p WHERE p.categoryId = "61dba35b-4f02-45c5-b648-c6badc0cbd79". This example uses query parameterization to construct the query. The query uses a string of the SQL query, and a dictionary of query parameters.

QUERY = "SELECT * FROM products p WHERE p.categoryId = @categoryId"
CATEGORYID = "61dba35b-4f02-45c5-b648-c6badc0cbd79"
params = [dict(name="@categoryId", value=CATEGORYID)]

This example dictionary included the @categoryId query parameter and the corresponding value 61dba35b-4f02-45c5-b648-c6badc0cbd79.

Once the query is defined, call ContainerProxy.query_items to run the query and return the results as a paged set of items (ItemPage[Dict[str, Any]]).

items = container.query_items(
    query=QUERY, parameters=params, enable_cross_partition_query=False
)

Finally, use a for loop to iterate over the results in each page and perform various actions.

for item in items:
    print(json.dumps(item, indent=True))

In this example, json.dumps is used to print the item to the console in a human-readable way.

Run the code

This app creates an API for NoSQL database and container. The example then creates an item and then reads the exact same item back. Finally, the example issues a query that should only return that single item. At the final step, the example outputs the final item to the console.

Use a terminal to navigate to the application directory and run the application.

python app.py

The output of the app should be similar to this example:

{
  "id": "70b63682-b93a-4c77-aad2-65501347265f",
  "categoryId": "61dba35b-4f02-45c5-b648-c6badc0cbd79",
  "categoryName": "gear-surf-surfboards",
  "name": "Yamba Surfboard",
  "quantity": 12,
  "sale": false,
  "_rid": "yzN6AIfJxe0BAAAAAAAAAA==",
  "_self": "dbs/yzN6AA==/colls/yzN6AIfJxe0=/docs/yzN6AIfJxe0BAAAAAAAAAA==/",
  "_etag": "\"2a00ccd4-0000-0200-0000-63650e420000\"",
  "_attachments": "attachments/",
  "_ts": 16457527130
}

Note

The fields assigned by Azure Cosmos DB (ex. ) will vary from this sample output.

Clean up resources

When you no longer need the API for NoSQL account, you can delete the corresponding resource group.

  1. Navigate to the resource group you previously created in the Azure portal.

    Tip

    In this quickstart, we recommended the name msdocs-cosmos-quickstart-rg.

  2. Select Delete resource group.

    Screenshot of the Delete resource group option in the navigation bar for a resource group.

  3. On the Are you sure you want to delete dialog, enter the name of the resource group, and then select Delete.

    Screenshot of the delete confirmation page for a resource group.

Next steps

In this quickstart, you learned how to create an Azure Cosmos DB for NoSQL account, create a database, and create a container using the Python SDK. You can now dive deeper into guidance on how to import your data into the API for NoSQL.