Connect to Azure Cosmos DB
This tutorial will guide you through the process of connecting your application to an Azure Cosmos DB database. We'll cover different methods and provide code examples for common scenarios.
Prerequisites
- An Azure subscription.
- An Azure Cosmos DB account. If you don't have one, you can create it from the previous tutorial.
- The connection string for your Cosmos DB account. You can find this in the Azure portal under your Cosmos DB account's "Keys" section.
Connecting using the .NET SDK
The Azure Cosmos DB .NET SDK provides a robust way to interact with your database. Here's how to initialize the client.
Step 1: Install the NuGet package
Use the NuGet Package Manager or the .NET CLI to install the SDK:
dotnet add package Microsoft.Azure.Cosmos
Step 2: Initialize the CosmosClient
Replace YOUR_COSMOS_DB_ENDPOINT
and YOUR_COSMOS_DB_KEY
with your actual endpoint and key.
using Microsoft.Azure.Cosmos;
using System;
using System.Threading.Tasks;
public class CosmosDbConnector
{
private readonly CosmosClient _cosmosClient;
private readonly string _databaseId = "YourDatabaseId"; // Replace with your database ID
public CosmosDbConnector(string endpoint, string key)
{
_cosmosClient = new CosmosClient(endpoint, key, new CosmosClientOptions
{
ApplicationName = "CosmosDbConnectorApp"
});
}
public async Task InitializeAsync()
{
// Create database if it doesn't exist
var databaseResponse = await _cosmosClient.CreateDatabaseIfNotExistsAsync(_databaseId);
Console.WriteLine($"Database '{databaseResponse.Resource.Id}' created or already exists.");
// You can also create containers here if needed
// await databaseResponse.Resource.CreateContainerIfNotExistsAsync("YourContainerId", "/yourPartitionKey");
}
public CosmosClient GetClient()
{
return _cosmosClient;
}
public async Task CloseAsync()
{
await _cosmosClient.DisposeAsync();
}
public static async Task Main(string[] args)
{
string endpoint = "YOUR_COSMOS_DB_ENDPOINT";
string key = "YOUR_COSMOS_DB_KEY";
if (string.IsNullOrEmpty(endpoint) || string.IsNullOrEmpty(key) || endpoint.Contains("YOUR_") || key.Contains("YOUR_"))
{
Console.WriteLine("Please replace 'YOUR_COSMOS_DB_ENDPOINT' and 'YOUR_COSMOS_DB_KEY' with your actual credentials.");
return;
}
var connector = new CosmosDbConnector(endpoint, key);
try
{
await connector.InitializeAsync();
var client = connector.GetClient();
Console.WriteLine("Successfully connected to Azure Cosmos DB!");
// Now you can use 'client' to interact with your database and containers.
// Example: List databases
var databases = client.GetDatabaseQueryIterator();
Console.WriteLine("Databases in your account:");
await foreach (var db in databases.ReadNextAsync())
{
Console.WriteLine($"- {db.Id}");
}
}
catch (CosmosException ex)
{
Console.WriteLine($"Cosmos DB error: {ex.StatusCode} - {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
finally
{
await connector.CloseAsync();
Console.WriteLine("Connection closed.");
}
}
}
Connecting using the Node.js SDK
For Node.js applications, you can use the @azure/cosmos
package.
Step 1: Install the npm package
npm install @azure/cosmos
Step 2: Initialize the CosmosClient
Replace YOUR_COSMOS_DB_ENDPOINT
and YOUR_COSMOS_DB_KEY
with your actual endpoint and key.
const { CosmosClient } = require("@azure/cosmos");
const endpoint = "YOUR_COSMOS_DB_ENDPOINT";
const key = "YOUR_COSMOS_DB_KEY";
const databaseId = "YourDatabaseId"; // Replace with your database ID
if (!endpoint || endpoint.includes("YOUR_") || !key || key.includes("YOUR_")) {
console.error("Please set the COSMOS_ENDPOINT and COSMOS_KEY environment variables or replace the placeholders.");
process.exit(1);
}
const client = new CosmosClient({ endpoint, key });
async function initializeDatabase() {
try {
const { database } = await client.databases.createIfNotExists({ id: databaseId });
console.log(`Database '${database.id}' created or already exists.`);
// You can also create containers here
// const { container } = await database.containers.createIfNotExists({ id: "YourContainerId", partitionKey: { paths: ["/yourPartitionKey"] } });
// console.log(`Container '${container.id}' created or already exists.`);
console.log("Successfully connected to Azure Cosmos DB!");
return database;
} catch (error) {
console.error("Error connecting to Azure Cosmos DB:", error);
throw error;
}
}
// Example usage:
async function main() {
try {
await initializeDatabase();
// Now you can use the 'client' object to perform operations.
// Example: List databases
console.log("Databases in your account:");
const { databases } = await client.databases.readAll().fetchAll();
databases.forEach(db => console.log(`- ${db.id}`));
} catch (error) {
console.error("An error occurred:", error);
}
}
main();
Connecting using the Python SDK
The Azure Cosmos DB Python SDK allows you to connect and manage your data.
Step 1: Install the package
pip install azure-cosmos
Step 2: Initialize the CosmosClient
Replace YOUR_COSMOS_DB_ENDPOINT
and YOUR_COSMOS_DB_KEY
with your actual endpoint and key.
import os
from azure.cosmos import CosmosClient, PartitionKey
from azure.cosmos.exceptions import CosmosHttpResponseError
endpoint = "YOUR_COSMOS_DB_ENDPOINT"
key = "YOUR_COSMOS_DB_KEY"
database_id = "YourDatabaseId" # Replace with your database ID
if "YOUR_COSMOS_DB_ENDPOINT" in endpoint or "YOUR_COSMOS_DB_KEY" in key:
print("Please replace 'YOUR_COSMOS_DB_ENDPOINT' and 'YOUR_COSMOS_DB_KEY' with your actual credentials.")
exit()
try:
# Initialize the Cosmos client
client = CosmosClient(endpoint, key)
print("Successfully initialized CosmosClient.")
# Create database if it doesn't exist
database = client.create_database_if_not_exists(id=database_id)
print(f"Database '{database.id}' created or already exists.")
# You can also create containers here
# container_id = "YourContainerId"
# partition_key_path = "/yourPartitionKey"
# container = database.create_container_if_not_exists(id=container_id, partition_key=PartitionKey(path=partition_key_path))
# print(f"Container '{container.id}' created or already exists.")
# List databases
print("Databases in your account:")
for db in client.list_databases():
print(f"- {db['id']}")
except CosmosHttpResponseError as e:
print(f"Cosmos DB Error: Status {e.status_code}, Message: {e.message}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
# The CosmosClient does not need explicit closing in typical Python applications
# as it manages connections automatically. For long-running services,
# consider resource management if needed.
print("Connection attempt finished.")
Connection String Format
A typical Azure Cosmos DB connection string looks like this:
AccountEndpoint=https://your-cosmos-db-account-name.documents.azure.com:443/;AccountKey=your_account_key;
You can find your Account Endpoint and Account Key in the Azure portal under your Cosmos DB account's "Keys" section.
Next Steps
Now that you know how to connect, you're ready to start interacting with your data: