Azure Cosmos DB SDK Reference

This section provides comprehensive reference documentation for the Azure Cosmos DB Software Development Kits (SDKs) across various programming languages. Learn how to integrate Cosmos DB into your applications efficiently and effectively.

Overview

Azure Cosmos DB is a globally distributed, multi-model database service. The SDKs provide a robust and convenient way to interact with your Cosmos DB accounts. They offer features like:

Choose the SDK that best fits your application's technology stack.

.NET SDK

The .NET SDK allows you to work with Azure Cosmos DB using C# and other .NET languages. It's designed for high performance and ease of use.

Key Classes

  • CosmosClient: The primary client for interacting with Cosmos DB.
  • Container: Represents a container within a database.
  • ItemResponse<T>: Represents the response from an item operation.

Getting Started

Install the NuGet package:

dotnet add package Microsoft.Azure.Cosmos

Example: Creating an item

C#

using Microsoft.Azure.Cosmos;

// ...

CosmosClient client = new CosmosClient("YOUR_COSMOS_DB_CONNECTION_STRING");
Database database = await client.CreateDatabaseIfNotExistsAsync("myDatabase");
Container container = await database.CreateContainerIfNotExistsAsync("myContainer", "/partitionKey");

var newItem = new { id = "1", category = "gear-1", name = "Mountain Bike", price = 500 };
ItemResponse<dynamic> response = await container.CreateItemAsync(newItem, new PartitionKey("gear-1"));

Console.WriteLine($"Created item with ID: {response.Resource.id}");
                

For more details, refer to the official .NET SDK documentation.

Java SDK

The Java SDK enables Java developers to leverage the power of Azure Cosmos DB.

Key Classes

  • CosmosClient: Entry point for all Cosmos DB operations.
  • CosmosContainer: Represents a container.
  • CosmosResponse<T>: Generic response object.

Getting Started

Add the dependency to your pom.xml:


<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-cosmos</artifactId>
    <version>4.x.x</version>
</dependency>
                

Example: Querying items

Java

import com.azure.cosmos.*;
import com.azure.cosmos.models.*;

// ...

CosmosClient client = new CosmosClient("YOUR_COSMOS_DB_CONNECTION_STRING");
CosmosDatabase database = client.getDatabase("myDatabase");
CosmosContainer container = database.getContainer("myContainer");

String queryText = "SELECT * FROM c WHERE c.category = 'gear-1'";
CosmosPagedIterable<Product> results = container.queryItems(queryText, new CosmosQueryRequestOptions(), Product.class);

for (Product item : results) {
    System.out.println("Item: " + item.getId());
}
                

For more details, refer to the official Java SDK documentation.

Node.js SDK

The Node.js SDK is designed for building scalable, real-time applications using JavaScript or TypeScript.

Key Classes

  • CosmosClient: The main client object.
  • Container: Represents a Cosmos DB container.
  • ItemResponse<T>: Response for item operations.

Getting Started

Install the package:

npm install @azure/cosmos

Example: Upserting an item

JavaScript

const { CosmosClient } = require("@azure/cosmos");

// ...

const client = new CosmosClient("YOUR_COSMOS_DB_CONNECTION_STRING");
const database = client.database("myDatabase");
const container = database.container("myContainer");

const newItem = { id: "2", category: "gear-2", name: "Tent", price: 200 };
const response = await container.upsertItem(newItem);

console.log(`Upserted item with ID: ${response.resource.id}`);
                

For more details, refer to the official Node.js SDK documentation.

Python SDK

The Python SDK provides a straightforward way to interact with Cosmos DB for Python developers.

Key Classes

  • CosmosClient: For connecting to your Cosmos DB account.
  • ContainerProxy: Interface for container operations.
  • ItemResponse<T>: Response object for item-level operations.

Getting Started

Install the package:

pip install azure-cosmos

Example: Reading an item

Python

from azure.cosmos import CosmosClient

# ...

client = CosmosClient("YOUR_COSMOS_DB_CONNECTION_STRING")
database = client.get_database_client("myDatabase")
container = database.get_container_client("myContainer")

item_id = "1"
partition_key = "gear-1"
item = container.read_item(item_id, partition_key=partition_key)

print(f"Read item: {item['name']}")
                

For more details, refer to the official Python SDK documentation.

JavaScript SDK (Browser)

The JavaScript SDK can be used directly in browser-based applications.

Key Classes

  • CosmosClient: For initializing the client.
  • Container: Interface for container operations.

Getting Started

Include the library in your HTML:


<script src="https://unpkg.com/@azure/cosmos@4.x.x/dist/browser/cosmos.min.js"></script>
                

Example: Creating a document

JavaScript

const endpoint = "YOUR_COSMOS_DB_ENDPOINT";
const key = "YOUR_COSMOS_DB_KEY";
const databaseId = "myDatabase";
const containerId = "myContainer";

const client = new CosmosClient({ endpoint, key });
const container = client.database(databaseId).container(containerId);

async function createDocument() {
    const newItem = { id: "3", category: "gear-3", name: "Backpack", price: 75 };
    const response = await container.items.create(newItem);
    console.log(`Created item: ${response.resource.id}`);
}

createDocument();
                

For more details, refer to the official JavaScript SDK documentation.

Go SDK

The Go SDK is built for high-performance, concurrent applications in Go.

Key Structs

  • Client: The main client object.
  • Container: Represents a Cosmos DB container.
  • ItemResponse: Response structure for item operations.

Getting Started

Install the module:

go get github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos

Example: Creating a client

Go

package main

import (
	"fmt"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	credential, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("Failed to create credential: %v", err)
	}

	client, err := azcosmos.NewClient("YOUR_COSMOS_DB_ENDPOINT", credential, nil)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	fmt.Println("Cosmos DB client created successfully.")
}
                

For more details, refer to the official Go SDK documentation.

REST API

For scenarios where SDKs are not suitable or for advanced control, you can directly interact with the Cosmos DB REST API.

Key Operations

  • GET /dbs/{db_id}/colls/{coll_id}/docs: Query documents.
  • POST /dbs/{db_id}/colls/{coll_id}/docs: Create a document.
  • GET /dbs/{db_id}/colls/{coll_id}/docs/{doc_id}: Read a document.

Authentication

Requests are authenticated using the master key or resource tokens.

For more details, refer to the Cosmos DB REST API reference.